Skip to main content

yscv_tensor/
ops.rs

1use super::aligned::AlignedVec;
2use super::error::TensorError;
3use super::shape::{
4    broadcast_offset, broadcast_shape, compute_strides, increment_coords, shape_element_count,
5};
6use super::simd;
7use super::tensor::Tensor;
8
9impl Tensor {
10    // ── Binary elementwise with broadcasting ────────────────────────────
11
12    /// Element-wise addition with NumPy-style broadcasting.
13    pub fn add(&self, rhs: &Self) -> Result<Self, TensorError> {
14        if self.shape() == rhs.shape() {
15            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Add);
16        }
17        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Add) {
18            return result;
19        }
20        self.binary_broadcast_op(rhs, |l, r| l + r)
21    }
22
23    /// Element-wise subtraction with NumPy-style broadcasting.
24    pub fn sub(&self, rhs: &Self) -> Result<Self, TensorError> {
25        if self.shape() == rhs.shape() {
26            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Sub);
27        }
28        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Sub) {
29            return result;
30        }
31        self.binary_broadcast_op(rhs, |l, r| l - r)
32    }
33
34    /// Element-wise multiplication with NumPy-style broadcasting.
35    pub fn mul(&self, rhs: &Self) -> Result<Self, TensorError> {
36        if self.shape() == rhs.shape() {
37            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Mul);
38        }
39        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Mul) {
40            return result;
41        }
42        self.binary_broadcast_op(rhs, |l, r| l * r)
43    }
44
45    /// Element-wise division with NumPy-style broadcasting.
46    pub fn div(&self, rhs: &Self) -> Result<Self, TensorError> {
47        if self.shape() == rhs.shape() {
48            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Div);
49        }
50        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Div) {
51            return result;
52        }
53        self.binary_broadcast_op(rhs, |l, r| l / r)
54    }
55
56    /// Element-wise power with NumPy-style broadcasting.
57    ///
58    /// Fast paths:
59    /// - Constant exponent 2.0 → `mul(x, x)` (SIMD-accelerated).
60    /// - Constant exponent 0.5 → `sqrt(x)` (SIMD-accelerated).
61    /// - Same-shape general case → SIMD `exp(exp * ln(base))`.
62    #[allow(unsafe_code)]
63    pub fn pow(&self, rhs: &Self) -> Result<Self, TensorError> {
64        // Fast path: constant exponent (O(1) check instead of O(N) scan).
65        // A single-element tensor or a tensor whose total size is 1 (broadcast scalar)
66        // is always constant.  For same-shape tensors we skip the all-equal scan
67        // entirely — the per-element SIMD path handles them efficiently.
68        let rhs_total: usize = rhs.shape().iter().product();
69        if rhs_total == 1 {
70            let exp_val = rhs.data()[0];
71            if exp_val == 2.0 {
72                return self.mul(self);
73            }
74            if exp_val == 0.5 {
75                return Ok(self.sqrt());
76            }
77            if exp_val == 1.0 {
78                return Ok(self.clone());
79            }
80            if exp_val == 0.0 {
81                return Tensor::ones(self.shape().to_vec());
82            }
83            if exp_val == -1.0 {
84                return Ok(self.reciprocal());
85            }
86        }
87        // Same-shape SIMD path: pow(base, exp) = exp(exp * ln(base))
88        if self.shape() == rhs.shape() {
89            return self.pow_simd(rhs);
90        }
91        self.binary_broadcast_op(rhs, |l, r| l.powf(r))
92    }
93
94    /// SIMD-accelerated pow for same-shape tensors via exp(exp * ln(base)).
95    #[allow(unsafe_code)]
96    fn pow_simd(&self, rhs: &Self) -> Result<Self, TensorError> {
97        let len = self.len();
98        // Compute ln(base)
99        let mut ln_buf = AlignedVec::<f32>::uninitialized(len);
100        simd::ln_dispatch(self.data(), &mut ln_buf);
101        // Multiply by exponent: exp_val * ln(base)
102        let mut prod_buf = AlignedVec::<f32>::uninitialized(len);
103        simd::binary_dispatch(&ln_buf, rhs.data(), &mut prod_buf, simd::BinaryKind::Mul);
104        // Compute exp(exp_val * ln(base))
105        let mut out = AlignedVec::<f32>::uninitialized(len);
106        simd::exp_dispatch(&prod_buf, &mut out);
107        Ok(Tensor::from_raw_parts(self.shape(), self.strides(), out))
108    }
109
110    /// Element-wise atan2(self, other), with broadcasting.
111    ///
112    /// Same-shape case uses a SIMD-friendly polynomial approximation of atan
113    /// with quadrant correction, avoiding scalar `f32::atan2`.
114    #[allow(unsafe_code)]
115    pub fn atan2(&self, rhs: &Self) -> Result<Self, TensorError> {
116        if self.shape() == rhs.shape() {
117            return self.atan2_fast(rhs);
118        }
119        self.binary_broadcast_op(rhs, f32::atan2)
120    }
121
122    /// Vectorized atan2 for same-shape tensors. Uses Cephes-style range
123    /// reduction to [0, tan(pi/12)] then a polynomial approximation,
124    /// giving < 1e-6 max error across all quadrants.
125    #[allow(unsafe_code)]
126    fn atan2_fast(&self, rhs: &Self) -> Result<Self, TensorError> {
127        let y_data = self.data();
128        let x_data = rhs.data();
129        let len = self.len();
130        let mut out = AlignedVec::<f32>::uninitialized(len);
131
132        // Process in chunks of 4 for ILP (instruction-level parallelism).
133        // Each call to the scalar fast path avoids the overhead of the
134        // generic broadcasting machinery.
135        let mut i = 0;
136        while i + 4 <= len {
137            out[i] = fast_atan2_scalar(y_data[i], x_data[i]);
138            out[i + 1] = fast_atan2_scalar(y_data[i + 1], x_data[i + 1]);
139            out[i + 2] = fast_atan2_scalar(y_data[i + 2], x_data[i + 2]);
140            out[i + 3] = fast_atan2_scalar(y_data[i + 3], x_data[i + 3]);
141            i += 4;
142        }
143        while i < len {
144            out[i] = fast_atan2_scalar(y_data[i], x_data[i]);
145            i += 1;
146        }
147
148        Ok(Tensor::from_raw_parts(self.shape(), self.strides(), out))
149    }
150
151    /// Element-wise minimum with NumPy-style broadcasting.
152    pub fn minimum(&self, rhs: &Self) -> Result<Self, TensorError> {
153        if self.shape() == rhs.shape() {
154            return self.binary_same_shape(rhs, f32::min);
155        }
156        self.binary_broadcast_op(rhs, f32::min)
157    }
158
159    /// Element-wise maximum with NumPy-style broadcasting.
160    pub fn maximum(&self, rhs: &Self) -> Result<Self, TensorError> {
161        if self.shape() == rhs.shape() {
162            return self.binary_same_shape(rhs, f32::max);
163        }
164        self.binary_broadcast_op(rhs, f32::max)
165    }
166
167    // ── Unary elementwise ───────────────────────────────────────────────
168
169    /// Element-wise negation.
170    pub fn neg(&self) -> Self {
171        self.unary_simd_op(simd::UnaryKind::Neg)
172    }
173
174    /// Element-wise absolute value.
175    pub fn abs(&self) -> Self {
176        self.unary_simd_op(simd::UnaryKind::Abs)
177    }
178
179    /// Element-wise natural exponential.
180    #[allow(unsafe_code)]
181    pub fn exp(&self) -> Self {
182        let len = self.len();
183        // SAFETY: `uninitialized` allocates without zeroing.  `exp_dispatch`
184        // writes every element before anything reads from `out`.
185        let mut out = AlignedVec::<f32>::uninitialized(len);
186        simd::exp_dispatch(self.data(), &mut out);
187        Tensor::from_raw_parts(self.shape(), self.strides(), out)
188    }
189
190    /// Element-wise natural logarithm.
191    #[allow(unsafe_code)]
192    pub fn ln(&self) -> Self {
193        let len = self.len();
194        // SAFETY: `uninitialized` allocates without zeroing.  `ln_dispatch`
195        // writes every element before we ever read from `out`.
196        let mut out = AlignedVec::<f32>::uninitialized(len);
197        simd::ln_dispatch(self.data(), &mut out);
198        Tensor::from_raw_parts(self.shape(), self.strides(), out)
199    }
200
201    /// Element-wise square root.
202    pub fn sqrt(&self) -> Self {
203        self.unary_simd_op(simd::UnaryKind::Sqrt)
204    }
205
206    /// Element-wise reciprocal (`1 / x`).
207    pub fn reciprocal(&self) -> Self {
208        self.unary_simd_op(simd::UnaryKind::Recip)
209    }
210
211    /// Element-wise sign (`-1`, `0`, or `1`).
212    pub fn sign(&self) -> Self {
213        self.unary_simd_op(simd::UnaryKind::Sign)
214    }
215
216    /// Element-wise floor.
217    pub fn floor(&self) -> Self {
218        self.unary_simd_op(simd::UnaryKind::Floor)
219    }
220
221    /// Element-wise ceil.
222    pub fn ceil(&self) -> Self {
223        self.unary_simd_op(simd::UnaryKind::Ceil)
224    }
225
226    /// Element-wise round.
227    pub fn round(&self) -> Self {
228        self.unary_simd_op(simd::UnaryKind::Round)
229    }
230
231    /// Element-wise sine (SIMD-accelerated polynomial approximation).
232    #[allow(unsafe_code)]
233    pub fn sin(&self) -> Self {
234        let len = self.len();
235        let mut out = AlignedVec::<f32>::uninitialized(len);
236        simd::sin_dispatch(self.data(), &mut out);
237        Tensor::from_raw_parts(self.shape(), self.strides(), out)
238    }
239
240    /// Element-wise cosine (SIMD-accelerated polynomial approximation).
241    #[allow(unsafe_code)]
242    pub fn cos(&self) -> Self {
243        let len = self.len();
244        let mut out = AlignedVec::<f32>::uninitialized(len);
245        simd::cos_dispatch(self.data(), &mut out);
246        Tensor::from_raw_parts(self.shape(), self.strides(), out)
247    }
248
249    /// Element-wise tangent (SIMD-accelerated via sin/cos).
250    #[allow(unsafe_code)]
251    pub fn tan(&self) -> Self {
252        let len = self.len();
253        let mut out = AlignedVec::<f32>::uninitialized(len);
254        simd::tan_dispatch(self.data(), &mut out);
255        Tensor::from_raw_parts(self.shape(), self.strides(), out)
256    }
257
258    /// Element-wise arcsine.
259    pub fn asin(&self) -> Self {
260        self.unary_op(f32::asin)
261    }
262
263    /// Element-wise arccosine.
264    pub fn acos(&self) -> Self {
265        self.unary_op(f32::acos)
266    }
267
268    /// Element-wise arctangent.
269    pub fn atan(&self) -> Self {
270        self.unary_op(f32::atan)
271    }
272
273    /// Element-wise hyperbolic sine.
274    pub fn sinh(&self) -> Self {
275        self.unary_op(f32::sinh)
276    }
277
278    /// Element-wise hyperbolic cosine.
279    pub fn cosh(&self) -> Self {
280        self.unary_op(f32::cosh)
281    }
282
283    /// Element-wise base-2 logarithm.
284    pub fn log2(&self) -> Self {
285        self.unary_op(f32::log2)
286    }
287
288    /// Element-wise base-10 logarithm.
289    pub fn log10(&self) -> Self {
290        self.unary_op(f32::log10)
291    }
292
293    /// Convert radians to degrees.
294    pub fn degrees(&self) -> Self {
295        self.unary_op(|v| v.to_degrees())
296    }
297
298    /// Convert degrees to radians.
299    pub fn radians(&self) -> Self {
300        self.unary_op(|v| v.to_radians())
301    }
302
303    /// Clamp all elements to `[min, max]`.
304    #[allow(unsafe_code)]
305    pub fn clamp(&self, min: f32, max: f32) -> Self {
306        let len = self.len();
307        let mut out = AlignedVec::<f32>::uninitialized(len);
308        simd::clamp_dispatch(self.data(), &mut out, min, max);
309        Tensor::from_raw_parts(self.shape(), self.strides(), out)
310    }
311
312    /// Scalar multiplication (broadcast multiply by a constant).
313    pub fn scale(&self, factor: f32) -> Self {
314        self.unary_op(|v| v * factor)
315    }
316
317    /// Add a scalar to all elements.
318    pub fn add_scalar(&self, value: f32) -> Self {
319        self.unary_op(|v| v + value)
320    }
321
322    // ── Reductions ──────────────────────────────────────────────────────
323
324    /// Sum reduction over all elements.
325    pub fn sum(&self) -> f32 {
326        simd::sum_dispatch(self.data())
327    }
328
329    /// Mean reduction over all elements.
330    pub fn mean(&self) -> f32 {
331        if self.is_empty() {
332            return f32::NAN;
333        }
334        self.sum() / self.len() as f32
335    }
336
337    /// Global max reduction. Returns `f32::NEG_INFINITY` for empty tensors.
338    pub fn max_value(&self) -> f32 {
339        simd::max_dispatch(self.data())
340    }
341
342    /// Global min reduction. Returns `f32::INFINITY` for empty tensors.
343    pub fn min_value(&self) -> f32 {
344        simd::min_dispatch(self.data())
345    }
346
347    /// Global argmax (flat index of maximum value).
348    pub fn argmax(&self) -> Option<usize> {
349        if self.is_empty() {
350            return None;
351        }
352        let mut best = 0;
353        let mut best_val = self.data()[0];
354        for (i, &v) in self.data().iter().enumerate().skip(1) {
355            if v > best_val {
356                best_val = v;
357                best = i;
358            }
359        }
360        Some(best)
361    }
362
363    /// Global argmin (flat index of minimum value).
364    pub fn argmin(&self) -> Option<usize> {
365        if self.is_empty() {
366            return None;
367        }
368        let mut best = 0;
369        let mut best_val = self.data()[0];
370        for (i, &v) in self.data().iter().enumerate().skip(1) {
371            if v < best_val {
372                best_val = v;
373                best = i;
374            }
375        }
376        Some(best)
377    }
378
379    /// Variance over all elements (population variance).
380    pub fn var(&self) -> f32 {
381        if self.is_empty() {
382            return f32::NAN;
383        }
384        let m = self.mean();
385        self.data().iter().map(|&v| (v - m) * (v - m)).sum::<f32>() / self.len() as f32
386    }
387
388    /// Standard deviation over all elements (population).
389    pub fn std_dev(&self) -> f32 {
390        self.var().sqrt()
391    }
392
393    /// Sum reduction over one axis. Reduced axis is removed from output shape.
394    pub fn sum_axis(&self, axis: usize) -> Result<Self, TensorError> {
395        let shape = self.shape();
396        let rank = shape.len();
397        if axis >= rank {
398            return Err(TensorError::InvalidAxis { axis, rank });
399        }
400
401        // Fast path: 2D contiguous tensor, axis 0 → accumulate rows with SIMD
402        if rank == 2 && axis == 0 {
403            let (rows, cols) = (shape[0], shape[1]);
404            let data = self.data();
405            let mut out = vec![0.0f32; cols];
406            for row in 0..rows {
407                let row_start = row * cols;
408                simd::add_inplace_dispatch(&mut out, &data[row_start..row_start + cols]);
409            }
410            return Self::from_vec(vec![cols], out);
411        }
412
413        // Fast path: 2D contiguous tensor, axis 1 → sum each row with SIMD
414        if rank == 2 && axis == 1 {
415            let (rows, cols) = (shape[0], shape[1]);
416            let data = self.data();
417            let mut out = Vec::with_capacity(rows);
418            for row in 0..rows {
419                out.push(simd::sum_dispatch(&data[row * cols..(row + 1) * cols]));
420            }
421            return Self::from_vec(vec![rows], out);
422        }
423
424        self.reduce_axis(axis, 0.0, |acc, v| acc + v)
425    }
426
427    /// Mean reduction over one axis. Reduced axis is removed from output shape.
428    pub fn mean_axis(&self, axis: usize) -> Result<Self, TensorError> {
429        if axis >= self.rank() {
430            return Err(TensorError::InvalidAxis {
431                axis,
432                rank: self.rank(),
433            });
434        }
435        let axis_len = self.shape()[axis] as f32;
436        let sum = self.sum_axis(axis)?;
437        Ok(sum.scale(1.0 / axis_len))
438    }
439
440    /// Max reduction over one axis. Reduced axis is removed from output shape.
441    pub fn max_axis(&self, axis: usize) -> Result<Self, TensorError> {
442        let shape = self.shape();
443        let rank = shape.len();
444        if axis >= rank {
445            return Err(TensorError::InvalidAxis { axis, rank });
446        }
447
448        // Fast path: 2D contiguous tensor, axis 0 → accumulate rows with SIMD max
449        if rank == 2 && axis == 0 {
450            let (rows, cols) = (shape[0], shape[1]);
451            let data = self.data();
452            let mut out = data[..cols].to_vec();
453            for row in 1..rows {
454                let row_start = row * cols;
455                simd::max_inplace_dispatch(&mut out, &data[row_start..row_start + cols]);
456            }
457            return Self::from_vec(vec![cols], out);
458        }
459
460        // Fast path: 2D contiguous tensor, axis 1 → max each row with SIMD
461        if rank == 2 && axis == 1 {
462            let (rows, cols) = (shape[0], shape[1]);
463            let data = self.data();
464            let mut out = Vec::with_capacity(rows);
465            for row in 0..rows {
466                out.push(simd::max_dispatch(&data[row * cols..(row + 1) * cols]));
467            }
468            return Self::from_vec(vec![rows], out);
469        }
470
471        self.reduce_axis(axis, f32::NEG_INFINITY, f32::max)
472    }
473
474    /// Min reduction over one axis. Reduced axis is removed from output shape.
475    pub fn min_axis(&self, axis: usize) -> Result<Self, TensorError> {
476        self.reduce_axis(axis, f32::INFINITY, f32::min)
477    }
478
479    /// Variance reduction over one axis (population variance).
480    pub fn var_axis(&self, axis: usize) -> Result<Self, TensorError> {
481        let m = self.mean_axis(axis)?;
482        let diff = self.sub(&m.unsqueeze(axis)?)?;
483        let sq = diff.mul(&diff)?;
484        sq.mean_axis(axis)
485    }
486
487    /// Global median of all elements.
488    pub fn median(&self) -> f32 {
489        let mut sorted = self.data().to_vec();
490        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
491        let n = sorted.len();
492        if n == 0 {
493            return 0.0;
494        }
495        if n % 2 == 1 {
496            sorted[n / 2]
497        } else {
498            (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
499        }
500    }
501
502    /// Median along a given axis.
503    pub fn median_axis(&self, axis: usize) -> Result<Self, TensorError> {
504        let shape = self.shape();
505        let rank = shape.len();
506        if axis >= rank {
507            return Err(TensorError::InvalidAxis { axis, rank });
508        }
509        let axis_len = shape[axis];
510        let outer: usize = shape[..axis].iter().product();
511        let inner: usize = shape[axis + 1..].iter().product();
512        let mut new_shape = shape.to_vec();
513        new_shape.remove(axis);
514        if new_shape.is_empty() {
515            new_shape.push(1);
516        }
517        let data = self.data();
518        let mut result = Vec::with_capacity(outer * inner);
519        for o in 0..outer {
520            for i in 0..inner {
521                let mut vals: Vec<f32> = (0..axis_len)
522                    .map(|a| data[o * axis_len * inner + a * inner + i])
523                    .collect();
524                vals.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
525                let n = vals.len();
526                let med = if n % 2 == 1 {
527                    vals[n / 2]
528                } else {
529                    (vals[n / 2 - 1] + vals[n / 2]) / 2.0
530                };
531                result.push(med);
532            }
533        }
534        Self::from_vec(new_shape, result)
535    }
536
537    /// Returns true if any element is non-zero.
538    pub fn any(&self) -> bool {
539        self.data().iter().any(|&v| v != 0.0)
540    }
541
542    /// Returns true if all elements are non-zero.
543    pub fn all(&self) -> bool {
544        self.data().iter().all(|&v| v != 0.0)
545    }
546
547    /// Quantile of all elements. q must be in [0, 1].
548    pub fn quantile(&self, q: f32) -> f32 {
549        let mut sorted = self.data().to_vec();
550        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
551        let n = sorted.len();
552        if n == 0 {
553            return 0.0;
554        }
555        let idx = q * (n - 1) as f32;
556        let lo = idx.floor() as usize;
557        let hi = idx.ceil() as usize;
558        if lo == hi || hi >= n {
559            sorted[lo.min(n - 1)]
560        } else {
561            let frac = idx - lo as f32;
562            sorted[lo] * (1.0 - frac) + sorted[hi] * frac
563        }
564    }
565
566    // ── Shape manipulation ──────────────────────────────────────────────
567
568    /// 2D matrix transpose. Requires rank-2 input.
569    ///
570    /// # Safety
571    /// `AlignedVec::uninitialized` allocates without zeroing. The tiled loop
572    /// writes every element before anything reads from the buffer.
573    #[allow(unsafe_code)]
574    pub fn transpose_2d(&self) -> Result<Self, TensorError> {
575        if self.rank() != 2 {
576            return Err(TensorError::InvalidAxis {
577                axis: 1,
578                rank: self.rank(),
579            });
580        }
581        let rows = self.shape()[0];
582        let cols = self.shape()[1];
583        // SAFETY: every element is written by the tiled loop below before we read.
584        let mut out_data = AlignedVec::<f32>::uninitialized(rows * cols);
585        let src = self.data();
586
587        // Tiled transpose with 8x8 blocks for cache efficiency.
588        const TILE: usize = 8;
589        let rr = rows / TILE * TILE;
590        let cc = cols / TILE * TILE;
591
592        for ii in (0..rr).step_by(TILE) {
593            for jj in (0..cc).step_by(TILE) {
594                for r in ii..ii + TILE {
595                    for c in jj..jj + TILE {
596                        out_data[c * rows + r] = src[r * cols + c];
597                    }
598                }
599            }
600            // Right edge (columns beyond cc)
601            for r in ii..ii + TILE {
602                for c in cc..cols {
603                    out_data[c * rows + r] = src[r * cols + c];
604                }
605            }
606        }
607        // Bottom edge (rows beyond rr)
608        for r in rr..rows {
609            for c in 0..cols {
610                out_data[c * rows + r] = src[r * cols + c];
611            }
612        }
613
614        Tensor::from_aligned(vec![cols, rows], out_data)
615    }
616
617    /// General axis permutation (like NumPy `transpose`/`permute`).
618    pub fn permute(&self, axes: &[usize]) -> Result<Self, TensorError> {
619        if axes.len() != self.rank() {
620            return Err(TensorError::InvalidIndexRank {
621                expected: self.rank(),
622                got: axes.len(),
623            });
624        }
625        let rank = self.rank();
626        let mut seen = vec![false; rank];
627        for &a in axes {
628            if a >= rank {
629                return Err(TensorError::InvalidAxis { axis: a, rank });
630            }
631            seen[a] = true;
632        }
633        if seen.iter().any(|&s| !s) {
634            return Err(TensorError::InvalidAxis { axis: 0, rank });
635        }
636
637        let src_shape = self.shape();
638        let mut out_shape = vec![0usize; rank];
639        for (dst, &src_axis) in axes.iter().enumerate() {
640            out_shape[dst] = src_shape[src_axis];
641        }
642        let out_count =
643            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
644                shape: out_shape.clone(),
645            })?;
646
647        // ── Fast path: tiled 2D transpose for common 4D permutations ──
648        // Uses unsafe pointer arithmetic to eliminate bounds checks in hot inner loops.
649        // NHWC→NCHW [0,3,1,2]: transpose inner [H*W, C] → [C, H*W]
650        if rank == 4 && axes == [0, 3, 1, 2] {
651            let (n, h, w, c) = (src_shape[0], src_shape[1], src_shape[2], src_shape[3]);
652            let hw = h * w;
653            let src = self.data();
654            let mut dst = AlignedVec::<f32>::uninitialized(out_count);
655            const TILE: usize = 32;
656            #[allow(unsafe_code)]
657            unsafe {
658                let src_ptr = src.as_ptr();
659                let dst_ptr = dst.as_mut_ptr();
660                for batch in 0..n {
661                    let s_base = src_ptr.add(batch * hw * c);
662                    let d_base = dst_ptr.add(batch * c * hw);
663                    for i0 in (0..hw).step_by(TILE) {
664                        let ie = (i0 + TILE).min(hw);
665                        for j0 in (0..c).step_by(TILE) {
666                            let je = (j0 + TILE).min(c);
667                            for i in i0..ie {
668                                let s_row = s_base.add(i * c);
669                                for j in j0..je {
670                                    *d_base.add(j * hw + i) = *s_row.add(j);
671                                }
672                            }
673                        }
674                    }
675                }
676            }
677            return Tensor::from_aligned(out_shape, dst);
678        }
679        // NCHW→NHWC [0,2,3,1]: transpose inner [C, H*W] → [H*W, C]
680        if rank == 4 && axes == [0, 2, 3, 1] {
681            let (n, c, h, w) = (src_shape[0], src_shape[1], src_shape[2], src_shape[3]);
682            let hw = h * w;
683            let src = self.data();
684            let mut dst = AlignedVec::<f32>::uninitialized(out_count);
685            const TILE: usize = 32;
686            #[allow(unsafe_code)]
687            unsafe {
688                let src_ptr = src.as_ptr();
689                let dst_ptr = dst.as_mut_ptr();
690                for batch in 0..n {
691                    let s_base = src_ptr.add(batch * c * hw);
692                    let d_base = dst_ptr.add(batch * hw * c);
693                    for i0 in (0..c).step_by(TILE) {
694                        let ie = (i0 + TILE).min(c);
695                        for j0 in (0..hw).step_by(TILE) {
696                            let je = (j0 + TILE).min(hw);
697                            for i in i0..ie {
698                                let s_row = s_base.add(i * hw);
699                                for j in j0..je {
700                                    *d_base.add(j * c + i) = *s_row.add(j);
701                                }
702                            }
703                        }
704                    }
705                }
706            }
707            return Tensor::from_aligned(out_shape, dst);
708        }
709        // 3D swap last two dims [0,2,1]: transpose [A, B, C] → [A, C, B]
710        if rank == 3 && axes == [0, 2, 1] {
711            let (a, b, c) = (src_shape[0], src_shape[1], src_shape[2]);
712            let src = self.data();
713            let mut dst = AlignedVec::<f32>::uninitialized(out_count);
714            const TILE: usize = 32;
715            #[allow(unsafe_code)]
716            unsafe {
717                let src_ptr = src.as_ptr();
718                let dst_ptr = dst.as_mut_ptr();
719                for batch in 0..a {
720                    let s_base = src_ptr.add(batch * b * c);
721                    let d_base = dst_ptr.add(batch * c * b);
722                    for i0 in (0..b).step_by(TILE) {
723                        let ie = (i0 + TILE).min(b);
724                        for j0 in (0..c).step_by(TILE) {
725                            let je = (j0 + TILE).min(c);
726                            for i in i0..ie {
727                                let s_row = s_base.add(i * c);
728                                for j in j0..je {
729                                    *d_base.add(j * b + i) = *s_row.add(j);
730                                }
731                            }
732                        }
733                    }
734                }
735            }
736            return Tensor::from_aligned(out_shape, dst);
737        }
738
739        // [0,1,3,2]: swap last two dims in 4D → [N, A, C, B]
740        // For each (n, a), tiled 2D transpose of [B, C] → [C, B].
741        if rank == 4 && axes == [0, 1, 3, 2] {
742            let (nn, a, b, c) = (src_shape[0], src_shape[1], src_shape[2], src_shape[3]);
743            let src = self.data();
744            let mut dst = AlignedVec::<f32>::uninitialized(out_count);
745            const TILE: usize = 32;
746            #[allow(unsafe_code)]
747            unsafe {
748                let src_ptr = src.as_ptr();
749                let dst_ptr = dst.as_mut_ptr();
750                for n in 0..nn {
751                    for aa in 0..a {
752                        let base = (n * a + aa) * b * c;
753                        let s_base = src_ptr.add(base);
754                        let d_base = dst_ptr.add(base); // same offset, different shape
755                        for i0 in (0..b).step_by(TILE) {
756                            let ie = (i0 + TILE).min(b);
757                            for j0 in (0..c).step_by(TILE) {
758                                let je = (j0 + TILE).min(c);
759                                for i in i0..ie {
760                                    let s_row = s_base.add(i * c);
761                                    for j in j0..je {
762                                        *d_base.add(j * b + i) = *s_row.add(j);
763                                    }
764                                }
765                            }
766                        }
767                    }
768                }
769            }
770            return Tensor::from_aligned(out_shape, dst);
771        }
772        // [0,2,1,3]: swap dims 1↔2 in 4D → [N, B, A, C]
773        // Each element in the swap is a contiguous block of C floats — use memcpy.
774        if rank == 4 && axes == [0, 2, 1, 3] {
775            let (nn, a, b, c) = (src_shape[0], src_shape[1], src_shape[2], src_shape[3]);
776            let src = self.data();
777            let mut dst = AlignedVec::<f32>::uninitialized(out_count);
778            #[allow(unsafe_code)]
779            unsafe {
780                let src_ptr = src.as_ptr();
781                let dst_ptr = dst.as_mut_ptr();
782                for n in 0..nn {
783                    let s_batch = src_ptr.add(n * a * b * c);
784                    let d_batch = dst_ptr.add(n * b * a * c);
785                    for aa in 0..a {
786                        for bb in 0..b {
787                            std::ptr::copy_nonoverlapping(
788                                s_batch.add(aa * b * c + bb * c),
789                                d_batch.add(bb * a * c + aa * c),
790                                c,
791                            );
792                        }
793                    }
794                }
795            }
796            return Tensor::from_aligned(out_shape, dst);
797        }
798        // [0,3,2,1]: swap dims 1↔3 in 4D → [N, D, B, A]
799        // For each (n, b), tiled 2D transpose of [A, D] → [D, A] with strides.
800        if rank == 4 && axes == [0, 3, 2, 1] {
801            let (nn, a, b, d) = (src_shape[0], src_shape[1], src_shape[2], src_shape[3]);
802            let src = self.data();
803            let mut dst = AlignedVec::<f32>::uninitialized(out_count);
804            let src_a_stride = b * d;
805            let dst_d_stride = b * a;
806            const TILE: usize = 32;
807            #[allow(unsafe_code)]
808            unsafe {
809                let src_ptr = src.as_ptr();
810                let dst_ptr = dst.as_mut_ptr();
811                for n in 0..nn {
812                    for bb in 0..b {
813                        let s_base = src_ptr.add(n * a * b * d + bb * d);
814                        let d_base = dst_ptr.add(n * d * b * a + bb * a);
815                        for i0 in (0..a).step_by(TILE) {
816                            let ie = (i0 + TILE).min(a);
817                            for j0 in (0..d).step_by(TILE) {
818                                let je = (j0 + TILE).min(d);
819                                for i in i0..ie {
820                                    for j in j0..je {
821                                        *d_base.add(j * dst_d_stride + i) =
822                                            *s_base.add(i * src_a_stride + j);
823                                    }
824                                }
825                            }
826                        }
827                    }
828                }
829            }
830            return Tensor::from_aligned(out_shape, dst);
831        }
832        // 2D transpose [1,0]: swap rows and cols
833        if rank == 2 && axes == [1, 0] {
834            let (rows, cols) = (src_shape[0], src_shape[1]);
835            let src = self.data();
836            let mut dst = AlignedVec::<f32>::uninitialized(out_count);
837            const TILE: usize = 32;
838            #[allow(unsafe_code)]
839            unsafe {
840                let src_ptr = src.as_ptr();
841                let dst_ptr = dst.as_mut_ptr();
842                for i0 in (0..rows).step_by(TILE) {
843                    let ie = (i0 + TILE).min(rows);
844                    for j0 in (0..cols).step_by(TILE) {
845                        let je = (j0 + TILE).min(cols);
846                        for i in i0..ie {
847                            let s_row = src_ptr.add(i * cols);
848                            for j in j0..je {
849                                *dst_ptr.add(j * rows + i) = *s_row.add(j);
850                            }
851                        }
852                    }
853                }
854            }
855            return Tensor::from_aligned(out_shape, dst);
856        }
857
858        // ── General fallback: coordinate-based scatter ──
859        let out_strides = compute_strides(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
860            shape: out_shape.clone(),
861        })?;
862        let mut out_data = vec![0.0f32; out_count];
863
864        let mut in_coords = vec![0usize; rank];
865        for &val in self.data().iter() {
866            let mut out_offset = 0usize;
867            for (dst_axis, &src_axis) in axes.iter().enumerate() {
868                out_offset += in_coords[src_axis] * out_strides[dst_axis];
869            }
870            out_data[out_offset] = val;
871            increment_coords(&mut in_coords, src_shape);
872        }
873
874        Tensor::from_vec(out_shape, out_data)
875    }
876
877    /// Insert a length-1 dimension at the given axis.
878    pub fn unsqueeze(&self, axis: usize) -> Result<Self, TensorError> {
879        if axis > self.rank() {
880            return Err(TensorError::InvalidAxis {
881                axis,
882                rank: self.rank() + 1,
883            });
884        }
885        let mut new_shape = self.shape().to_vec();
886        new_shape.insert(axis, 1);
887        self.reshape(new_shape)
888    }
889
890    /// Remove a length-1 dimension at the given axis.
891    pub fn squeeze(&self, axis: usize) -> Result<Self, TensorError> {
892        if axis >= self.rank() {
893            return Err(TensorError::InvalidAxis {
894                axis,
895                rank: self.rank(),
896            });
897        }
898        if self.shape()[axis] != 1 {
899            return Err(TensorError::InvalidAxis {
900                axis,
901                rank: self.rank(),
902            });
903        }
904        let mut new_shape = self.shape().to_vec();
905        new_shape.remove(axis);
906        self.reshape(new_shape)
907    }
908
909    /// Concatenate tensors along an axis. All tensors must have the same
910    /// shape except along the concatenation axis.
911    pub fn cat(tensors: &[&Self], axis: usize) -> Result<Self, TensorError> {
912        if tensors.is_empty() {
913            return Err(TensorError::SizeMismatch {
914                shape: vec![],
915                data_len: 0,
916            });
917        }
918        let rank = tensors[0].rank();
919        if axis >= rank {
920            return Err(TensorError::InvalidAxis { axis, rank });
921        }
922        for t in &tensors[1..] {
923            if t.rank() != rank {
924                return Err(TensorError::ShapeMismatch {
925                    left: tensors[0].shape().to_vec(),
926                    right: t.shape().to_vec(),
927                });
928            }
929            for (a, (&d0, &di)) in tensors[0].shape().iter().zip(t.shape().iter()).enumerate() {
930                if a != axis && d0 != di {
931                    return Err(TensorError::ShapeMismatch {
932                        left: tensors[0].shape().to_vec(),
933                        right: t.shape().to_vec(),
934                    });
935                }
936            }
937        }
938
939        let mut out_shape = tensors[0].shape().to_vec();
940        out_shape[axis] = tensors.iter().map(|t| t.shape()[axis]).sum();
941        let out_count =
942            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
943                shape: out_shape.clone(),
944            })?;
945
946        let outer: usize = out_shape[..axis].iter().product();
947        let inner: usize = out_shape[axis + 1..].iter().product();
948
949        // Write directly into AlignedVec to avoid the double-copy through
950        // Vec -> AlignedVec::from_vec.
951        let mut out_data = AlignedVec::<f32>::uninitialized(out_count);
952
953        if inner == 1 && tensors.len() <= 8 {
954            // Last-axis concat: write entire output in outer-major order.
955            let axis_lens: Vec<usize> = tensors.iter().map(|t| t.shape()[axis]).collect();
956            let dst = out_data.as_mut_slice();
957            let mut dst_off = 0;
958            for o in 0..outer {
959                for (ti, t) in tensors.iter().enumerate() {
960                    let al = axis_lens[ti];
961                    let src_off = o * al;
962                    dst[dst_off..dst_off + al].copy_from_slice(&t.data()[src_off..src_off + al]);
963                    dst_off += al;
964                }
965            }
966        } else {
967            let dst = out_data.as_mut_slice();
968            let mut dst_off = 0;
969            for o in 0..outer {
970                for t in tensors {
971                    let t_axis_len = t.shape()[axis];
972                    let chunk_len = t_axis_len * inner;
973                    let chunk_start = o * chunk_len;
974                    dst[dst_off..dst_off + chunk_len]
975                        .copy_from_slice(&t.data()[chunk_start..chunk_start + chunk_len]);
976                    dst_off += chunk_len;
977                }
978            }
979        }
980
981        Tensor::from_aligned(out_shape, out_data)
982    }
983
984    /// Stack tensors along a new axis. All tensors must have identical shapes.
985    pub fn stack(tensors: &[&Self], axis: usize) -> Result<Self, TensorError> {
986        if tensors.is_empty() {
987            return Err(TensorError::SizeMismatch {
988                shape: vec![],
989                data_len: 0,
990            });
991        }
992        if axis > tensors[0].rank() {
993            return Err(TensorError::InvalidAxis {
994                axis,
995                rank: tensors[0].rank() + 1,
996            });
997        }
998        let expanded: Vec<Self> = tensors
999            .iter()
1000            .map(|t| t.unsqueeze(axis))
1001            .collect::<Result<_, _>>()?;
1002        let refs: Vec<&Self> = expanded.iter().collect();
1003        Self::cat(&refs, axis)
1004    }
1005
1006    /// Select a single slice along an axis, removing that axis from the output.
1007    pub fn select(&self, axis: usize, index: usize) -> Result<Self, TensorError> {
1008        if axis >= self.rank() {
1009            return Err(TensorError::InvalidAxis {
1010                axis,
1011                rank: self.rank(),
1012            });
1013        }
1014        if index >= self.shape()[axis] {
1015            return Err(TensorError::IndexOutOfBounds {
1016                axis,
1017                index,
1018                dim: self.shape()[axis],
1019            });
1020        }
1021        let outer: usize = self.shape()[..axis].iter().product();
1022        let axis_len = self.shape()[axis];
1023        let inner: usize = self.shape()[axis + 1..].iter().product();
1024
1025        let mut out_data = Vec::with_capacity(outer * inner);
1026        for o in 0..outer {
1027            let base = o * axis_len * inner + index * inner;
1028            out_data.extend_from_slice(&self.data()[base..base + inner]);
1029        }
1030
1031        let mut out_shape = self.shape().to_vec();
1032        out_shape.remove(axis);
1033        Tensor::from_vec(out_shape, out_data)
1034    }
1035
1036    /// Narrow (slice) along an axis: extract elements `start..start+length`.
1037    pub fn narrow(&self, axis: usize, start: usize, length: usize) -> Result<Self, TensorError> {
1038        if axis >= self.rank() {
1039            return Err(TensorError::InvalidAxis {
1040                axis,
1041                rank: self.rank(),
1042            });
1043        }
1044        if start + length > self.shape()[axis] {
1045            return Err(TensorError::IndexOutOfBounds {
1046                axis,
1047                index: start + length,
1048                dim: self.shape()[axis],
1049            });
1050        }
1051        let outer: usize = self.shape()[..axis].iter().product();
1052        let axis_len = self.shape()[axis];
1053        let inner: usize = self.shape()[axis + 1..].iter().product();
1054
1055        let mut out_data = Vec::with_capacity(outer * length * inner);
1056        for o in 0..outer {
1057            let base = o * axis_len * inner + start * inner;
1058            out_data.extend_from_slice(&self.data()[base..base + length * inner]);
1059        }
1060
1061        let mut out_shape = self.shape().to_vec();
1062        out_shape[axis] = length;
1063        Tensor::from_vec(out_shape, out_data)
1064    }
1065
1066    // ── Comparison ──────────────────────────────────────────────────────
1067
1068    /// Element-wise equality check: 1.0 where equal, 0.0 otherwise.
1069    pub fn eq_tensor(&self, rhs: &Self) -> Result<Self, TensorError> {
1070        if self.shape() == rhs.shape() {
1071            return self.binary_same_shape(rhs, |l, r| {
1072                if (l - r).abs() < f32::EPSILON {
1073                    1.0
1074                } else {
1075                    0.0
1076                }
1077            });
1078        }
1079        self.binary_broadcast_op(rhs, |l, r| {
1080            if (l - r).abs() < f32::EPSILON {
1081                1.0
1082            } else {
1083                0.0
1084            }
1085        })
1086    }
1087
1088    /// Element-wise greater-than: 1.0 where `self > rhs`, 0.0 otherwise.
1089    pub fn gt_tensor(&self, rhs: &Self) -> Result<Self, TensorError> {
1090        if self.shape() == rhs.shape() {
1091            return self.binary_same_shape(rhs, |l, r| if l > r { 1.0 } else { 0.0 });
1092        }
1093        self.binary_broadcast_op(rhs, |l, r| if l > r { 1.0 } else { 0.0 })
1094    }
1095
1096    /// Element-wise less-than: 1.0 where `self < rhs`, 0.0 otherwise.
1097    pub fn lt_tensor(&self, rhs: &Self) -> Result<Self, TensorError> {
1098        if self.shape() == rhs.shape() {
1099            return self.binary_same_shape(rhs, |l, r| if l < r { 1.0 } else { 0.0 });
1100        }
1101        self.binary_broadcast_op(rhs, |l, r| if l < r { 1.0 } else { 0.0 })
1102    }
1103
1104    /// Element-wise greater-than writing into a pre-allocated output tensor.
1105    /// `self`, `rhs`, and `output` must all have the same shape.
1106    pub fn gt_tensor_into(&self, rhs: &Self, output: &mut Self) {
1107        debug_assert_eq!(self.shape(), rhs.shape());
1108        debug_assert_eq!(self.shape(), output.shape());
1109        simd::cmp_dispatch(
1110            self.data(),
1111            rhs.data(),
1112            output.data_mut(),
1113            simd::CmpKind::Gt,
1114        );
1115    }
1116
1117    /// Element-wise equality check writing into a pre-allocated output tensor.
1118    /// `self`, `rhs`, and `output` must all have the same shape.
1119    pub fn eq_tensor_into(&self, rhs: &Self, output: &mut Self) {
1120        debug_assert_eq!(self.shape(), rhs.shape());
1121        debug_assert_eq!(self.shape(), output.shape());
1122        simd::cmp_dispatch(
1123            self.data(),
1124            rhs.data(),
1125            output.data_mut(),
1126            simd::CmpKind::Eq,
1127        );
1128    }
1129
1130    /// Element-wise less-than writing into a pre-allocated output tensor.
1131    /// `self`, `rhs`, and `output` must all have the same shape.
1132    pub fn lt_tensor_into(&self, rhs: &Self, output: &mut Self) {
1133        debug_assert_eq!(self.shape(), rhs.shape());
1134        debug_assert_eq!(self.shape(), output.shape());
1135        simd::cmp_dispatch(
1136            self.data(),
1137            rhs.data(),
1138            output.data_mut(),
1139            simd::CmpKind::Lt,
1140        );
1141    }
1142
1143    /// Element-wise not-equal: 1.0 where not equal (diff.abs() >= 1e-7), 0.0 otherwise.
1144    pub fn ne_tensor(&self, rhs: &Self) -> Result<Self, TensorError> {
1145        if self.shape() == rhs.shape() {
1146            return self.binary_same_shape(
1147                rhs,
1148                |l, r| {
1149                    if (l - r).abs() >= 1e-7 { 1.0 } else { 0.0 }
1150                },
1151            );
1152        }
1153        self.binary_broadcast_op(rhs, |l, r| if (l - r).abs() >= 1e-7 { 1.0 } else { 0.0 })
1154    }
1155
1156    /// Element-wise less-than-or-equal: 1.0 where `self <= rhs`, 0.0 otherwise.
1157    pub fn le_tensor(&self, rhs: &Self) -> Result<Self, TensorError> {
1158        if self.shape() == rhs.shape() {
1159            return self.binary_same_shape(rhs, |l, r| if l <= r { 1.0 } else { 0.0 });
1160        }
1161        self.binary_broadcast_op(rhs, |l, r| if l <= r { 1.0 } else { 0.0 })
1162    }
1163
1164    /// Element-wise greater-than-or-equal: 1.0 where `self >= rhs`, 0.0 otherwise.
1165    pub fn ge_tensor(&self, rhs: &Self) -> Result<Self, TensorError> {
1166        if self.shape() == rhs.shape() {
1167            return self.binary_same_shape(rhs, |l, r| if l >= r { 1.0 } else { 0.0 });
1168        }
1169        self.binary_broadcast_op(rhs, |l, r| if l >= r { 1.0 } else { 0.0 })
1170    }
1171
1172    /// Returns true if all elements are finite (no NaN or Inf).
1173    pub fn all_finite(&self) -> bool {
1174        self.data().iter().all(|v| v.is_finite())
1175    }
1176
1177    // ── Advanced indexing/selection ─────────────────────────────────────
1178
1179    /// Element-wise where: `condition ? self : other`.
1180    /// `condition` has 1.0 for true, 0.0 for false.
1181    pub fn where_cond(&self, condition: &Self, other: &Self) -> Result<Self, TensorError> {
1182        if self.shape() != condition.shape() || self.shape() != other.shape() {
1183            return Err(TensorError::ShapeMismatch {
1184                left: self.shape().to_vec(),
1185                right: condition.shape().to_vec(),
1186            });
1187        }
1188        let data: Vec<f32> = condition
1189            .data()
1190            .iter()
1191            .zip(self.data().iter())
1192            .zip(other.data().iter())
1193            .map(|((&c, &t), &f)| if c != 0.0 { t } else { f })
1194            .collect();
1195        Tensor::from_vec(self.shape().to_vec(), data)
1196    }
1197
1198    /// Replace elements where `mask != 0` with `value`.
1199    pub fn masked_fill(&self, mask: &Self, value: f32) -> Result<Self, TensorError> {
1200        if self.shape() != mask.shape() {
1201            return Err(TensorError::ShapeMismatch {
1202                left: self.shape().to_vec(),
1203                right: mask.shape().to_vec(),
1204            });
1205        }
1206        let data: Vec<f32> = self
1207            .data()
1208            .iter()
1209            .zip(mask.data().iter())
1210            .map(|(&v, &m)| if m != 0.0 { value } else { v })
1211            .collect();
1212        Tensor::from_vec(self.shape().to_vec(), data)
1213    }
1214
1215    /// Scatter values into self along `axis` at positions given by `index`.
1216    /// `src` provides the values. `index` has same shape as `src`.
1217    pub fn scatter(&self, axis: usize, index: &Self, src: &Self) -> Result<Self, TensorError> {
1218        if index.shape() != src.shape() {
1219            return Err(TensorError::ShapeMismatch {
1220                left: index.shape().to_vec(),
1221                right: src.shape().to_vec(),
1222            });
1223        }
1224        if axis >= self.rank() {
1225            return Err(TensorError::InvalidAxis {
1226                axis,
1227                rank: self.rank(),
1228            });
1229        }
1230        let mut out = self.data().to_vec();
1231        let shape = index.shape();
1232        let outer: usize = shape[..axis].iter().product();
1233        let dim = shape[axis];
1234        let inner: usize = shape[axis + 1..].iter().product();
1235        let self_dim = self.shape()[axis];
1236        let self_inner: usize = self.shape()[axis + 1..].iter().product();
1237
1238        for o in 0..outer {
1239            for d in 0..dim {
1240                for i in 0..inner {
1241                    let src_idx = (o * dim + d) * inner + i;
1242                    let target_d = index.data()[src_idx] as usize;
1243                    if target_d < self_dim {
1244                        let out_idx = (o * self_dim + target_d) * self_inner + i;
1245                        if out_idx < out.len() {
1246                            out[out_idx] = src.data()[src_idx];
1247                        }
1248                    }
1249                }
1250            }
1251        }
1252        Tensor::from_vec(self.shape().to_vec(), out)
1253    }
1254
1255    /// Gather elements along `axis` at positions given by `index`.
1256    pub fn gather(&self, axis: usize, index: &Self) -> Result<Self, TensorError> {
1257        if axis >= self.rank() {
1258            return Err(TensorError::InvalidAxis {
1259                axis,
1260                rank: self.rank(),
1261            });
1262        }
1263        let shape = index.shape();
1264        let outer: usize = shape[..axis].iter().product();
1265        let dim = shape[axis];
1266        let inner: usize = shape[axis + 1..].iter().product();
1267        let self_dim = self.shape()[axis];
1268        let self_inner: usize = self.shape()[axis + 1..].iter().product();
1269
1270        let mut out = vec![0.0f32; index.len()];
1271        for o in 0..outer {
1272            for d in 0..dim {
1273                for i in 0..inner {
1274                    let idx_pos = (o * dim + d) * inner + i;
1275                    let src_d = index.data()[idx_pos] as usize;
1276                    if src_d < self_dim {
1277                        let src_pos = (o * self_dim + src_d) * self_inner + i;
1278                        if src_pos < self.len() {
1279                            out[idx_pos] = self.data()[src_pos];
1280                        }
1281                    }
1282                }
1283            }
1284        }
1285        Tensor::from_vec(shape.to_vec(), out)
1286    }
1287
1288    /// Returns the top-k values and their indices along the last axis.
1289    pub fn topk(&self, k: usize) -> Result<(Self, Self), TensorError> {
1290        if self.rank() == 0 {
1291            return Err(TensorError::InvalidAxis { axis: 0, rank: 0 });
1292        }
1293        let last_dim = *self.shape().last().expect("non-empty shape");
1294        let k = k.min(last_dim);
1295        let outer: usize = self.len() / last_dim;
1296
1297        let mut values = Vec::with_capacity(outer * k);
1298        let mut indices = Vec::with_capacity(outer * k);
1299
1300        for o in 0..outer {
1301            let start = o * last_dim;
1302            let slice = &self.data()[start..start + last_dim];
1303            let mut idx_vec: Vec<usize> = (0..last_dim).collect();
1304            idx_vec.sort_unstable_by(|&a, &b| {
1305                slice[b]
1306                    .partial_cmp(&slice[a])
1307                    .unwrap_or(std::cmp::Ordering::Equal)
1308            });
1309            for &i in &idx_vec[..k] {
1310                values.push(slice[i]);
1311                indices.push(i as f32);
1312            }
1313        }
1314
1315        let mut out_shape = self.shape().to_vec();
1316        *out_shape.last_mut().expect("non-empty shape") = k;
1317        let val_t = Tensor::from_vec(out_shape.clone(), values)?;
1318        let idx_t = Tensor::from_vec(out_shape, indices)?;
1319        Ok((val_t, idx_t))
1320    }
1321
1322    /// Upper triangular mask: zero below diagonal, keep above.
1323    /// `diagonal` shifts: 0 = main, positive = above, negative = below.
1324    pub fn triu(&self, diagonal: i64) -> Result<Self, TensorError> {
1325        if self.rank() < 2 {
1326            return Err(TensorError::InvalidAxis {
1327                axis: 0,
1328                rank: self.rank(),
1329            });
1330        }
1331        let shape = self.shape();
1332        let rows = shape[shape.len() - 2];
1333        let cols = shape[shape.len() - 1];
1334        let batch: usize = shape[..shape.len() - 2].iter().product();
1335        let mut out = self.data().to_vec();
1336        for b in 0..batch {
1337            for r in 0..rows {
1338                for c in 0..cols {
1339                    if (c as i64) < (r as i64) + diagonal {
1340                        out[b * rows * cols + r * cols + c] = 0.0;
1341                    }
1342                }
1343            }
1344        }
1345        Tensor::from_vec(shape.to_vec(), out)
1346    }
1347
1348    /// Lower triangular mask: zero above diagonal, keep below.
1349    pub fn tril(&self, diagonal: i64) -> Result<Self, TensorError> {
1350        if self.rank() < 2 {
1351            return Err(TensorError::InvalidAxis {
1352                axis: 0,
1353                rank: self.rank(),
1354            });
1355        }
1356        let shape = self.shape();
1357        let rows = shape[shape.len() - 2];
1358        let cols = shape[shape.len() - 1];
1359        let batch: usize = shape[..shape.len() - 2].iter().product();
1360        let mut out = self.data().to_vec();
1361        for b in 0..batch {
1362            for r in 0..rows {
1363                for c in 0..cols {
1364                    if (c as i64) > (r as i64) + diagonal {
1365                        out[b * rows * cols + r * cols + c] = 0.0;
1366                    }
1367                }
1368            }
1369        }
1370        Tensor::from_vec(shape.to_vec(), out)
1371    }
1372
1373    /// Identity matrix `[n, n]`.
1374    pub fn eye(n: usize) -> Result<Self, TensorError> {
1375        let mut data = vec![0.0f32; n * n];
1376        for i in 0..n {
1377            data[i * n + i] = 1.0;
1378        }
1379        Tensor::from_vec(vec![n, n], data)
1380    }
1381
1382    /// Create a diagonal matrix from a 1D vector.
1383    pub fn diag(vector: &Tensor) -> Result<Self, TensorError> {
1384        let shape = vector.shape();
1385        if shape.len() != 1 {
1386            return Err(TensorError::UnsupportedOperation {
1387                msg: format!("diag requires a 1D tensor, got shape {:?}", shape),
1388            });
1389        }
1390        let n = shape[0];
1391        let mut data = vec![0.0f32; n * n];
1392        for i in 0..n {
1393            data[i * n + i] = vector.data()[i];
1394        }
1395        Self::from_vec(vec![n, n], data)
1396    }
1397
1398    /// Extract the diagonal of a 2D matrix as a 1D vector.
1399    pub fn diag_extract(&self) -> Result<Self, TensorError> {
1400        let shape = self.shape();
1401        if shape.len() != 2 {
1402            return Err(TensorError::UnsupportedOperation {
1403                msg: format!("diag_extract requires a 2D tensor, got shape {:?}", shape),
1404            });
1405        }
1406        let n = shape[0].min(shape[1]);
1407        let cols = shape[1];
1408        let data: Vec<f32> = (0..n).map(|i| self.data()[i * cols + i]).collect();
1409        Self::from_vec(vec![n], data)
1410    }
1411
1412    /// Pad the tensor with a constant value. `padding` is a slice of (before, after) per dimension.
1413    pub fn pad(&self, padding: &[(usize, usize)], value: f32) -> Result<Self, TensorError> {
1414        let shape = self.shape();
1415        if padding.len() != shape.len() {
1416            return Err(TensorError::InvalidIndexRank {
1417                expected: shape.len(),
1418                got: padding.len(),
1419            });
1420        }
1421        let new_shape: Vec<usize> = shape
1422            .iter()
1423            .zip(padding)
1424            .map(|(&s, &(b, a))| s + b + a)
1425            .collect();
1426        let new_size: usize = new_shape.iter().product();
1427        let mut result = vec![value; new_size];
1428        let ndim = shape.len();
1429
1430        // Compute strides for both old and new shapes
1431        let mut old_strides = vec![1usize; ndim];
1432        for i in (0..ndim.saturating_sub(1)).rev() {
1433            old_strides[i] = old_strides[i + 1] * shape[i + 1];
1434        }
1435        let mut new_strides = vec![1usize; ndim];
1436        for i in (0..ndim.saturating_sub(1)).rev() {
1437            new_strides[i] = new_strides[i + 1] * new_shape[i + 1];
1438        }
1439
1440        let old_size: usize = shape.iter().product();
1441        let data = self.data();
1442        for flat_idx in 0..old_size {
1443            let mut remaining = flat_idx;
1444            let mut new_flat = 0;
1445            for d in 0..ndim {
1446                let coord = remaining / old_strides[d];
1447                remaining %= old_strides[d];
1448                new_flat += (coord + padding[d].0) * new_strides[d];
1449            }
1450            result[new_flat] = data[flat_idx];
1451        }
1452
1453        Self::from_vec(new_shape, result)
1454    }
1455
1456    /// Repeat tensor along each axis by the given counts.
1457    pub fn repeat(&self, counts: &[usize]) -> Result<Self, TensorError> {
1458        if counts.len() != self.rank() {
1459            return Err(TensorError::InvalidIndexRank {
1460                expected: self.rank(),
1461                got: counts.len(),
1462            });
1463        }
1464        let mut out = self.clone();
1465        for (axis, &count) in counts.iter().enumerate() {
1466            if count > 1 {
1467                let refs: Vec<&Tensor> = std::iter::repeat_n(&out, count).collect();
1468                out = Tensor::cat(&refs, axis)?;
1469            }
1470        }
1471        Ok(out)
1472    }
1473
1474    // ── Cumulative operations ──────────────────────────────────────────
1475
1476    /// Cumulative sum along an axis.
1477    pub fn cumsum(&self, axis: usize) -> Result<Self, TensorError> {
1478        if axis >= self.rank() {
1479            return Err(TensorError::InvalidAxis {
1480                axis,
1481                rank: self.rank(),
1482            });
1483        }
1484        let shape = self.shape();
1485        let outer: usize = shape[..axis].iter().product();
1486        let axis_len = shape[axis];
1487        let inner: usize = shape[axis + 1..].iter().product();
1488        let mut out = self.data().to_vec();
1489
1490        for o in 0..outer {
1491            for i in 0..inner {
1492                let mut acc = 0.0f32;
1493                for d in 0..axis_len {
1494                    let idx = (o * axis_len + d) * inner + i;
1495                    acc += out[idx];
1496                    out[idx] = acc;
1497                }
1498            }
1499        }
1500        Tensor::from_vec(shape.to_vec(), out)
1501    }
1502
1503    /// Cumulative product along an axis.
1504    pub fn cumprod(&self, axis: usize) -> Result<Self, TensorError> {
1505        if axis >= self.rank() {
1506            return Err(TensorError::InvalidAxis {
1507                axis,
1508                rank: self.rank(),
1509            });
1510        }
1511        let shape = self.shape();
1512        let outer: usize = shape[..axis].iter().product();
1513        let axis_len = shape[axis];
1514        let inner: usize = shape[axis + 1..].iter().product();
1515        let mut out = self.data().to_vec();
1516
1517        for o in 0..outer {
1518            for i in 0..inner {
1519                let mut acc = 1.0f32;
1520                for d in 0..axis_len {
1521                    let idx = (o * axis_len + d) * inner + i;
1522                    acc *= out[idx];
1523                    out[idx] = acc;
1524                }
1525            }
1526        }
1527        Tensor::from_vec(shape.to_vec(), out)
1528    }
1529
1530    // ── FP16 conversion ────────────────────────────────────────────────
1531
1532    /// Convert all elements to IEEE 754 half-precision (FP16) bytes.
1533    /// Returns `Vec<u16>` where each u16 is an FP16 bit pattern.
1534    pub fn to_fp16(&self) -> Vec<u16> {
1535        self.data().iter().map(|&v| f32_to_fp16(v)).collect()
1536    }
1537
1538    /// Create a tensor from FP16 bit patterns.
1539    pub fn from_fp16(shape: Vec<usize>, fp16_data: &[u16]) -> Result<Self, TensorError> {
1540        let data: Vec<f32> = fp16_data.iter().map(|&v| fp16_to_f32(v)).collect();
1541        Tensor::from_vec(shape, data)
1542    }
1543
1544    // ── Internal helpers ────────────────────────────────────────────────
1545
1546    #[allow(unsafe_code)]
1547    fn unary_op<F>(&self, op: F) -> Self
1548    where
1549        F: Fn(f32) -> f32,
1550    {
1551        let src = self.data();
1552        let len = src.len();
1553        // SAFETY: `uninitialized` allocates without zeroing.  The loop below
1554        // writes every element before we ever read from `out_data`.
1555        let mut out_data = AlignedVec::<f32>::uninitialized(len);
1556        let inp = src.as_ptr();
1557        let outp = out_data.as_mut_ptr();
1558        unsafe {
1559            for i in 0..len {
1560                *outp.add(i) = op(*inp.add(i));
1561            }
1562        }
1563        Tensor::from_raw_parts(self.shape(), self.strides(), out_data)
1564    }
1565
1566    #[allow(unsafe_code)]
1567    fn unary_simd_op(&self, kind: simd::UnaryKind) -> Self {
1568        let len = self.len();
1569        // SAFETY: `uninitialized` allocates without zeroing.  `unary_dispatch`
1570        // writes every element before we ever read from `out`.
1571        let mut out = AlignedVec::<f32>::uninitialized(len);
1572        simd::unary_dispatch(self.data(), &mut out, kind);
1573        Tensor::from_raw_parts(self.shape(), self.strides(), out)
1574    }
1575
1576    fn reduce_axis<F>(&self, axis: usize, init: f32, combine: F) -> Result<Self, TensorError>
1577    where
1578        F: Fn(f32, f32) -> f32,
1579    {
1580        if axis >= self.rank() {
1581            return Err(TensorError::InvalidAxis {
1582                axis,
1583                rank: self.rank(),
1584            });
1585        }
1586
1587        let mut out_shape = self.shape().to_vec();
1588        out_shape.remove(axis);
1589        let out_count =
1590            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
1591                shape: out_shape.clone(),
1592            })?;
1593        let out_strides = compute_strides(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
1594            shape: out_shape.clone(),
1595        })?;
1596        let mut out_data = vec![init; out_count];
1597
1598        let mut in_coords = vec![0usize; self.rank()];
1599        for input in self.data().iter().copied() {
1600            let mut out_offset = 0usize;
1601            for (src_axis, coord) in in_coords.iter().copied().enumerate() {
1602                if src_axis == axis {
1603                    continue;
1604                }
1605                let dst_axis = if src_axis < axis {
1606                    src_axis
1607                } else {
1608                    src_axis - 1
1609                };
1610                if !out_shape.is_empty() {
1611                    out_offset += coord * out_strides[dst_axis];
1612                }
1613            }
1614            out_data[out_offset] = combine(out_data[out_offset], input);
1615            increment_coords(&mut in_coords, self.shape());
1616        }
1617
1618        Tensor::from_vec(out_shape, out_data)
1619    }
1620
1621    /// SIMD fast path for broadcasting a last-dim vector across all rows.
1622    ///
1623    /// Matches patterns like `[N, C] + [C]`, `[N, H, W, C] + [1, C]`, etc.
1624    /// Returns `None` if the pattern doesn't match, so the caller falls through
1625    /// to the generic broadcast loop.
1626    #[allow(unsafe_code)]
1627    fn binary_broadcast_lastdim_simd(
1628        &self,
1629        rhs: &Self,
1630        kind: simd::BinaryKind,
1631    ) -> Option<Result<Self, TensorError>> {
1632        let lhs_shape = self.shape();
1633        let rhs_shape = rhs.shape();
1634
1635        // Detect: rhs is a 1-D vector whose length equals lhs's last dim,
1636        // or rhs shape is all-1 except the last dim which matches lhs's last dim.
1637        let lhs_last = *lhs_shape.last()?;
1638        if lhs_last == 0 {
1639            return None;
1640        }
1641
1642        let rhs_last = *rhs_shape.last()?;
1643
1644        // Check rhs is effectively a 1-D vector of size lhs_last:
1645        // either shape [C] or shape [1, 1, ..., C]
1646        let rhs_is_lastdim_vec =
1647            rhs_last == lhs_last && rhs_shape.iter().rev().skip(1).all(|&d| d == 1);
1648        // Also handle the symmetric case: lhs is the vector, rhs is the big tensor
1649        let lhs_is_lastdim_vec =
1650            lhs_last == rhs_last && lhs_shape.iter().rev().skip(1).all(|&d| d == 1);
1651
1652        // The fast path is safe only when the "row vector" side (all-1
1653        // except possibly the last dim) ALSO has rank ≤ the other side
1654        // and its 1-padding doesn't introduce extra dims. Otherwise the
1655        // broadcast result has a higher rank than the big tensor, and
1656        // we fall through to the general path so the output shape
1657        // matches numpy semantics.
1658        if rhs_is_lastdim_vec && !lhs_is_lastdim_vec {
1659            // rhs is the row-vector. Safe iff rhs_shape is rank-1 OR
1660            // rhs's rank is ≤ lhs's rank (otherwise rhs's leading 1s
1661            // would still expand the broadcast rank past lhs's).
1662            if rhs_shape.len() > lhs_shape.len() {
1663                return None;
1664            }
1665            let lhs_data = self.data();
1666            let rhs_data = rhs.data();
1667            let row_len = lhs_last;
1668            let num_rows = lhs_data.len() / row_len;
1669            let mut out_data = AlignedVec::<f32>::uninitialized(lhs_data.len());
1670
1671            for i in 0..num_rows {
1672                let start = i * row_len;
1673                let end = start + row_len;
1674                simd::binary_dispatch(
1675                    &lhs_data[start..end],
1676                    &rhs_data[..row_len],
1677                    &mut out_data[start..end],
1678                    kind,
1679                );
1680            }
1681
1682            let out_strides = compute_strides(lhs_shape).expect("valid shape for strides");
1683            Some(Ok(Tensor::from_raw_parts(
1684                lhs_shape,
1685                &out_strides,
1686                out_data,
1687            )))
1688        } else if lhs_is_lastdim_vec && !rhs_is_lastdim_vec {
1689            if lhs_shape.len() > rhs_shape.len() {
1690                return None;
1691            }
1692            let lhs_data = self.data();
1693            let rhs_data = rhs.data();
1694            let row_len = rhs_last;
1695            let num_rows = rhs_data.len() / row_len;
1696            let mut out_data = AlignedVec::<f32>::uninitialized(rhs_data.len());
1697
1698            for i in 0..num_rows {
1699                let start = i * row_len;
1700                let end = start + row_len;
1701                simd::binary_dispatch(
1702                    &lhs_data[..row_len],
1703                    &rhs_data[start..end],
1704                    &mut out_data[start..end],
1705                    kind,
1706                );
1707            }
1708
1709            let out_strides = compute_strides(rhs_shape).expect("valid shape for strides");
1710            Some(Ok(Tensor::from_raw_parts(
1711                rhs_shape,
1712                &out_strides,
1713                out_data,
1714            )))
1715        } else {
1716            None
1717        }
1718    }
1719
1720    /// Ternary `where` with NumPy-style broadcasting:
1721    /// `out[i] = if cond[i] != 0 { x[i] } else { y[i] }`, where each
1722    /// operand is broadcast to the common shape derived from all three.
1723    /// Mirrors ONNX's `Where` op (and `np.where` semantics).
1724    pub fn where_select(cond: &Self, x: &Self, y: &Self) -> Result<Self, TensorError> {
1725        // Same-shape fast path — no broadcasting work needed.
1726        if cond.shape() == x.shape() && cond.shape() == y.shape() {
1727            let cd = cond.data();
1728            let xd = x.data();
1729            let yd = y.data();
1730            let data: Vec<f32> = cd
1731                .iter()
1732                .zip(xd.iter().zip(yd.iter()))
1733                .map(|(&c, (&xv, &yv))| if c != 0.0 { xv } else { yv })
1734                .collect();
1735            return Tensor::from_vec(cond.shape().to_vec(), data);
1736        }
1737        let cx_shape = broadcast_shape(cond.shape(), x.shape()).ok_or_else(|| {
1738            TensorError::BroadcastIncompatible {
1739                left: cond.shape().to_vec(),
1740                right: x.shape().to_vec(),
1741            }
1742        })?;
1743        let out_shape = broadcast_shape(&cx_shape, y.shape()).ok_or_else(|| {
1744            TensorError::BroadcastIncompatible {
1745                left: cx_shape.clone(),
1746                right: y.shape().to_vec(),
1747            }
1748        })?;
1749        let out_count =
1750            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
1751                shape: out_shape.clone(),
1752            })?;
1753        let mut out_data = vec![0.0_f32; out_count];
1754        let mut coords = vec![0_usize; out_shape.len()];
1755        let cd = cond.data();
1756        let xd = x.data();
1757        let yd = y.data();
1758        for value in &mut out_data {
1759            let c_off = broadcast_offset(cond.shape(), cond.strides(), &coords);
1760            let x_off = broadcast_offset(x.shape(), x.strides(), &coords);
1761            let y_off = broadcast_offset(y.shape(), y.strides(), &coords);
1762            *value = if cd[c_off] != 0.0 {
1763                xd[x_off]
1764            } else {
1765                yd[y_off]
1766            };
1767            increment_coords(&mut coords, &out_shape);
1768        }
1769        Tensor::from_vec(out_shape, out_data)
1770    }
1771
1772    fn binary_broadcast_op<F>(&self, rhs: &Self, op: F) -> Result<Self, TensorError>
1773    where
1774        F: Fn(f32, f32) -> f32,
1775    {
1776        let out_shape = broadcast_shape(self.shape(), rhs.shape()).ok_or_else(|| {
1777            TensorError::BroadcastIncompatible {
1778                left: self.shape().to_vec(),
1779                right: rhs.shape().to_vec(),
1780            }
1781        })?;
1782
1783        let out_count =
1784            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
1785                shape: out_shape.clone(),
1786            })?;
1787        let mut out_data = vec![0.0; out_count];
1788        let mut coords = vec![0usize; out_shape.len()];
1789
1790        for value in &mut out_data {
1791            let left_offset = broadcast_offset(self.shape(), self.strides(), &coords);
1792            let right_offset = broadcast_offset(rhs.shape(), rhs.strides(), &coords);
1793            *value = op(self.data()[left_offset], rhs.data()[right_offset]);
1794            increment_coords(&mut coords, &out_shape);
1795        }
1796
1797        Tensor::from_vec(out_shape, out_data)
1798    }
1799
1800    /// SIMD-accelerated binary op for same-shape tensors (add/sub/mul/div).
1801    #[allow(unsafe_code)]
1802    #[allow(unsafe_code)]
1803    fn binary_same_shape_simd(
1804        &self,
1805        rhs: &Self,
1806        kind: simd::BinaryKind,
1807    ) -> Result<Self, TensorError> {
1808        let len = self.len();
1809        let mut out_data = AlignedVec::<f32>::uninitialized(len);
1810
1811        // Multi-threaded for large tensors. Cross-platform:
1812        // macOS → GCD dispatch_apply, others → rayon thread pool.
1813        if len >= 100_000 {
1814            let n = std::thread::available_parallelism()
1815                .map(|p| p.get())
1816                .unwrap_or(4);
1817            let chunk = len.div_ceil(n);
1818            let lp = self.data().as_ptr() as usize;
1819            let rp = rhs.data().as_ptr() as usize;
1820            let op = out_data.as_mut_ptr() as usize;
1821
1822            #[cfg(target_os = "macos")]
1823            {
1824                use std::ffi::c_void;
1825                #[allow(unsafe_code)]
1826                unsafe extern "C" {
1827                    fn dispatch_get_global_queue(id: isize, flags: usize) -> *const c_void;
1828                    fn dispatch_apply_f(
1829                        n: usize,
1830                        q: *const c_void,
1831                        ctx: *mut c_void,
1832                        work: unsafe extern "C" fn(*mut c_void, usize),
1833                    );
1834                }
1835                struct Ctx {
1836                    lp: usize,
1837                    rp: usize,
1838                    op: usize,
1839                    chunk: usize,
1840                    len: usize,
1841                    kind: simd::BinaryKind,
1842                }
1843                let ctx = Ctx {
1844                    lp,
1845                    rp,
1846                    op,
1847                    chunk,
1848                    len,
1849                    kind,
1850                };
1851                unsafe extern "C" fn work(raw: *mut c_void, t: usize) {
1852                    let c = unsafe { &*(raw as *const Ctx) };
1853                    let start = t * c.chunk;
1854                    let end = (start + c.chunk).min(c.len);
1855                    if start >= end {
1856                        return;
1857                    }
1858                    let l = unsafe {
1859                        std::slice::from_raw_parts((c.lp as *const f32).add(start), end - start)
1860                    };
1861                    let r = unsafe {
1862                        std::slice::from_raw_parts((c.rp as *const f32).add(start), end - start)
1863                    };
1864                    let o = unsafe {
1865                        std::slice::from_raw_parts_mut((c.op as *mut f32).add(start), end - start)
1866                    };
1867                    simd::binary_dispatch(l, r, o, c.kind);
1868                }
1869                let q = unsafe { dispatch_get_global_queue(0, 0) };
1870                unsafe {
1871                    dispatch_apply_f(n, q, &ctx as *const Ctx as *mut c_void, work);
1872                }
1873            }
1874
1875            #[cfg(not(target_os = "macos"))]
1876            {
1877                // Rayon global thread pool — threads pre-spawned, ~0.5µs dispatch.
1878                use rayon::prelude::*;
1879                (0..n).into_par_iter().for_each(|t| {
1880                    let start = t * chunk;
1881                    let end = (start + chunk).min(len);
1882                    if start >= end {
1883                        return;
1884                    }
1885                    let l = unsafe {
1886                        std::slice::from_raw_parts((lp as *const f32).add(start), end - start)
1887                    };
1888                    let r = unsafe {
1889                        std::slice::from_raw_parts((rp as *const f32).add(start), end - start)
1890                    };
1891                    let o = unsafe {
1892                        std::slice::from_raw_parts_mut((op as *mut f32).add(start), end - start)
1893                    };
1894                    simd::binary_dispatch(l, r, o, kind);
1895                });
1896            }
1897
1898            return Ok(Tensor::from_raw_parts(
1899                self.shape(),
1900                self.strides(),
1901                out_data,
1902            ));
1903        }
1904
1905        simd::binary_dispatch(self.data(), rhs.data(), &mut out_data, kind);
1906        Ok(Tensor::from_raw_parts(
1907            self.shape(),
1908            self.strides(),
1909            out_data,
1910        ))
1911    }
1912
1913    #[allow(unsafe_code)]
1914    fn binary_same_shape<F>(&self, rhs: &Self, op: F) -> Result<Self, TensorError>
1915    where
1916        F: Fn(f32, f32) -> f32,
1917    {
1918        let len = self.len();
1919        // SAFETY: `uninitialized` allocates without zeroing.  The loop below
1920        // writes every element before we ever read from `out_data`.
1921        let mut out_data = AlignedVec::<f32>::uninitialized(len);
1922
1923        let lhs_ptr = self.data().as_ptr();
1924        let rhs_ptr = rhs.data().as_ptr();
1925        let out_ptr = out_data.as_mut_ptr();
1926
1927        // SAFETY:
1928        // - Pointers originate from valid slices/vectors of length `len`.
1929        // - Loop bounds guarantee all pointer arithmetic remains in-bounds.
1930        // - `out_data` is uniquely mutable and does not alias with input buffers.
1931        unsafe {
1932            let mut index = 0usize;
1933            while index + 4 <= len {
1934                *out_ptr.add(index) = op(*lhs_ptr.add(index), *rhs_ptr.add(index));
1935                *out_ptr.add(index + 1) = op(*lhs_ptr.add(index + 1), *rhs_ptr.add(index + 1));
1936                *out_ptr.add(index + 2) = op(*lhs_ptr.add(index + 2), *rhs_ptr.add(index + 2));
1937                *out_ptr.add(index + 3) = op(*lhs_ptr.add(index + 3), *rhs_ptr.add(index + 3));
1938                index += 4;
1939            }
1940            while index < len {
1941                *out_ptr.add(index) = op(*lhs_ptr.add(index), *rhs_ptr.add(index));
1942                index += 1;
1943            }
1944        }
1945
1946        Ok(Tensor::from_raw_parts(
1947            self.shape(),
1948            self.strides(),
1949            out_data,
1950        ))
1951    }
1952
1953    // ── In-place operations ──────────────────────────────────────────────
1954
1955    /// In-place ReLU: clamp negative values to zero.
1956    pub fn relu_inplace(&mut self) {
1957        simd::relu_inplace_dispatch(self.data_mut());
1958    }
1959
1960    /// In-place element-wise add from another tensor (must have same shape).
1961    pub fn add_inplace(&mut self, rhs: &Self) {
1962        debug_assert_eq!(self.len(), rhs.len());
1963        simd::add_inplace_dispatch(self.data_mut(), rhs.data());
1964    }
1965
1966    /// In-place add scalar to all elements.
1967    pub fn add_scalar_inplace(&mut self, s: f32) {
1968        simd::add_scalar_inplace_dispatch(self.data_mut(), s);
1969    }
1970
1971    /// In-place multiply all elements by scalar.
1972    pub fn mul_scalar_inplace(&mut self, s: f32) {
1973        simd::mul_scalar_inplace_dispatch(self.data_mut(), s);
1974    }
1975
1976    // ── Binary-into operations (write into pre-allocated output) ─────
1977
1978    /// Element-wise addition writing into a pre-allocated output tensor.
1979    /// `output`, `lhs`, and `rhs` must all have the same shape.
1980    pub fn add_into(output: &mut Self, lhs: &Self, rhs: &Self) {
1981        debug_assert_eq!(lhs.shape(), rhs.shape());
1982        debug_assert_eq!(lhs.shape(), output.shape());
1983        simd::binary_dispatch(
1984            lhs.data(),
1985            rhs.data(),
1986            output.data_mut(),
1987            simd::BinaryKind::Add,
1988        );
1989    }
1990
1991    /// Element-wise subtraction writing into a pre-allocated output tensor.
1992    /// `output`, `lhs`, and `rhs` must all have the same shape.
1993    pub fn sub_into(output: &mut Self, lhs: &Self, rhs: &Self) {
1994        debug_assert_eq!(lhs.shape(), rhs.shape());
1995        debug_assert_eq!(lhs.shape(), output.shape());
1996        simd::binary_dispatch(
1997            lhs.data(),
1998            rhs.data(),
1999            output.data_mut(),
2000            simd::BinaryKind::Sub,
2001        );
2002    }
2003
2004    /// Element-wise multiplication writing into a pre-allocated output tensor.
2005    /// `output`, `lhs`, and `rhs` must all have the same shape.
2006    pub fn mul_into(output: &mut Self, lhs: &Self, rhs: &Self) {
2007        debug_assert_eq!(lhs.shape(), rhs.shape());
2008        debug_assert_eq!(lhs.shape(), output.shape());
2009        simd::binary_dispatch(
2010            lhs.data(),
2011            rhs.data(),
2012            output.data_mut(),
2013            simd::BinaryKind::Mul,
2014        );
2015    }
2016}
2017
2018// ── atan2 helper ───────────────────────────────────────────────────
2019
2020/// Scalar atan2(y, x) using Cephes-style range reduction of atan.
2021///
2022/// Range-reduces the argument to [0, tan(pi/12)] ≈ [0, 0.268] using:
2023///   - If z > tan(3*pi/8) ≈ 2.414: atan(z) = pi/2 - atan(1/z)
2024///   - If z > tan(pi/8) ≈ 0.414: atan(z) = pi/4 + atan((z-1)/(z+1))
2025///
2026/// Then uses a degree-7 polynomial on the reduced argument.
2027/// Max error < 4e-7 across all inputs.
2028#[allow(clippy::excessive_precision)]
2029#[inline(always)]
2030fn fast_atan2_scalar(y: f32, x: f32) -> f32 {
2031    const PI: f32 = std::f32::consts::PI;
2032    const FRAC_PI_2: f32 = std::f32::consts::FRAC_PI_2;
2033    const FRAC_PI_4: f32 = std::f32::consts::FRAC_PI_4;
2034    const TAN_3PI_8: f32 = 2.414_213_6; // tan(3*pi/8) = 1 + sqrt(2)
2035    const TAN_PI_8: f32 = 0.414_213_57; // tan(pi/8) = sqrt(2) - 1
2036
2037    let ax = x.abs();
2038    let ay = y.abs();
2039
2040    // Compute atan(|y|/|x|) with range reduction
2041    let (num, den, swap) = if ax >= ay {
2042        (ay, ax, false)
2043    } else {
2044        (ax, ay, true)
2045    };
2046    let z = if den > 0.0 { num / den } else { 0.0 };
2047
2048    // Range reduction for atan(z), z >= 0
2049    let (z_red, bias) = if z > TAN_3PI_8 {
2050        // Should not happen since z <= 1 from our swap, but just in case
2051        (-1.0 / z, FRAC_PI_2)
2052    } else if z > TAN_PI_8 {
2053        ((z - 1.0) / (z + 1.0), FRAC_PI_4)
2054    } else {
2055        (z, 0.0)
2056    };
2057
2058    // Polynomial: atan(z) ≈ z + z³·P(z²) for small z
2059    // Coefficients from Cephes atanf.c (S. Moshier), reordered for Horner.
2060    let z2 = z_red * z_red;
2061    let p: f32 = 8.054_666e-02;
2062    let p = p.mul_add(z2, -1.384_895_1e-01);
2063    let p = p.mul_add(z2, 1.997_075_8e-01);
2064    let p = p.mul_add(z2, -3.333_129_8e-01);
2065    let atan_z = z_red.mul_add(z2 * p, z_red) + bias;
2066
2067    // If we swapped: atan(|y|/|x|) = pi/2 - atan(|x|/|y|)
2068    let mut result = if swap { FRAC_PI_2 - atan_z } else { atan_z };
2069
2070    // Quadrant correction
2071    if x < 0.0 {
2072        result = PI - result;
2073    }
2074    if y < 0.0 {
2075        result = -result;
2076    }
2077
2078    result
2079}
2080
2081// ── FP16 conversion utilities ──────────────────────────────────────
2082
2083/// Convert f32 to IEEE 754 half-precision (FP16) bit pattern.
2084fn f32_to_fp16(val: f32) -> u16 {
2085    let bits = val.to_bits();
2086    let sign = ((bits >> 16) & 0x8000) as u16;
2087    let exponent = ((bits >> 23) & 0xFF) as i32;
2088    let mantissa = bits & 0x007F_FFFF;
2089
2090    if exponent == 255 {
2091        // Inf or NaN
2092        return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 };
2093    }
2094
2095    let unbiased = exponent - 127;
2096    if unbiased > 15 {
2097        return sign | 0x7C00; // overflow -> Inf
2098    }
2099    if unbiased < -24 {
2100        return sign; // underflow -> zero
2101    }
2102    if unbiased < -14 {
2103        // subnormal FP16
2104        let shift = -1 - unbiased;
2105        let m = (mantissa | 0x0080_0000) >> (shift + 13);
2106        return sign | m as u16;
2107    }
2108
2109    let fp16_exp = ((unbiased + 15) as u16) << 10;
2110    let fp16_man = (mantissa >> 13) as u16;
2111    sign | fp16_exp | fp16_man
2112}
2113
2114impl Tensor {
2115    // ── Sort / argsort / unique / nonzero ──────────────────────────────
2116
2117    /// Sort along `dim`. Returns `(sorted_values, sorted_indices)`.
2118    ///
2119    /// If `descending` is true, values are sorted largest-first.
2120    pub fn sort(&self, dim: usize, descending: bool) -> Result<(Self, Self), TensorError> {
2121        if dim >= self.rank() {
2122            return Err(TensorError::InvalidAxis {
2123                axis: dim,
2124                rank: self.rank(),
2125            });
2126        }
2127        let shape = self.shape();
2128        let outer: usize = shape[..dim].iter().product();
2129        let dim_len = shape[dim];
2130        let inner: usize = shape[dim + 1..].iter().product();
2131        let data = self.data();
2132
2133        let mut out_vals = vec![0.0f32; data.len()];
2134        let mut out_idxs = vec![0.0f32; data.len()];
2135
2136        for o in 0..outer {
2137            for i in 0..inner {
2138                let mut idx_vec: Vec<usize> = (0..dim_len).collect();
2139                idx_vec.sort_unstable_by(|&a, &b| {
2140                    let va = data[(o * dim_len + a) * inner + i];
2141                    let vb = data[(o * dim_len + b) * inner + i];
2142                    if descending {
2143                        vb.partial_cmp(&va).unwrap_or(std::cmp::Ordering::Equal)
2144                    } else {
2145                        va.partial_cmp(&vb).unwrap_or(std::cmp::Ordering::Equal)
2146                    }
2147                });
2148                for (rank, &src) in idx_vec.iter().enumerate() {
2149                    let dst = (o * dim_len + rank) * inner + i;
2150                    let src_pos = (o * dim_len + src) * inner + i;
2151                    out_vals[dst] = data[src_pos];
2152                    out_idxs[dst] = src as f32;
2153                }
2154            }
2155        }
2156
2157        let v = Tensor::from_vec(shape.to_vec(), out_vals)?;
2158        let idx = Tensor::from_vec(shape.to_vec(), out_idxs)?;
2159        Ok((v, idx))
2160    }
2161
2162    /// Return indices that would sort along `dim`.
2163    pub fn argsort(&self, dim: usize, descending: bool) -> Result<Self, TensorError> {
2164        let (_, indices) = self.sort(dim, descending)?;
2165        Ok(indices)
2166    }
2167
2168    /// Return unique elements (sorted), inverse indices, and counts.
2169    pub fn unique(&self) -> (Self, Self, Self) {
2170        let data = self.data();
2171        let mut sorted: Vec<f32> = data.to_vec();
2172        sorted.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2173        sorted.dedup();
2174
2175        let mut inverse = vec![0.0f32; data.len()];
2176        let mut counts = vec![0.0f32; sorted.len()];
2177        for (i, &v) in data.iter().enumerate() {
2178            let pos = sorted
2179                .binary_search_by(|probe| {
2180                    probe.partial_cmp(&v).unwrap_or(std::cmp::Ordering::Equal)
2181                })
2182                .expect("value exists in sorted list");
2183            inverse[i] = pos as f32;
2184            counts[pos] += 1.0;
2185        }
2186
2187        let vals = Tensor::from_vec(vec![sorted.len()], sorted).expect("unique vals");
2188        let inv = Tensor::from_vec(self.shape().to_vec(), inverse).expect("unique inv");
2189        let cnt = Tensor::from_vec(vec![counts.len()], counts).expect("unique counts");
2190        (vals, inv, cnt)
2191    }
2192
2193    /// Return coordinates of nonzero elements as a 2D tensor `[N, rank]`.
2194    pub fn nonzero(&self) -> Self {
2195        let shape = self.shape();
2196        let rank = shape.len().max(1);
2197        let data = self.data();
2198        let mut coords: Vec<Vec<usize>> = Vec::new();
2199
2200        if shape.is_empty() {
2201            // scalar
2202            if data[0] != 0.0 {
2203                coords.push(vec![0]);
2204            }
2205        } else {
2206            let mut idx = vec![0usize; shape.len()];
2207            for pos in 0..data.len() {
2208                if data[pos] != 0.0 {
2209                    coords.push(idx.clone());
2210                }
2211                // increment multi-dim index
2212                for d in (0..shape.len()).rev() {
2213                    idx[d] += 1;
2214                    if idx[d] < shape[d] {
2215                        break;
2216                    }
2217                    idx[d] = 0;
2218                }
2219            }
2220        }
2221
2222        let n = coords.len();
2223        let mut flat = Vec::with_capacity(n * rank);
2224        for c in &coords {
2225            for &v in c {
2226                flat.push(v as f32);
2227            }
2228        }
2229        if n == 0 {
2230            Tensor::from_vec(vec![0, rank], flat).expect("nonzero empty")
2231        } else {
2232            Tensor::from_vec(vec![n, rank], flat).expect("nonzero")
2233        }
2234    }
2235
2236    // ── Flip / roll ────────────────────────────────────────────────────
2237
2238    /// Reverse elements along the given dimensions.
2239    pub fn flip(&self, dims: &[usize]) -> Result<Self, TensorError> {
2240        for &d in dims {
2241            if d >= self.rank() {
2242                return Err(TensorError::InvalidAxis {
2243                    axis: d,
2244                    rank: self.rank(),
2245                });
2246            }
2247        }
2248        let shape = self.shape();
2249        let data = self.data();
2250        let total = data.len();
2251        let mut out = vec![0.0f32; total];
2252        let rank = shape.len();
2253
2254        let mut src_idx = vec![0usize; rank];
2255        for pos in 0..total {
2256            // compute destination index by flipping specified dims
2257            let mut dst_idx = src_idx.clone();
2258            for &d in dims {
2259                dst_idx[d] = shape[d] - 1 - src_idx[d];
2260            }
2261            // linear offset
2262            let mut dst_pos = 0;
2263            let mut stride = 1;
2264            for d in (0..rank).rev() {
2265                dst_pos += dst_idx[d] * stride;
2266                stride *= shape[d];
2267            }
2268            out[dst_pos] = data[pos];
2269
2270            // increment src_idx
2271            for d in (0..rank).rev() {
2272                src_idx[d] += 1;
2273                if src_idx[d] < shape[d] {
2274                    break;
2275                }
2276                src_idx[d] = 0;
2277            }
2278        }
2279        Tensor::from_vec(shape.to_vec(), out)
2280    }
2281
2282    /// Circular shift elements along `dim` by `shift` positions.
2283    pub fn roll(&self, shift: i64, dim: usize) -> Result<Self, TensorError> {
2284        if dim >= self.rank() {
2285            return Err(TensorError::InvalidAxis {
2286                axis: dim,
2287                rank: self.rank(),
2288            });
2289        }
2290        let shape = self.shape();
2291        let outer: usize = shape[..dim].iter().product();
2292        let dim_len = shape[dim];
2293        let inner: usize = shape[dim + 1..].iter().product();
2294        let data = self.data();
2295
2296        let mut out = vec![0.0f32; data.len()];
2297        for o in 0..outer {
2298            for d in 0..dim_len {
2299                let dst_d = ((d as i64 + shift).rem_euclid(dim_len as i64)) as usize;
2300                for i in 0..inner {
2301                    out[(o * dim_len + dst_d) * inner + i] = data[(o * dim_len + d) * inner + i];
2302                }
2303            }
2304        }
2305        Tensor::from_vec(shape.to_vec(), out)
2306    }
2307
2308    // ── Factory: linspace / arange / meshgrid ──────────────────────────
2309
2310    /// Create a 1-D tensor of `steps` evenly spaced values from `start` to `end` (inclusive).
2311    pub fn linspace(start: f32, end: f32, steps: usize) -> Result<Self, TensorError> {
2312        if steps == 0 {
2313            return Tensor::from_vec(vec![0], vec![]);
2314        }
2315        if steps == 1 {
2316            return Tensor::from_vec(vec![1], vec![start]);
2317        }
2318        let step = (end - start) / (steps - 1) as f32;
2319        let data: Vec<f32> = (0..steps).map(|i| start + step * i as f32).collect();
2320        Tensor::from_vec(vec![steps], data)
2321    }
2322
2323    /// Create a 1-D tensor with values in `[start, end)` with given `step`.
2324    pub fn arange(start: f32, end: f32, step: f32) -> Result<Self, TensorError> {
2325        if step == 0.0 {
2326            return Err(TensorError::ShapeMismatch {
2327                left: vec![],
2328                right: vec![],
2329            });
2330        }
2331        let mut data = Vec::new();
2332        let mut v = start;
2333        if step > 0.0 {
2334            while v < end {
2335                data.push(v);
2336                v += step;
2337            }
2338        } else {
2339            while v > end {
2340                data.push(v);
2341                v += step;
2342            }
2343        }
2344        let n = data.len();
2345        Tensor::from_vec(vec![n], data)
2346    }
2347
2348    /// Create coordinate grids from 1-D tensors (numpy-style `meshgrid` with `indexing='ij'`).
2349    pub fn meshgrid(tensors: &[Self]) -> Result<Vec<Self>, TensorError> {
2350        let shape: Vec<usize> = tensors.iter().map(|t| t.len()).collect();
2351        let total: usize = shape.iter().product();
2352        let n = tensors.len();
2353        let mut result = Vec::with_capacity(n);
2354
2355        for (idx, t) in tensors.iter().enumerate() {
2356            let t_data = t.data();
2357            let mut out = vec![0.0f32; total];
2358            // stride pattern: product of dims after idx
2359            let inner: usize = shape[idx + 1..].iter().product();
2360            let outer: usize = shape[..idx].iter().product();
2361            let dim_len = shape[idx];
2362            for o in 0..outer {
2363                for d in 0..dim_len {
2364                    for i in 0..inner {
2365                        out[(o * dim_len + d) * inner + i] = t_data[d];
2366                    }
2367                }
2368            }
2369            result.push(Tensor::from_vec(shape.clone(), out)?);
2370        }
2371        Ok(result)
2372    }
2373
2374    // ── Advanced indexing extras ────────────────────────────────────────
2375
2376    /// Select elements where `mask` (f32, nonzero = true) is true, returned as 1-D.
2377    pub fn boolean_mask(&self, mask: &Self) -> Result<Self, TensorError> {
2378        if self.shape() != mask.shape() {
2379            return Err(TensorError::ShapeMismatch {
2380                left: self.shape().to_vec(),
2381                right: mask.shape().to_vec(),
2382            });
2383        }
2384        let data = self.data();
2385        let m = mask.data();
2386        let out: Vec<f32> = data
2387            .iter()
2388            .zip(m.iter())
2389            .filter(|(_, mv)| **mv != 0.0)
2390            .map(|(v, _)| *v)
2391            .collect();
2392        let n = out.len();
2393        Tensor::from_vec(vec![n], out)
2394    }
2395
2396    /// Select slices along `dim` using integer `indices` tensor (1-D).
2397    pub fn index_select(&self, dim: usize, indices: &Self) -> Result<Self, TensorError> {
2398        if dim >= self.rank() {
2399            return Err(TensorError::InvalidAxis {
2400                axis: dim,
2401                rank: self.rank(),
2402            });
2403        }
2404        let shape = self.shape();
2405        let idx_data = indices.data();
2406        let n_idx = idx_data.len();
2407        let outer: usize = shape[..dim].iter().product();
2408        let dim_len = shape[dim];
2409        let inner: usize = shape[dim + 1..].iter().product();
2410        let data = self.data();
2411
2412        let mut out = Vec::with_capacity(outer * n_idx * inner);
2413        for o in 0..outer {
2414            for &idx_f in idx_data {
2415                let idx = idx_f as usize;
2416                if idx >= dim_len {
2417                    return Err(TensorError::IndexOutOfBounds {
2418                        axis: dim,
2419                        index: idx,
2420                        dim: dim_len,
2421                    });
2422                }
2423                let src_start = (o * dim_len + idx) * inner;
2424                out.extend_from_slice(&data[src_start..src_start + inner]);
2425            }
2426        }
2427
2428        let mut out_shape = shape.to_vec();
2429        out_shape[dim] = n_idx;
2430        Tensor::from_vec(out_shape, out)
2431    }
2432
2433    // ── Random tensor creation ──────────────────────────────────────────
2434
2435    /// Create a tensor filled with uniform random values in [0, 1).
2436    pub fn rand(shape: Vec<usize>, seed: u64) -> Result<Self, TensorError> {
2437        let n: usize = shape.iter().product();
2438        let mut rng = seed;
2439        let data: Vec<f32> = (0..n)
2440            .map(|_| {
2441                rng ^= rng << 13;
2442                rng ^= rng >> 7;
2443                rng ^= rng << 17;
2444                (rng as f32) / (u64::MAX as f32)
2445            })
2446            .collect();
2447        Self::from_vec(shape, data)
2448    }
2449
2450    /// Create a tensor filled with normally distributed random values (mean=0, std=1).
2451    /// Uses Box-Muller transform.
2452    pub fn randn(shape: Vec<usize>, seed: u64) -> Result<Self, TensorError> {
2453        let n: usize = shape.iter().product();
2454        let mut rng = seed;
2455        let mut next_rng = || -> f32 {
2456            rng ^= rng << 13;
2457            rng ^= rng >> 7;
2458            rng ^= rng << 17;
2459            // Map to (0, 1) exclusive to avoid log(0)
2460            ((rng as f64) / (u64::MAX as f64)).clamp(1e-15, 1.0 - 1e-15) as f32
2461        };
2462        let mut data = Vec::with_capacity(n);
2463        let mut i = 0;
2464        while i < n {
2465            let u1 = next_rng();
2466            let u2 = next_rng();
2467            let r = (-2.0 * (u1 as f64).ln()).sqrt();
2468            let theta = 2.0 * std::f64::consts::PI * u2 as f64;
2469            data.push((r * theta.cos()) as f32);
2470            i += 1;
2471            if i < n {
2472                data.push((r * theta.sin()) as f32);
2473                i += 1;
2474            }
2475        }
2476        Self::from_vec(shape, data)
2477    }
2478
2479    /// Create a tensor filled with random integers in [low, high).
2480    pub fn randint(shape: Vec<usize>, low: i64, high: i64, seed: u64) -> Result<Self, TensorError> {
2481        if high <= low {
2482            return Err(TensorError::UnsupportedOperation {
2483                msg: format!("randint requires high > low, got low={low}, high={high}"),
2484            });
2485        }
2486        let range = (high - low) as u64;
2487        let n: usize = shape.iter().product();
2488        let mut rng = seed;
2489        let data: Vec<f32> = (0..n)
2490            .map(|_| {
2491                rng ^= rng << 13;
2492                rng ^= rng >> 7;
2493                rng ^= rng << 17;
2494                (low + (rng % range) as i64) as f32
2495            })
2496            .collect();
2497        Self::from_vec(shape, data)
2498    }
2499
2500    /// Create a random permutation of integers [0, n).
2501    pub fn randperm(n: usize, seed: u64) -> Result<Self, TensorError> {
2502        let mut perm: Vec<f32> = (0..n).map(|i| i as f32).collect();
2503        let mut rng = seed;
2504        for i in (1..n).rev() {
2505            rng ^= rng << 13;
2506            rng ^= rng >> 7;
2507            rng ^= rng << 17;
2508            let j = (rng as usize) % (i + 1);
2509            perm.swap(i, j);
2510        }
2511        Self::from_vec(vec![n], perm)
2512    }
2513}
2514
2515// ── Advanced tensor operations ──────────────────────────────────────────
2516
2517impl Tensor {
2518    /// Slice with step: extract every `step`-th element along `dim` from `start` to `end`.
2519    pub fn step_slice(
2520        &self,
2521        dim: usize,
2522        start: usize,
2523        end: usize,
2524        step: usize,
2525    ) -> Result<Self, TensorError> {
2526        let rank = self.rank();
2527        if dim >= rank {
2528            return Err(TensorError::InvalidAxis { axis: dim, rank });
2529        }
2530        if step == 0 {
2531            return Err(TensorError::UnsupportedOperation {
2532                msg: "step must be > 0".to_string(),
2533            });
2534        }
2535        let shape = self.shape();
2536        let dim_len = shape[dim];
2537        let end = end.min(dim_len);
2538        if start >= end {
2539            // empty along this dim
2540            let mut out_shape = shape.to_vec();
2541            out_shape[dim] = 0;
2542            return Tensor::from_vec(out_shape, vec![]);
2543        }
2544
2545        let selected_indices: Vec<usize> = (start..end).step_by(step).collect();
2546        let new_dim = selected_indices.len();
2547
2548        let outer: usize = shape[..dim].iter().product();
2549        let inner: usize = shape[dim + 1..].iter().product();
2550        let data = self.data();
2551
2552        let mut out = Vec::with_capacity(outer * new_dim * inner);
2553        for o in 0..outer {
2554            for &idx in &selected_indices {
2555                let src_start = (o * dim_len + idx) * inner;
2556                out.extend_from_slice(&data[src_start..src_start + inner]);
2557            }
2558        }
2559
2560        let mut out_shape = shape.to_vec();
2561        out_shape[dim] = new_dim;
2562        Tensor::from_vec(out_shape, out)
2563    }
2564
2565    /// Einstein summation for common patterns.
2566    ///
2567    /// Supported equations:
2568    /// - `"ij,jk->ik"` — matrix multiply
2569    /// - `"ij->ji"` — transpose
2570    /// - `"ii->i"` — diagonal
2571    /// - `"ij->i"` — row sum
2572    /// - `"ij->j"` — column sum
2573    /// - `"ij->"` — total sum
2574    /// - `"i,i->"` — dot product
2575    /// - `"ij,ij->"` — Frobenius inner product
2576    pub fn einsum(equation: &str, tensors: &[&Tensor]) -> Result<Tensor, TensorError> {
2577        let equation = equation.replace(' ', "");
2578        let parts: Vec<&str> = equation.split("->").collect();
2579        if parts.len() != 2 {
2580            return Err(TensorError::UnsupportedOperation {
2581                msg: format!("invalid einsum equation: {equation}"),
2582            });
2583        }
2584        let inputs_str = parts[0];
2585        let output_str = parts[1];
2586        let input_parts: Vec<&str> = inputs_str.split(',').collect();
2587
2588        if input_parts.len() != tensors.len() {
2589            return Err(TensorError::UnsupportedOperation {
2590                msg: format!(
2591                    "einsum equation has {} inputs but {} tensors provided",
2592                    input_parts.len(),
2593                    tensors.len()
2594                ),
2595            });
2596        }
2597
2598        // Match known patterns
2599        let pattern = format!(
2600            "{}->{}",
2601            input_parts
2602                .iter()
2603                .map(|s| s.to_string())
2604                .collect::<Vec<_>>()
2605                .join(","),
2606            output_str
2607        );
2608
2609        match pattern.as_str() {
2610            // matrix multiply: ij,jk->ik
2611            "ij,jk->ik" => {
2612                let a = tensors[0];
2613                let b = tensors[1];
2614                if a.rank() != 2 || b.rank() != 2 {
2615                    return Err(TensorError::UnsupportedOperation {
2616                        msg: "ij,jk->ik requires 2D tensors".to_string(),
2617                    });
2618                }
2619                let (m, k1) = (a.shape()[0], a.shape()[1]);
2620                let (k2, n) = (b.shape()[0], b.shape()[1]);
2621                if k1 != k2 {
2622                    return Err(TensorError::ShapeMismatch {
2623                        left: a.shape().to_vec(),
2624                        right: b.shape().to_vec(),
2625                    });
2626                }
2627                let ad = a.data();
2628                let bd = b.data();
2629                let mut out = vec![0.0f32; m * n];
2630                for i in 0..m {
2631                    for j in 0..n {
2632                        let mut sum = 0.0f32;
2633                        for p in 0..k1 {
2634                            sum += ad[i * k1 + p] * bd[p * n + j];
2635                        }
2636                        out[i * n + j] = sum;
2637                    }
2638                }
2639                Tensor::from_vec(vec![m, n], out)
2640            }
2641            // transpose: ij->ji
2642            "ij->ji" => {
2643                let a = tensors[0];
2644                if a.rank() != 2 {
2645                    return Err(TensorError::UnsupportedOperation {
2646                        msg: "ij->ji requires a 2D tensor".to_string(),
2647                    });
2648                }
2649                let (rows, cols) = (a.shape()[0], a.shape()[1]);
2650                let ad = a.data();
2651                let mut out = vec![0.0f32; rows * cols];
2652                for i in 0..rows {
2653                    for j in 0..cols {
2654                        out[j * rows + i] = ad[i * cols + j];
2655                    }
2656                }
2657                Tensor::from_vec(vec![cols, rows], out)
2658            }
2659            // diagonal: ii->i
2660            "ii->i" => {
2661                let a = tensors[0];
2662                if a.rank() != 2 || a.shape()[0] != a.shape()[1] {
2663                    return Err(TensorError::UnsupportedOperation {
2664                        msg: "ii->i requires a square 2D tensor".to_string(),
2665                    });
2666                }
2667                let n = a.shape()[0];
2668                let ad = a.data();
2669                let out: Vec<f32> = (0..n).map(|i| ad[i * n + i]).collect();
2670                Tensor::from_vec(vec![n], out)
2671            }
2672            // row sum: ij->i
2673            "ij->i" => {
2674                let a = tensors[0];
2675                if a.rank() != 2 {
2676                    return Err(TensorError::UnsupportedOperation {
2677                        msg: "ij->i requires a 2D tensor".to_string(),
2678                    });
2679                }
2680                let (rows, cols) = (a.shape()[0], a.shape()[1]);
2681                let ad = a.data();
2682                let out: Vec<f32> = (0..rows)
2683                    .map(|i| ad[i * cols..(i + 1) * cols].iter().sum())
2684                    .collect();
2685                Tensor::from_vec(vec![rows], out)
2686            }
2687            // column sum: ij->j
2688            "ij->j" => {
2689                let a = tensors[0];
2690                if a.rank() != 2 {
2691                    return Err(TensorError::UnsupportedOperation {
2692                        msg: "ij->j requires a 2D tensor".to_string(),
2693                    });
2694                }
2695                let (rows, cols) = (a.shape()[0], a.shape()[1]);
2696                let ad = a.data();
2697                let mut out = vec![0.0f32; cols];
2698                for i in 0..rows {
2699                    for j in 0..cols {
2700                        out[j] += ad[i * cols + j];
2701                    }
2702                }
2703                Tensor::from_vec(vec![cols], out)
2704            }
2705            // total sum: ij->
2706            "ij->" => {
2707                let a = tensors[0];
2708                if a.rank() != 2 {
2709                    return Err(TensorError::UnsupportedOperation {
2710                        msg: "ij-> requires a 2D tensor".to_string(),
2711                    });
2712                }
2713                let sum: f32 = a.data().iter().sum();
2714                Ok(Tensor::scalar(sum))
2715            }
2716            // dot product: i,i->
2717            "i,i->" => {
2718                let a = tensors[0];
2719                let b = tensors[1];
2720                if a.rank() != 1 || b.rank() != 1 {
2721                    return Err(TensorError::UnsupportedOperation {
2722                        msg: "i,i-> requires 1D tensors".to_string(),
2723                    });
2724                }
2725                if a.shape()[0] != b.shape()[0] {
2726                    return Err(TensorError::ShapeMismatch {
2727                        left: a.shape().to_vec(),
2728                        right: b.shape().to_vec(),
2729                    });
2730                }
2731                let sum: f32 = a
2732                    .data()
2733                    .iter()
2734                    .zip(b.data().iter())
2735                    .map(|(x, y)| x * y)
2736                    .sum();
2737                Ok(Tensor::scalar(sum))
2738            }
2739            // Frobenius inner product: ij,ij->
2740            "ij,ij->" => {
2741                let a = tensors[0];
2742                let b = tensors[1];
2743                if a.rank() != 2 || b.rank() != 2 {
2744                    return Err(TensorError::UnsupportedOperation {
2745                        msg: "ij,ij-> requires 2D tensors".to_string(),
2746                    });
2747                }
2748                if a.shape() != b.shape() {
2749                    return Err(TensorError::ShapeMismatch {
2750                        left: a.shape().to_vec(),
2751                        right: b.shape().to_vec(),
2752                    });
2753                }
2754                let sum: f32 = a
2755                    .data()
2756                    .iter()
2757                    .zip(b.data().iter())
2758                    .map(|(x, y)| x * y)
2759                    .sum();
2760                Ok(Tensor::scalar(sum))
2761            }
2762            _ => Err(TensorError::UnsupportedOperation {
2763                msg: format!("unsupported einsum pattern: {pattern}"),
2764            }),
2765        }
2766    }
2767
2768    // ── Chunk ───────────────────────────────────────────────────────────
2769
2770    /// Split tensor into `n_chunks` pieces along `axis`. Last chunk may be smaller.
2771    pub fn chunk(&self, n_chunks: usize, axis: usize) -> Result<Vec<Self>, TensorError> {
2772        if axis >= self.rank() {
2773            return Err(TensorError::InvalidAxis {
2774                axis,
2775                rank: self.rank(),
2776            });
2777        }
2778        if n_chunks == 0 {
2779            return Err(TensorError::UnsupportedOperation {
2780                msg: "n_chunks must be > 0".to_string(),
2781            });
2782        }
2783        let dim = self.shape()[axis];
2784        let chunk_size = dim.div_ceil(n_chunks); // ceil division
2785        let mut chunks = Vec::new();
2786        let mut start = 0;
2787        while start < dim {
2788            let length = chunk_size.min(dim - start);
2789            chunks.push(self.narrow(axis, start, length)?);
2790            start += length;
2791        }
2792        Ok(chunks)
2793    }
2794
2795    // ── Histogram ───────────────────────────────────────────────────────
2796
2797    /// Counts elements in each bin, returns 1D tensor of shape `[bins]`.
2798    /// Bins are evenly spaced between `min` and `max`.
2799    pub fn histogram(&self, bins: usize, min: f32, max: f32) -> Result<Self, TensorError> {
2800        let mut counts = vec![0.0f32; bins];
2801        let range = max - min;
2802        for &v in self.data() {
2803            if v >= min && v <= max {
2804                let idx = if v == max {
2805                    bins - 1
2806                } else {
2807                    ((v - min) / range * bins as f32) as usize
2808                };
2809                counts[idx] += 1.0;
2810            }
2811        }
2812        Tensor::from_vec(vec![bins], counts)
2813    }
2814
2815    // ── Bincount ────────────────────────────────────────────────────────
2816
2817    /// Treats values as integer indices, counts occurrences.
2818    /// Returns 1D tensor of shape `[num_bins]`.
2819    pub fn bincount(&self, num_bins: usize) -> Result<Self, TensorError> {
2820        let mut counts = vec![0.0f32; num_bins];
2821        for &v in self.data() {
2822            let idx = v as usize;
2823            if idx < num_bins {
2824                counts[idx] += 1.0;
2825            }
2826        }
2827        Tensor::from_vec(vec![num_bins], counts)
2828    }
2829
2830    // ── Scalar convenience ──────────────────────────────────────────────
2831
2832    /// Returns the single scalar value if tensor has exactly one element.
2833    /// Errors if tensor has more than one element.
2834    pub fn item(&self) -> Result<f32, TensorError> {
2835        if self.len() != 1 {
2836            return Err(TensorError::ShapeMismatch {
2837                left: vec![1],
2838                right: self.shape().to_vec(),
2839            });
2840        }
2841        Ok(self.data()[0])
2842    }
2843
2844    /// Returns true if tensor has exactly one element.
2845    pub fn is_scalar(&self) -> bool {
2846        self.len() == 1
2847    }
2848
2849    // ── Scatter Add ──────────────────────────────────────────────────
2850
2851    /// Like `scatter` but adds instead of replacing values.
2852    ///
2853    /// For `dim=1`: `self[i][index[i][j][k]][k] += src[i][j][k]`
2854    pub fn scatter_add(&self, dim: usize, index: &Self, src: &Self) -> Result<Self, TensorError> {
2855        if dim >= self.rank() {
2856            return Err(TensorError::InvalidAxis {
2857                axis: dim,
2858                rank: self.rank(),
2859            });
2860        }
2861        if index.rank() != self.rank() {
2862            return Err(TensorError::InvalidIndexRank {
2863                expected: self.rank(),
2864                got: index.rank(),
2865            });
2866        }
2867        if src.shape() != index.shape() {
2868            return Err(TensorError::ShapeMismatch {
2869                left: src.shape().to_vec(),
2870                right: index.shape().to_vec(),
2871            });
2872        }
2873
2874        let self_shape = self.shape();
2875        let idx_shape = index.shape();
2876        let idx_data = index.data();
2877        let src_data = src.data();
2878        let ndim = self.rank();
2879
2880        let mut out = self.data().to_vec();
2881        let mut coords = vec![0usize; ndim];
2882
2883        for pos in 0..index.len() {
2884            let idx_val = idx_data[pos] as usize;
2885            if idx_val >= self_shape[dim] {
2886                return Err(TensorError::IndexOutOfBounds {
2887                    axis: dim,
2888                    index: idx_val,
2889                    dim: self_shape[dim],
2890                });
2891            }
2892
2893            let mut dst_offset = 0;
2894            for d in 0..ndim {
2895                let c = if d == dim { idx_val } else { coords[d] };
2896                dst_offset += c * self.strides()[d];
2897            }
2898            out[dst_offset] += src_data[pos];
2899
2900            increment_coords(&mut coords, idx_shape);
2901        }
2902
2903        Tensor::from_vec(self_shape.to_vec(), out)
2904    }
2905}
2906
2907/// Convert IEEE 754 half-precision (FP16) bit pattern to f32.
2908fn fp16_to_f32(half: u16) -> f32 {
2909    let sign = ((half & 0x8000) as u32) << 16;
2910    let exponent = (half >> 10) & 0x1F;
2911    let mantissa = (half & 0x03FF) as u32;
2912
2913    if exponent == 0 {
2914        if mantissa == 0 {
2915            return f32::from_bits(sign); // zero
2916        }
2917        // subnormal
2918        let mut m = mantissa;
2919        let mut e = 0i32;
2920        while m & 0x0400 == 0 {
2921            m <<= 1;
2922            e += 1;
2923        }
2924        m &= 0x03FF;
2925        let f32_exp = ((127 - 15 - e) as u32) << 23;
2926        let f32_man = m << 13;
2927        return f32::from_bits(sign | f32_exp | f32_man);
2928    }
2929    if exponent == 31 {
2930        let f32_exp = 0xFF << 23;
2931        let f32_man = mantissa << 13;
2932        return f32::from_bits(sign | f32_exp | f32_man);
2933    }
2934
2935    let f32_exp = ((exponent as i32 - 15 + 127) as u32 & 0xFF) << 23;
2936    let f32_man = mantissa << 13;
2937    f32::from_bits(sign | f32_exp | f32_man)
2938}