Debian Codegraph @

debian/rust-vendor/icu_segmenter/tests/cnn/helper.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use core::ops::Range;
6 #[allow(unused_imports)]
7 use core_maths::*;
8 use std::vec;
9 use std::vec::Vec;
10 use zerovec::ZeroSlice;
11 use zerovec::ule::AsULE;
12
13 /// A `D`-dimensional, heap-allocated matrix.
14 ///
15 /// This matrix implementation supports slicing matrices into tightly-packed
16 /// submatrices. For example, indexing into a matrix of size 5x4x3 returns a
17 /// matrix of size 4x3. For more information, see [`MatrixOwned::submatrix`].
18 #[derive(Debug, Clone)]
19 pub(super) struct MatrixOwned<const D: usize> {
20 data: Vec<f32>,
21 dims: [usize; D],
22 }
23
24 impl<const D: usize> MatrixOwned<D> {
25 pub(super) fn as_borrowed(&self) -> MatrixBorrowed<'_, D> {
26 MatrixBorrowed {
27 data: &self.data,
28 dims: self.dims,
29 }
30 }
31
32 #[cfg(test)]
33 pub fn as_flat_slice(&self) -> &[f32] {
34 &self.data
35 }
36
37 pub(super) fn new_zero(dims: [usize; D]) -> Self {
38 let total_len = dims.iter().product::<usize>();
39 MatrixOwned {
40 data: vec![0.0; total_len],
41 dims,
42 }
43 }
44
45 /// Returns the tightly packed submatrix at _index_, or `None` if _index_ is out of range.
46 ///
47 /// For example, if the matrix is 5x4x3, this function returns a matrix sized 4x3. If the
48 /// matrix is 4x3, then this function returns a linear matrix of length 3.
49 ///
50 /// The type parameter `M` should be `D - 1`.
51 // #[inline]
52 // pub(super) fn submatrix<const M: usize>(&self, index: usize) -> Option<MatrixBorrowed<'_, M>> {
53 // // This assertion is based on const generics; it should always succeed and be elided.
54 // assert_eq!(M, D - 1);
55 // let (range, dims) = self.as_borrowed().submatrix_range(index);
56 // let data = &self.data.get(range)?;
57 // Some(MatrixBorrowed { data, dims })
58 // }
59 pub(super) fn as_mut(&mut self) -> MatrixBorrowedMut<'_, D> {
60 MatrixBorrowedMut {
61 data: &mut self.data,
62 dims: self.dims,
63 }
64 }
65
66 /// A mutable version of [`Self::submatrix`].
67 #[inline]
68 pub(super) fn submatrix_mut<const M: usize>(
69 &mut self,
70 index: usize,
71 ) -> Option<MatrixBorrowedMut<'_, M>> {
72 // This assertion is based on const generics; it should always succeed and be elided.
73 assert_eq!(M, D - 1);
74 let (range, dims) = self.as_borrowed().submatrix_range(index);
75 let data = self.data.get_mut(range)?;
76 Some(MatrixBorrowedMut { data, dims })
77 }
78 }
79
80 /// A `D`-dimensional, borrowed matrix.
81 #[derive(Debug, Clone, Copy)]
82 pub(super) struct MatrixBorrowed<'a, const D: usize> {
83 data: &'a [f32],
84 dims: [usize; D],
85 }
86
87 impl<'a, const D: usize> MatrixBorrowed<'a, D> {
88 #[cfg(debug_assertions)]
89 #[allow(dead_code)]
90 pub(super) fn debug_assert_dims(&self, dims: [usize; D]) {
91 debug_assert_eq!(dims, self.dims);
92 let expected_len = dims.iter().product::<usize>();
93 debug_assert_eq!(expected_len, self.data.len());
94 }
95
96 pub(super) fn as_slice(&self) -> &'a [f32] {
97 self.data
98 }
99
100 /// See [`MatrixOwned::submatrix`].
101 #[inline]
102 pub(super) fn submatrix<const M: usize>(&self, index: usize) -> Option<MatrixBorrowed<'a, M>> {
103 // This assertion is based on const generics; it should always succeed and be elided.
104 assert_eq!(M, D - 1);
105 let (range, dims) = self.submatrix_range(index);
106 let data = &self.data.get(range)?;
107 Some(MatrixBorrowed { data, dims })
108 }
109
110 #[inline]
111 fn submatrix_range<const M: usize>(&self, index: usize) -> (Range<usize>, [usize; M]) {
112 // This assertion is based on const generics; it should always succeed and be elided.
113 assert_eq!(M, D - 1);
114 // The above assertion guarantees that the following line will succeed
115 #[expect(clippy::unwrap_used)]
116 let sub_dims: [usize; M] = self.dims[1..].try_into().unwrap();
117 let n = sub_dims.iter().product::<usize>();
118 (n * index..n * (index + 1), sub_dims)
119 }
120 }
121
122 macro_rules! impl_basic_dim {
123 ($t1:path, $t2:path, $t3:path) => {
124 impl $t1 {
125 #[allow(dead_code)]
126 pub(super) fn dim(&self) -> usize {
127 let [dim] = self.dims;
128 dim
129 }
130 }
131 impl $t2 {
132 #[allow(dead_code)]
133 pub(super) fn dim(&self) -> (usize, usize) {
134 let [d0, d1] = self.dims;
135 (d0, d1)
136 }
137 }
138 impl $t3 {
139 #[allow(dead_code)]
140 pub(super) fn dim(&self) -> (usize, usize, usize) {
141 let [d0, d1, d2] = self.dims;
142 (d0, d1, d2)
143 }
144 }
145 };
146 }
147
148 impl_basic_dim!(MatrixOwned<1>, MatrixOwned<2>, MatrixOwned<3>);
149 impl_basic_dim!(
150 MatrixBorrowed<'_, 1>,
151 MatrixBorrowed<'_, 2>,
152 MatrixBorrowed<'_, 3>
153 );
154 impl_basic_dim!(
155 MatrixBorrowedMut<'_, 1>,
156 MatrixBorrowedMut<'_, 2>,
157 MatrixBorrowedMut<'_, 3>
158 );
159 impl_basic_dim!(MatrixZero<'_, 1>, MatrixZero<'_, 2>, MatrixZero<'_, 3>);
160
161 /// A `D`-dimensional, mutably borrowed matrix.
162 pub(super) struct MatrixBorrowedMut<'a, const D: usize> {
163 pub(super) data: &'a mut [f32],
164 pub(super) dims: [usize; D],
165 }
166
167 impl<const D: usize> MatrixBorrowedMut<'_, D> {
168 pub(super) fn as_borrowed(&self) -> MatrixBorrowed<'_, D> {
169 MatrixBorrowed {
170 data: self.data,
171 dims: self.dims,
172 }
173 }
174
175 pub(super) fn as_mut_slice(&mut self) -> &mut [f32] {
176 self.data
177 }
178
179 #[allow(dead_code)]
180 pub(super) fn copy_submatrix<const M: usize>(&mut self, from: usize, to: usize) {
181 let (range_from, _) = self.as_borrowed().submatrix_range::<M>(from);
182 let (range_to, _) = self.as_borrowed().submatrix_range::<M>(to);
183 if let (Some(_), Some(_)) = (
184 self.data.get(range_from.clone()),
185 self.data.get(range_to.clone()),
186 ) {
187 // This function is panicky, but we just validated the ranges
188 self.data.copy_within(range_from, range_to.start);
189 }
190 }
191
192 // #[must_use]
193 #[allow(dead_code)]
194 pub(super) fn add(&mut self, other: MatrixZero<'_, D>) -> Option<()> {
195 debug_assert_eq!(self.dims, other.dims);
196 // TODO: Vectorize?
197 for i in 0..self.data.len() {
198 *self.data.get_mut(i)? += other.data.get(i)?;
199 }
200 Some(())
201 }
202
203 #[allow(dead_code)] // maybe needed for more complicated bies calculations
204 /// Mutates this matrix by applying a softmax transformation.
205 pub(super) fn softmax_transform(&mut self) {
206 for v in self.data.iter_mut() {
207 *v = v.exp();
208 }
209 let sm = 1.0 / self.data.iter().sum::<f32>();
210 for v in self.data.iter_mut() {
211 *v *= sm;
212 }
213 }
214
215 #[allow(dead_code)]
216 pub(super) fn sigmoid_transform(&mut self) {
217 for x in &mut self.data.iter_mut() {
218 *x = 1.0 / (1.0 + (-*x).exp());
219 }
220 }
221
222 #[allow(dead_code)]
223 pub(super) fn tanh_transform(&mut self) {
224 for x in &mut self.data.iter_mut() {
225 *x = x.tanh();
226 }
227 }
228
229 #[allow(dead_code)]
230 pub(super) fn convolve(
231 &mut self,
232 i: MatrixBorrowed<'_, D>,
233 c: MatrixBorrowed<'_, D>,
234 f: MatrixBorrowed<'_, D>,
235 ) {
236 let i = i.as_slice();
237 let c = c.as_slice();
238 let f = f.as_slice();
239 let len = self.data.len();
240 if len != i.len() || len != c.len() || len != f.len() {
241 debug_assert!(false, "LSTM matrices not the correct dimensions");
242 return;
243 }
244 for idx in 0..len {
245 // Safety: The lengths are all the same (checked above)
246 unsafe {
247 *self.data.get_unchecked_mut(idx) = i.get_unchecked(idx) * c.get_unchecked(idx)
248 + self.data.get_unchecked(idx) * f.get_unchecked(idx)
249 }
250 }
251 }
252
253 #[allow(dead_code)]
254 pub(super) fn mul_tanh(&mut self, o: MatrixBorrowed<'_, D>, c: MatrixBorrowed<'_, D>) {
255 let o = o.as_slice();
256 let c = c.as_slice();
257 let len = self.data.len();
258 if len != o.len() || len != c.len() {
259 debug_assert!(false, "LSTM matrices not the correct dimensions");
260 return;
261 }
262 for idx in 0..len {
263 // Safety: The lengths are all the same (checked above)
264 unsafe {
265 *self.data.get_unchecked_mut(idx) =
266 o.get_unchecked(idx) * c.get_unchecked(idx).tanh();
267 }
268 }
269 }
270 }
271
272 impl MatrixBorrowed<'_, 1> {
273 #[allow(dead_code)] // could be useful
274 pub(super) fn dot_1d(&self, other: MatrixZero<1>) -> f32 {
275 debug_assert_eq!(self.dims, other.dims);
276 unrolled_dot_1(self.data, other.data)
277 }
278 }
279
280 impl MatrixBorrowedMut<'_, 1> {
281 /// Calculate the dot product of a and b, adding the result to self.
282 ///
283 /// Note: For better dot product efficiency, if `b` is `MxN`, then `a` should be `N`;
284 /// this is the opposite of standard practice.
285 #[allow(dead_code)]
286 pub(super) fn add_dot_2d(&mut self, a: MatrixBorrowed<1>, b: MatrixZero<2>) {
287 let m = a.dim();
288 let n = self.as_borrowed().dim();
289 debug_assert_eq!(
290 m,
291 b.dim().1,
292 "dims: {:?}/{:?}/{:?}",
293 self.as_borrowed().dim(),
294 a.dim(),
295 b.dim()
296 );
297 debug_assert_eq!(
298 n,
299 b.dim().0,
300 "dims: {:?}/{:?}/{:?}",
301 self.as_borrowed().dim(),
302 a.dim(),
303 b.dim()
304 );
305 for i in 0..n {
306 if let (Some(dest), Some(b_sub)) = (self.as_mut_slice().get_mut(i), b.submatrix::<1>(i))
307 {
308 *dest += unrolled_dot_1(a.data, b_sub.data);
309 } else {
310 debug_assert!(false, "unreachable: dims checked above");
311 }
312 }
313 }
314 }
315
316 impl MatrixBorrowedMut<'_, 2> {
317 /// Calculate the dot product of a and b, adding the result to self.
318 ///
319 /// Self should be `MxN`; `a`, `O`; and `b`, `MxNxO`.
320 #[allow(dead_code)]
321 pub(super) fn add_dot_3d_1(&mut self, a: MatrixBorrowed<1>, b: MatrixZero<3>) {
322 let m = a.dim();
323 let n = self.as_borrowed().dim().0 * self.as_borrowed().dim().1;
324 debug_assert_eq!(
325 m,
326 b.dim().2,
327 "dims: {:?}/{:?}/{:?}",
328 self.as_borrowed().dim(),
329 a.dim(),
330 b.dim()
331 );
332 debug_assert_eq!(
333 n,
334 b.dim().0 * b.dim().1,
335 "dims: {:?}/{:?}/{:?}",
336 self.as_borrowed().dim(),
337 a.dim(),
338 b.dim()
339 );
340 // Note: The following two loops are equivalent, but the second has more opportunity for
341 // vectorization since it allows the vectorization to span submatrices.
342 // for i in 0..b.dim().0 {
343 // self.submatrix_mut::<1>(i).add_dot_2d(a, b.submatrix(i));
344 // }
345 let lhs = a.as_slice();
346 for i in 0..n {
347 if let (Some(dest), Some(rhs)) = (
348 self.as_mut_slice().get_mut(i),
349 b.as_slice().get_subslice(i * m..(i + 1) * m),
350 ) {
351 *dest += unrolled_dot_1(lhs, rhs);
352 } else {
353 debug_assert!(false, "unreachable: dims checked above");
354 }
355 }
356 }
357
358 /// Calculate the dot product of a and b, adding the result to self.
359 ///
360 /// Self should be `MxN`; `a`, `O`; and `b`, `MxNxO`.
361 #[allow(dead_code)]
362 pub(super) fn add_dot_3d_2(&mut self, a: MatrixZero<1>, b: MatrixZero<3>) {
363 let m = a.dim();
364 let n = self.as_borrowed().dim().0 * self.as_borrowed().dim().1;
365 debug_assert_eq!(
366 m,
367 b.dim().2,
368 "dims: {:?}/{:?}/{:?}",
369 self.as_borrowed().dim(),
370 a.dim(),
371 b.dim()
372 );
373 debug_assert_eq!(
374 n,
375 b.dim().0 * b.dim().1,
376 "dims: {:?}/{:?}/{:?}",
377 self.as_borrowed().dim(),
378 a.dim(),
379 b.dim()
380 );
381 // Note: The following two loops are equivalent, but the second has more opportunity for
382 // vectorization since it allows the vectorization to span submatrices.
383 // for i in 0..b.dim().0 {
384 // self.submatrix_mut::<1>(i).add_dot_2d(a, b.submatrix(i));
385 // }
386 let lhs = a.as_slice();
387 for i in 0..n {
388 if let (Some(dest), Some(rhs)) = (
389 self.as_mut_slice().get_mut(i),
390 b.as_slice().get_subslice(i * m..(i + 1) * m),
391 ) {
392 *dest += unrolled_dot_2(lhs, rhs);
393 } else {
394 debug_assert!(false, "unreachable: dims checked above");
395 }
396 }
397 }
398 }
399
400 /// A `D`-dimensional matrix borrowed from a [`ZeroSlice`].
401 #[derive(Debug, Clone, Copy)]
402 pub(super) struct MatrixZero<'a, const D: usize> {
403 data: &'a ZeroSlice<f32>,
404 dims: [usize; D],
405 }
406
407 // impl<'a> From<&'a super::provider::LstmMatrix1<'a>> for MatrixZero<'a, 1> {
408 // fn from(other: &'a super::provider::LstmMatrix1<'a>) -> Self {
409 // Self {
410 // data: &other.data,
411 // dims: other.dims.map(|x| x as usize),
412 // }
413 // }
414 // }
415
416 // impl<'a> From<&'a super::provider::LstmMatrix2<'a>> for MatrixZero<'a, 2> {
417 // fn from(other: &'a super::provider::LstmMatrix2<'a>) -> Self {
418 // Self {
419 // data: &other.data,
420 // dims: other.dims.map(|x| x as usize),
421 // }
422 // }
423 // }
424
425 // impl<'a> From<&'a super::provider::LstmMatrix3<'a>> for MatrixZero<'a, 3> {
426 // fn from(other: &'a super::provider::LstmMatrix3<'a>) -> Self {
427 // Self {
428 // data: &other.data,
429 // dims: other.dims.map(|x| x as usize),
430 // }
431 // }
432 // }
433
434 impl<'a> From<&'a super::CnnMatrix1<'a>> for MatrixZero<'a, 1> {
435 fn from(m: &'a super::CnnMatrix1<'a>) -> Self {
436 Self {
437 data: &m.data,
438 dims: m.dims.map(|x| x as usize),
439 }
440 }
441 }
442 impl<'a> From<&'a super::CnnMatrix2<'a>> for MatrixZero<'a, 2> {
443 fn from(m: &'a super::CnnMatrix2<'a>) -> Self {
444 Self {
445 data: &m.data,
446 dims: m.dims.map(|x| x as usize),
447 }
448 }
449 }
450 impl<'a> From<&'a super::CnnMatrix3<'a>> for MatrixZero<'a, 3> {
451 fn from(m: &'a super::CnnMatrix3<'a>) -> Self {
452 Self {
453 data: &m.data,
454 dims: m.dims.map(|x| x as usize),
455 }
456 }
457 }
458
459 impl<'a, const D: usize> MatrixZero<'a, D> {
460 // #[expect(clippy::wrong_self_convention)] // same convention as slice::to_vec
461 // pub(super) fn to_owned(&self) -> MatrixOwned<D> {
462 // MatrixOwned {
463 // data: self.data.iter().collect(),
464 // dims: self.dims,
465 // }
466 // }
467
468 pub(super) fn as_slice(&self) -> &ZeroSlice<f32> {
469 self.data
470 }
471
472 #[cfg(debug_assertions)]
473 #[allow(dead_code)]
474 pub(super) fn debug_assert_dims(&self, dims: [usize; D]) {
475 debug_assert_eq!(dims, self.dims);
476 let expected_len = dims.iter().product::<usize>();
477 debug_assert_eq!(expected_len, self.data.len());
478 }
479
480 /// See [`MatrixOwned::submatrix`].
481 #[inline]
482 pub(super) fn submatrix<const M: usize>(&self, index: usize) -> Option<MatrixZero<'a, M>> {
483 // This assertion is based on const generics; it should always succeed and be elided.
484 assert_eq!(M, D - 1);
485 let (range, dims) = self.submatrix_range(index);
486 let data = &self.data.get_subslice(range)?;
487 Some(MatrixZero { data, dims })
488 }
489
490 #[inline]
491 fn submatrix_range<const M: usize>(&self, index: usize) -> (Range<usize>, [usize; M]) {
492 // This assertion is based on const generics; it should always succeed and be elided.
493 assert_eq!(M, D - 1);
494 // The above assertion guarantees that the following line will succeed
495 #[expect(clippy::unwrap_used)]
496 let sub_dims: [usize; M] = self.dims[1..].try_into().unwrap();
497 let n = sub_dims.iter().product::<usize>();
498 (n * index..n * (index + 1), sub_dims)
499 }
500 }
501
502 macro_rules! f32c {
503 ($ule:expr) => {
504 f32::from_unaligned($ule)
505 };
506 }
507
508 /// Compute the dot product of an aligned and an unaligned f32 slice.
509 ///
510 /// `xs` and `ys` must be the same length
511 ///
512 /// (Based on ndarray 0.15.6)
513 fn unrolled_dot_1(xs: &[f32], ys: &ZeroSlice<f32>) -> f32 {
514 debug_assert_eq!(xs.len(), ys.len());
515 // eightfold unrolled so that floating point can be vectorized
516 // (even with strict floating point accuracy semantics)
517 let mut p = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
518 let xit = xs.chunks_exact(8);
519 let yit = ys.as_ule_slice().chunks_exact(8);
520 let sum = xit
521 .remainder()
522 .iter()
523 .zip(yit.remainder().iter())
524 .map(|(x, y)| x * f32c!(*y))
525 .sum::<f32>();
526 for (xx, yy) in xit.zip(yit) {
527 // TODO: Use array_chunks once stable to avoid the unwrap.
528 // <https://github.com/rust-lang/rust/issues/74985>
529 #[expect(clippy::unwrap_used)]
530 let [x0, x1, x2, x3, x4, x5, x6, x7] = *<&[f32; 8]>::try_from(xx).unwrap();
531 #[expect(clippy::unwrap_used)]
532 let [y0, y1, y2, y3, y4, y5, y6, y7] = *<&[<f32 as AsULE>::ULE; 8]>::try_from(yy).unwrap();
533 p.0 += x0 * f32c!(y0);
534 p.1 += x1 * f32c!(y1);
535 p.2 += x2 * f32c!(y2);
536 p.3 += x3 * f32c!(y3);
537 p.4 += x4 * f32c!(y4);
538 p.5 += x5 * f32c!(y5);
539 p.6 += x6 * f32c!(y6);
540 p.7 += x7 * f32c!(y7);
541 }
542 sum + (p.0 + p.4) + (p.1 + p.5) + (p.2 + p.6) + (p.3 + p.7)
543 }
544
545 /// Compute the dot product of two unaligned f32 slices.
546 ///
547 /// `xs` and `ys` must be the same length
548 ///
549 /// (Based on ndarray 0.15.6)
550 fn unrolled_dot_2(xs: &ZeroSlice<f32>, ys: &ZeroSlice<f32>) -> f32 {
551 debug_assert_eq!(xs.len(), ys.len());
552 // eightfold unrolled so that floating point can be vectorized
553 // (even with strict floating point accuracy semantics)
554 let mut p = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
555 let xit = xs.as_ule_slice().chunks_exact(8);
556 let yit = ys.as_ule_slice().chunks_exact(8);
557 let sum = xit
558 .remainder()
559 .iter()
560 .zip(yit.remainder().iter())
561 .map(|(x, y)| f32c!(*x) * f32c!(*y))
562 .sum::<f32>();
563 for (xx, yy) in xit.zip(yit) {
564 // TODO: Use array_chunks once stable to avoid the unwrap.
565 // <https://github.com/rust-lang/rust/issues/74985>
566 #[expect(clippy::unwrap_used)]
567 let [x0, x1, x2, x3, x4, x5, x6, x7] = *<&[<f32 as AsULE>::ULE; 8]>::try_from(xx).unwrap();
568 #[expect(clippy::unwrap_used)]
569 let [y0, y1, y2, y3, y4, y5, y6, y7] = *<&[<f32 as AsULE>::ULE; 8]>::try_from(yy).unwrap();
570 p.0 += f32c!(x0) * f32c!(y0);
571 p.1 += f32c!(x1) * f32c!(y1);
572 p.2 += f32c!(x2) * f32c!(y2);
573 p.3 += f32c!(x3) * f32c!(y3);
574 p.4 += f32c!(x4) * f32c!(y4);
575 p.5 += f32c!(x5) * f32c!(y5);
576 p.6 += f32c!(x6) * f32c!(y6);
577 p.7 += f32c!(x7) * f32c!(y7);
578 }
579 sum + (p.0 + p.4) + (p.1 + p.5) + (p.2 + p.6) + (p.3 + p.7)
580 }