Skip to main content

cortex_hybrid/tensor/
mod.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3pub mod finite;
4pub mod ops;
5
6use crate::error::{CortexError, Result, unwrap_compat};
7use serde::ser::SerializeStruct;
8use serde::{Deserialize, Serialize};
9use std::alloc::Layout;
10use std::fmt;
11
12/// Row-major dense tensor — a CPU-only reference backend.
13///
14/// Stores `f32` data in a single contiguous, row-major `Vec<f32>` addressed as
15/// `data[i * ncols + j]` (and the rank-`n` generalization). This layout is the
16/// one and only invariant: there are no strided views, no broadcasting outside
17/// the documented [`ops::batched_matmul`] case, and no device or dtype
18/// dispatch. External ML frameworks own general tensor abstractions; this crate
19/// deliberately stays a small, honest reference kernel.
20///
21/// [`Tensor`] does not carry a `strides` field. Because every element is
22/// contiguous and row-major, strides are fully determined by [`Self::shape`]
23/// and can be recomputed on demand with [`Tensor::row_major_strides`]; storing
24/// them would only invite the illusion of stride-aware kernels that do not
25/// exist.
26///
27/// # Layout and copies
28///
29/// [`Self::reshape`] and [`Self::transpose`] both return owned tensors backed
30/// by fresh buffers — they are copies, never aliasing views. [`Self::data_mut`]
31/// hands out the raw contiguous storage; callers must preserve the row-major
32/// element count for [`Self::shape`] (mutating length or reordering across rows
33/// breaks the contiguity invariant).
34///
35/// [`ops::batched_matmul`]: crate::tensor::ops::batched_matmul
36///
37/// # Construction
38///
39/// Prefer [`Tensor::try_from_vec`], which validates the element count and
40/// row-major stride arithmetic with checked multiplication before storing
41/// `data`. [`Tensor::from_vec`] and the other panic-style constructors remain
42/// as pre-1.0 compatibility wrappers; migrate new call sites to `try_from_vec`.
43///
44/// # Serialization
45///
46/// JSON is a versioned fixture format for this CPU reference backend, not a
47/// universal tensor interchange format. Version 1 carries `schema_version`,
48/// `data`, and `shape`; unknown fields, including legacy `strides`, are rejected.
49/// Non-finite values cannot be serialized to JSON. Deserialization checks the
50/// shape and row-major stride arithmetic through [`Self::try_from_vec`]. Use
51/// [`crate::reference_json::from_slice_with_limit`] for untrusted input.
52///
53/// # Rank-0 scalars vs zero-sized axes
54///
55/// - `shape == []` is a rank-0 scalar with exactly one element (`numel == 1`).
56/// - Any axis equal to `0` yields `numel == 0`, even when other extents would
57///   overflow if multiplied without checked arithmetic (for example
58///   `[usize::MAX, 0, 2]`).
59/// - Constructors and [`Deserialize`] reject shapes whose element count or
60///   row-major stride product is not representable in `usize` (see
61///   `checked_numel` and `try_compute_strides`).
62/// - [`Self::mean`] on a zero-element tensor is `0.0 / 0.0`, which is `NaN`.
63#[derive(Clone)]
64pub struct Tensor {
65    data: Vec<f32>,
66    shape: Vec<usize>,
67}
68
69#[derive(Deserialize)]
70#[serde(deny_unknown_fields)]
71struct TensorWire {
72    schema_version: u32,
73    data: Vec<f32>,
74    shape: Vec<usize>,
75}
76
77impl Serialize for Tensor {
78    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
79    where
80        S: serde::Serializer,
81    {
82        self.check_storage().map_err(serde::ser::Error::custom)?;
83        if self.data.iter().any(|value| !value.is_finite()) {
84            return Err(serde::ser::Error::custom(
85                "non-finite tensor data cannot be serialized",
86            ));
87        }
88        let mut wire = serializer.serialize_struct("Tensor", 3)?;
89        wire.serialize_field("schema_version", &1u32)?;
90        wire.serialize_field("data", &self.data)?;
91        wire.serialize_field("shape", &self.shape)?;
92        wire.end()
93    }
94}
95
96impl<'de> Deserialize<'de> for Tensor {
97    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
98    where
99        D: serde::Deserializer<'de>,
100    {
101        let wire: TensorWire = crate::reference_json::deserialize_object(deserializer)?;
102        if wire.schema_version != 1 {
103            return Err(serde::de::Error::custom(format!(
104                "unsupported Tensor schema_version {}",
105                wire.schema_version
106            )));
107        }
108        if wire.data.iter().any(|value| !value.is_finite()) {
109            return Err(serde::de::Error::custom("non-finite tensor data"));
110        }
111        Self::try_from_vec(wire.data, &wire.shape).map_err(serde::de::Error::custom)
112    }
113}
114
115/// Portable RNG behind every `*_seeded` constructor. ChaCha8 is a fixed,
116/// documented algorithm, unlike `StdRng`, whose stream may change between
117/// `rand` releases, so a `(config, seed)` pair keeps rebuilding the same
118/// weights. A golden test pins the stream.
119pub(crate) fn seeded_rng(seed: u64) -> rand_chacha::ChaCha8Rng {
120    use rand::SeedableRng;
121    rand_chacha::ChaCha8Rng::seed_from_u64(seed)
122}
123
124impl Tensor {
125    // ── Constructors ─────────────────────────────────────────────────
126
127    /// Constructs a tensor from a contiguous row-major buffer and shape.
128    ///
129    /// # Panics
130    ///
131    /// Panics if the shape product or stride arithmetic overflows `usize`, or
132    /// if `data.len()` does not equal the number of elements implied by
133    /// `shape`.
134    ///
135    /// Prefer [`Tensor::try_from_vec`] in new code. This wrapper is retained
136    /// for pre-1.0 source compatibility and will remain until a separate
137    /// SemVer decision removes panic-on-invalid-shape constructors.
138    pub fn from_vec(data: Vec<f32>, shape: &[usize]) -> Self {
139        unwrap_compat(Self::try_from_vec(data, shape), "Tensor::from_vec")
140    }
141
142    /// Fallible constructor: proves `numel` and row-major strides are
143    /// representable before taking ownership of `data`.
144    ///
145    /// Strides are not stored; the check exists only to reject shapes whose
146    /// row-major stride arithmetic would overflow `usize`, matching the
147    /// contiguity guarantees callers of [`Self::data`] rely on. Does not
148    /// allocate a new data buffer, so overflowing shapes fail without
149    /// attempting a giant allocation.
150    pub fn try_from_vec(data: Vec<f32>, shape: &[usize]) -> Result<Self> {
151        let numel = checked_numel(shape)?;
152        let _ = try_compute_strides(shape)?;
153        if data.len() != numel {
154            return Err(CortexError::ShapeMismatch {
155                expected: shape.to_vec(),
156                got: vec![data.len()],
157            });
158        }
159        Ok(Self {
160            data,
161            shape: shape.to_vec(),
162        })
163    }
164
165    /// Fills a tensor with zeros.
166    ///
167    /// # Panics
168    ///
169    /// Panics if the shape product or stride arithmetic overflows `usize`.
170    /// Prefer [`Tensor::try_zeros`] in new code.
171    pub fn zeros(shape: &[usize]) -> Self {
172        unwrap_compat(Self::try_zeros(shape), "Tensor::zeros")
173    }
174
175    /// Fallible [`Tensor::zeros`].
176    ///
177    /// Returns [`CortexError::SizeOverflow`] when the element count or strides
178    /// are not representable and [`CortexError::AllocationFailed`] when the
179    /// allocator refuses the reservation, instead of aborting through
180    /// `handle_alloc_error`. The same holds for `try_ones`, `try_full`,
181    /// `try_randn*`, and the ops that allocate a fresh output buffer from a
182    /// shape (`try_matmul`, `try_batched_matmul`, `try_layer_norm`,
183    /// `try_rms_norm`, `try_embedding`, `try_causal_mask`). Ops that copy an
184    /// existing tensor (`try_transpose`, `try_softmax_last`, elementwise and
185    /// activation methods) still allocate infallibly; see
186    /// the crate-private `try_reserve_f32` helper for that limitation and for
187    /// the overcommit caveat.
188    pub fn try_zeros(shape: &[usize]) -> Result<Self> {
189        try_filled(shape, 0.0)
190    }
191
192    /// Fills a tensor with ones.
193    ///
194    /// # Panics
195    ///
196    /// Panics if the shape product or stride arithmetic overflows `usize`.
197    /// See [`Tensor::from_vec`] for the pre-1.0 compatibility policy.
198    /// Prefer [`Tensor::try_ones`] in new code.
199    pub fn ones(shape: &[usize]) -> Self {
200        unwrap_compat(Self::try_ones(shape), "Tensor::ones")
201    }
202
203    /// Fallible [`Tensor::ones`].
204    pub fn try_ones(shape: &[usize]) -> Result<Self> {
205        try_filled(shape, 1.0)
206    }
207
208    /// Fills a tensor with `val`.
209    ///
210    /// # Panics
211    ///
212    /// Panics if the shape product or stride arithmetic overflows `usize`.
213    /// See [`Tensor::from_vec`] for the pre-1.0 compatibility policy.
214    /// Prefer [`Tensor::try_full`] in new code.
215    pub fn full(shape: &[usize], val: f32) -> Self {
216        unwrap_compat(Self::try_full(shape, val), "Tensor::full")
217    }
218
219    /// Fallible [`Tensor::full`].
220    pub fn try_full(shape: &[usize], val: f32) -> Result<Self> {
221        try_filled(shape, val)
222    }
223
224    /// Fills a tensor with i.i.d. normal samples.
225    ///
226    /// # Panics
227    ///
228    /// Panics if the shape product or stride arithmetic overflows `usize`,
229    /// if `mean` is not finite, if `std` is not finite or is negative, or if
230    /// a sample overflows `f32`. Prefer [`Tensor::try_randn`] in new code.
231    /// See [`Tensor::from_vec`] for the pre-1.0 compatibility policy.
232    pub fn randn(shape: &[usize], mean: f32, std: f32) -> Self {
233        unwrap_compat(Self::try_randn(shape, mean, std), "Tensor::randn")
234    }
235
236    /// Fallible [`Tensor::randn`]: fails on shape/stride overflow before
237    /// allocating, and with [`CortexError::InvalidConfig`] unless `mean` is
238    /// finite and `std` is finite and non-negative. Draws from the thread
239    /// RNG; use [`Tensor::try_randn_with_rng`] for reproducible values.
240    pub fn try_randn(shape: &[usize], mean: f32, std: f32) -> Result<Self> {
241        Self::try_randn_with_rng(shape, mean, std, &mut rand::rng())
242    }
243
244    /// Like [`Tensor::try_randn`] but draws from the caller's RNG, so a
245    /// seeded RNG reproduces the same tensor.
246    pub fn try_randn_with_rng<R: rand::Rng + ?Sized>(
247        shape: &[usize],
248        mean: f32,
249        std: f32,
250        rng: &mut R,
251    ) -> Result<Self> {
252        use rand::RngExt;
253        if !mean.is_finite() || !std.is_finite() || std < 0.0 {
254            return Err(CortexError::InvalidConfig(format!(
255                "randn: mean ({mean}) must be finite and std ({std}) must be finite and >= 0"
256            )));
257        }
258        let numel = checked_alloc_len(shape)?;
259        let mut data = try_reserve_f32(numel, shape)?;
260        // Box-Muller: each (u1, u2) pair yields two independent samples.
261        while data.len() < numel {
262            // u1 in (0, 1] so ln(u1) is finite without clamping the tails.
263            let u1: f32 = 1.0 - rng.random_range(0.0f32..1.0);
264            let u2: f32 = rng.random_range(0.0f32..1.0);
265            let r = (-2.0f32 * u1.ln()).sqrt();
266            let (sin, cos) = (2.0f32 * std::f32::consts::PI * u2).sin_cos();
267            data.push(mean + std * r * cos);
268            if data.len() < numel {
269                data.push(mean + std * r * sin);
270            }
271        }
272        // A finite but huge `std` (or `mean`) can still overflow to inf/NaN.
273        if data.iter().any(|v| !v.is_finite()) {
274            return Err(CortexError::InvalidConfig(format!(
275                "randn: mean ({mean}) and std ({std}) overflow f32 while sampling"
276            )));
277        }
278        Self::try_from_vec(data, shape)
279    }
280
281    // ── Accessors ────────────────────────────────────────────────────
282
283    #[inline]
284    pub fn data(&self) -> &[f32] {
285        &self.data
286    }
287
288    /// Mutable access to the raw contiguous, row-major storage.
289    ///
290    /// The slice length equals [`Self::numel`] and is addressed as
291    /// `data[i * ncols + j]`. Callers may overwrite values in place but must
292    /// not rely on any layout other than contiguous row-major, and must not
293    /// assume the length can change: [`Self::shape`] is unaffected by writes
294    /// here, so reinterpreting the buffer under a different shape requires
295    /// [`Self::reshape`] (which copies).
296    #[inline]
297    pub fn data_mut(&mut self) -> &mut [f32] {
298        &mut self.data
299    }
300
301    #[inline]
302    pub fn shape(&self) -> &[usize] {
303        &self.shape
304    }
305
306    /// Recomputes the row-major strides implied by [`Self::shape`].
307    ///
308    /// Strides are not stored: this tensor is always contiguous row-major, so
309    /// they are a pure function of the shape. The last stride is `1` and each
310    /// earlier stride is the product of the following extents. Returns an empty
311    /// vector for a scalar (rank-0) shape.
312    ///
313    /// # Panics
314    ///
315    /// Panics only if the stride product overflows `usize`, which cannot happen
316    /// for a tensor built through the crate's constructors (they reject such
317    /// shapes up front). Use [`Self::try_row_major_strides`] to recover instead
318    /// of panicking on a hand-corrupted shape.
319    #[inline]
320    pub fn row_major_strides(&self) -> Vec<usize> {
321        unwrap_compat(self.try_row_major_strides(), "Tensor::row_major_strides")
322    }
323
324    /// Fallible [`Self::row_major_strides`]: returns
325    /// [`CortexError::SizeOverflow`] if the row-major stride product is not
326    /// representable in `usize`.
327    #[inline]
328    pub fn try_row_major_strides(&self) -> Result<Vec<usize>> {
329        try_compute_strides(&self.shape)
330    }
331
332    #[inline]
333    pub fn numel(&self) -> usize {
334        self.data.len()
335    }
336
337    #[inline]
338    pub fn ndim(&self) -> usize {
339        self.shape.len()
340    }
341
342    // ── Reshape / transpose (copying) ────────────────────────────────
343
344    /// Reshapes to `new_shape`, which must imply the same element count.
345    ///
346    /// This **copies**. The returned tensor owns a fresh `Vec<f32>` cloned from
347    /// `self`; it does not alias `self`'s storage. Because the layout is always
348    /// contiguous row-major, the reinterpretation is a no-op on the element
349    /// order — only the shape metadata changes. To avoid the clone entirely,
350    /// reinterpret in place with [`Self::reshape_in_place`].
351    ///
352    /// # Panics
353    ///
354    /// Panics if the element count changes or the new shape overflows.
355    /// Prefer [`Tensor::try_reshape`] in new code.
356    pub fn reshape(&self, new_shape: &[usize]) -> Self {
357        unwrap_compat(self.try_reshape(new_shape), "Tensor::reshape")
358    }
359
360    /// Fallible reshape (copying): `new_shape` must imply exactly
361    /// `self.numel()` elements and have representable row-major strides.
362    ///
363    /// See [`Self::reshape`]: the result is a copy, not a view.
364    pub fn try_reshape(&self, new_shape: &[usize]) -> Result<Self> {
365        self.check_storage()?;
366        let numel = checked_numel(new_shape)?;
367        if numel != self.numel() {
368            return Err(CortexError::ShapeMismatch {
369                expected: self.shape.clone(),
370                got: new_shape.to_vec(),
371            });
372        }
373        Self::try_from_vec(self.data.clone(), new_shape)
374    }
375
376    /// Reinterprets `self` under `new_shape` in place, without copying.
377    ///
378    /// Because the storage is already contiguous row-major, a reshape only
379    /// rewrites the shape metadata. This variant mutates `self` and reuses the
380    /// existing buffer instead of cloning, which [`Self::reshape`] cannot do
381    /// behind `&self`. `new_shape` must imply exactly `self.numel()` elements
382    /// and have representable row-major strides.
383    ///
384    /// On error the shape is validated **before** any mutation, so `self` is
385    /// left completely unchanged and remains usable: returns
386    /// [`CortexError::ShapeMismatch`] on an element-count change and
387    /// [`CortexError::SizeOverflow`] on stride overflow.
388    pub fn reshape_in_place(&mut self, new_shape: &[usize]) -> Result<()> {
389        self.check_storage()?;
390        let numel = checked_numel(new_shape)?;
391        if numel != self.numel() {
392            return Err(CortexError::ShapeMismatch {
393                expected: self.shape.clone(),
394                got: new_shape.to_vec(),
395            });
396        }
397        try_compute_strides(new_shape)?;
398        self.shape = new_shape.to_vec();
399        Ok(())
400    }
401
402    /// Transposes a 2-D tensor: `[rows, cols]` → `[cols, rows]`.
403    ///
404    /// This **materializes** a new tensor: the returned buffer is a fresh,
405    /// contiguous row-major reordering of the elements, not a stride-swapped
406    /// view over `self`'s storage.
407    ///
408    /// # Panics
409    ///
410    /// Panics if `self` is not rank-2. Prefer [`Tensor::try_transpose`].
411    pub fn transpose(&self) -> Self {
412        unwrap_compat(self.try_transpose(), "Tensor::transpose")
413    }
414
415    /// Fallible transpose (materializing): returns [`CortexError::RankMismatch`]
416    /// unless `self` is rank-2. See [`Self::transpose`]: the result is a copy,
417    /// not a view.
418    pub fn try_transpose(&self) -> Result<Self> {
419        self.check_storage()?;
420        if self.ndim() != 2 {
421            return Err(CortexError::RankMismatch {
422                expected: 2,
423                got: self.ndim(),
424            });
425        }
426        let (rows, cols) = (self.shape[0], self.shape[1]);
427        if rows == 0 || cols == 0 {
428            // Nothing to copy. Returning here matters: `[usize::MAX, 0]` has
429            // numel 0 but would otherwise iterate the huge axis.
430            return Self::try_from_vec(Vec::new(), &[cols, rows]);
431        }
432        let out_len = checked_numel(&[cols, rows])?;
433        let mut out = Vec::with_capacity(out_len);
434        // Output row `c` is input column `c`: elements `c, c + cols, ...`.
435        // Striding the iterator avoids computing `c * rows + r` offsets, so
436        // no index arithmetic can overflow.
437        for c in 0..cols {
438            out.extend(self.data.iter().skip(c).step_by(cols));
439        }
440        Self::try_from_vec(out, &[cols, rows])
441    }
442
443    // ── Element-wise ops ─────────────────────────────────────────────
444
445    /// Element-wise addition. Both tensors must have identical shapes.
446    ///
447    /// # Panics
448    ///
449    /// Panics on shape mismatch. Prefer [`Tensor::try_add`] in new code.
450    pub fn add(&self, other: &Tensor) -> Self {
451        unwrap_compat(self.try_add(other), "Tensor::add")
452    }
453
454    /// Fallible element-wise addition.
455    pub fn try_add(&self, other: &Tensor) -> Result<Self> {
456        self.try_elementwise(other, |a, b| a + b)
457    }
458
459    /// Element-wise subtraction. Both tensors must have identical shapes.
460    ///
461    /// # Panics
462    ///
463    /// Panics on shape mismatch. Prefer [`Tensor::try_sub`] in new code.
464    pub fn sub(&self, other: &Tensor) -> Self {
465        unwrap_compat(self.try_sub(other), "Tensor::sub")
466    }
467
468    /// Fallible element-wise subtraction.
469    pub fn try_sub(&self, other: &Tensor) -> Result<Self> {
470        self.try_elementwise(other, |a, b| a - b)
471    }
472
473    /// Element-wise multiplication. Both tensors must have identical shapes.
474    ///
475    /// # Panics
476    ///
477    /// Panics on shape mismatch. Prefer [`Tensor::try_mul`] in new code.
478    pub fn mul(&self, other: &Tensor) -> Self {
479        unwrap_compat(self.try_mul(other), "Tensor::mul")
480    }
481
482    /// Fallible element-wise multiplication.
483    pub fn try_mul(&self, other: &Tensor) -> Result<Self> {
484        self.try_elementwise(other, |a, b| a * b)
485    }
486
487    fn try_elementwise(&self, other: &Tensor, f: impl Fn(f32, f32) -> f32) -> Result<Self> {
488        if self.shape != other.shape {
489            return Err(CortexError::ShapeMismatch {
490                expected: self.shape.clone(),
491                got: other.shape.clone(),
492            });
493        }
494        let data: Vec<f32> = self
495            .data
496            .iter()
497            .zip(other.data.iter())
498            .map(|(&a, &b)| f(a, b))
499            .collect();
500        Self::try_from_vec(data, &self.shape)
501    }
502
503    pub fn scale(&self, s: f32) -> Self {
504        let data: Vec<f32> = self.data.iter().map(|x| x * s).collect();
505        Self::from_vec(data, &self.shape)
506    }
507
508    pub fn add_scalar(&self, s: f32) -> Self {
509        let data: Vec<f32> = self.data.iter().map(|x| x + s).collect();
510        Self::from_vec(data, &self.shape)
511    }
512
513    // ── Activation functions ─────────────────────────────────────────
514
515    // Elementwise activations follow the finite-value policy in
516    // [`finite`](crate::tensor::finite): NaN propagates, `±Inf` maps to the
517    // function's mathematical limit, finite inputs give finite outputs.
518
519    /// Rectified linear unit, `max(x, 0)` with NaN propagation.
520    ///
521    /// `f32::max` is not used because it discards NaN. NaN inputs stay NaN,
522    /// `+Inf` stays `+Inf`, and every non-positive input (including `-0.0`
523    /// and `-Inf`) is written as canonical `+0.0`.
524    pub fn relu(&self) -> Self {
525        let data: Vec<f32> = self
526            .data
527            .iter()
528            .map(|&x| if x.is_nan() || x > 0.0 { x } else { 0.0 })
529            .collect();
530        Self::from_vec(data, &self.shape)
531    }
532
533    /// Tanh-approximate GELU: `x * 0.5 * (1 + tanh(sqrt(2/π) * (x + 0.044715 x³)))`.
534    ///
535    /// `+Inf` gives `+Inf` and `-Inf` gives `0` (the limits), instead of the
536    /// NaN that `-Inf * 0` would produce. NaN propagates.
537    pub fn gelu(&self) -> Self {
538        let data: Vec<f32> = self
539            .data
540            .iter()
541            .map(|&x| {
542                if x.is_infinite() {
543                    return if x.is_sign_positive() { x } else { 0.0 };
544                }
545                let c = (2.0f32 / std::f32::consts::PI).sqrt();
546                x * 0.5 * (1.0 + (c * (x + 0.044715 * x * x * x)).tanh())
547            })
548            .collect();
549        Self::from_vec(data, &self.shape)
550    }
551
552    /// SiLU / swish: `x / (1 + exp(-x))`.
553    ///
554    /// `+Inf` gives `+Inf` and `-Inf` gives `0` (the limits), instead of the
555    /// NaN that `-Inf / Inf` would produce. NaN propagates.
556    pub fn silu(&self) -> Self {
557        let data: Vec<f32> = self
558            .data
559            .iter()
560            .map(|&x| {
561                if x.is_infinite() {
562                    return if x.is_sign_positive() { x } else { 0.0 };
563                }
564                x / (1.0 + (-x).exp())
565            })
566            .collect();
567        Self::from_vec(data, &self.shape)
568    }
569
570    /// Fast sigmoid surrogate gradient (from soma-engine's E-prop): `x / (1 + |x|)`.
571    ///
572    /// `±Inf` gives `±1` (the limits), instead of the NaN that `Inf / Inf`
573    /// would produce. NaN propagates.
574    pub fn fast_sigmoid(&self) -> Self {
575        let data: Vec<f32> = self
576            .data
577            .iter()
578            .map(|&x| {
579                if x.is_infinite() {
580                    return if x.is_sign_positive() { 1.0 } else { -1.0 };
581                }
582                x / (1.0 + x.abs())
583            })
584            .collect();
585        Self::from_vec(data, &self.shape)
586    }
587
588    // ── Reductions ───────────────────────────────────────────────────
589
590    /// Sum of all elements, accumulated in compensated `f64` and cast back to `f32`.
591    ///
592    /// Sequential Neumaier (Kahan-Babuška) `f64` accumulation keeps every
593    /// `f32` input exact, avoids the `f32` running-sum stall at `2^24` and
594    /// spurious intermediate overflow (`[MAX, MAX, -MAX]` sums to `MAX`), and
595    /// keeps a small term that plain `f64` would cancel away between two large
596    /// ones (`[MAX, 1e20, -MAX]` sums to `1e20`). The final cast follows
597    /// IEEE rounding: a true sum outside the `f32` range becomes `±Inf`. NaN
598    /// inputs propagate and `+Inf + -Inf` is NaN. An empty tensor sums to `0`.
599    pub fn sum(&self) -> f32 {
600        self.sum_f64() as f32
601    }
602
603    /// Arithmetic mean over all elements: the compensated `f64` total divided
604    /// by `numel()` in `f64`, then cast once to `f32` (not `sum() / numel()`).
605    ///
606    /// Returns `NaN` when `numel() == 0` (zero-sized axis or empty buffer).
607    pub fn mean(&self) -> f32 {
608        (self.sum_f64() / self.numel() as f64) as f32
609    }
610
611    /// Neumaier-compensated sequential `f64` sum (deterministic for a given
612    /// input bit pattern). Non-finite inputs fall through IEEE arithmetic:
613    /// NaN propagates and `+Inf + -Inf` is NaN.
614    fn sum_f64(&self) -> f64 {
615        let mut sum = 0.0f64;
616        let mut comp = 0.0f64;
617        for &x in &self.data {
618            let x = f64::from(x);
619            let t = sum + x;
620            if sum.abs() >= x.abs() {
621                comp += (sum - t) + x;
622            } else {
623                comp += (x - t) + sum;
624            }
625            sum = t;
626        }
627        if sum.is_finite() { sum + comp } else { sum }
628    }
629
630    /// Largest element.
631    ///
632    /// NaN policy: any NaN (either sign) makes the result NaN; `f32::max` is
633    /// not used because it silently discards NaN. Otherwise this is the
634    /// ordinary maximum, so `data()[argmax()] == max_val()` for NaN-free
635    /// input and both report NaN when a positive NaN is present. (A negative
636    /// NaN sorts below `-Inf` in [`argmax`](Self::argmax)'s total order but
637    /// still yields NaN here.) An empty tensor returns `-Inf`, the identity of
638    /// `max`.
639    pub fn max_val(&self) -> f32 {
640        let mut best = f32::NEG_INFINITY;
641        for &x in &self.data {
642            if x.is_nan() {
643                return f32::NAN;
644            }
645            if x > best {
646                best = x;
647            }
648        }
649        best
650    }
651
652    /// Index of the largest element.
653    ///
654    /// NaN policy: elements are ordered with [`f32::total_cmp`] (IEEE 754
655    /// `totalOrder`), which never yields `None`, so this function cannot
656    /// panic on NaN inputs. A positive NaN sorts above `+Inf` and therefore
657    /// wins; a negative NaN sorts below `-Inf`. Returns `0` for an empty
658    /// tensor. Callers that need NaN rejection should screen inputs with
659    /// [`f32::is_nan`] first.
660    pub fn argmax(&self) -> usize {
661        self.data
662            .iter()
663            .enumerate()
664            .max_by(|(_, a), (_, b)| a.total_cmp(b))
665            .map(|(i, _)| i)
666            .unwrap_or(0)
667    }
668
669    /// Softmax along the last axis (0-D, 1-D, or each row of a 2-D tensor).
670    ///
671    /// See [`finite`] for the NaN / `±Inf` / all-masked policy.
672    ///
673    /// # Panics
674    ///
675    /// Panics if the rank is greater than 2. Prefer
676    /// [`Self::try_softmax_last`] in new code.
677    pub fn softmax_last(&self) -> Self {
678        unwrap_compat(self.try_softmax_last(), "Tensor::softmax_last")
679    }
680
681    /// Fallible softmax along the last axis.
682    ///
683    /// Returns [`CortexError::RankMismatch`] with `expected: 2` when
684    /// `ndim > 2`, matching the other rank-checked ops.
685    pub fn try_softmax_last(&self) -> Result<Self> {
686        self.check_storage()?;
687        if self.ndim() > 2 {
688            return Err(CortexError::RankMismatch {
689                expected: 2,
690                got: self.ndim(),
691            });
692        }
693        if self.ndim() <= 1 {
694            let mut data = vec![0.0f32; self.data.len()];
695            finite::softmax_row(&self.data, &mut data);
696            return Ok(Self::from_vec(data, &self.shape));
697        }
698        let (rows, cols) = (self.shape[0], self.shape[1]);
699        let mut data = vec![0.0f32; rows * cols];
700        if cols == 0 {
701            return Ok(Self::from_vec(data, &self.shape));
702        }
703        for r in 0..rows {
704            let row_start = r * cols;
705            finite::softmax_row(
706                &self.data[row_start..row_start + cols],
707                &mut data[row_start..row_start + cols],
708            );
709        }
710        Ok(Self::from_vec(data, &self.shape))
711    }
712
713    // ── Row / slice access ───────────────────────────────────────────
714
715    /// Copies row `idx` of a 2-D tensor into a 1-D tensor.
716    ///
717    /// # Panics
718    ///
719    /// Panics if `self` is not rank-2 or `idx` is out of bounds. Prefer
720    /// [`Tensor::try_row`] in new code.
721    pub fn row(&self, idx: usize) -> Self {
722        unwrap_compat(self.try_row(idx), "Tensor::row")
723    }
724
725    /// Fallible row access: returns [`CortexError::RankMismatch`] unless
726    /// `self` is rank-2 and [`CortexError::IndexOutOfBounds`] when
727    /// `idx >= shape[0]`.
728    pub fn try_row(&self, idx: usize) -> Result<Self> {
729        self.check_storage()?;
730        if self.ndim() != 2 {
731            return Err(CortexError::RankMismatch {
732                expected: 2,
733                got: self.ndim(),
734            });
735        }
736        let (rows, cols) = (self.shape[0], self.shape[1]);
737        if idx >= rows {
738            return Err(CortexError::IndexOutOfBounds {
739                axis: 0,
740                index: idx,
741                size: rows,
742            });
743        }
744        let start = idx * cols;
745        Self::try_from_vec(self.data[start..start + cols].to_vec(), &[cols])
746    }
747
748    /// Rejects tensors whose stored `data` length disagrees with `shape`.
749    ///
750    /// Deserialization validates this invariant; fallible methods that slice
751    /// retain the check as a guard against internal corruption.
752    pub(crate) fn check_storage(&self) -> Result<()> {
753        let expected = checked_numel(&self.shape).unwrap_or(usize::MAX);
754        if self.data.len() != expected {
755            return Err(CortexError::ShapeMismatch {
756                expected: self.shape.clone(),
757                got: vec![self.data.len()],
758            });
759        }
760        Ok(())
761    }
762}
763
764/// Product of `shape` using checked arithmetic.
765///
766/// Any zero axis yields `0` without multiplying the remaining extents, so a
767/// trailing zero still produces an empty tensor when an earlier product would
768/// overflow (for example `[3, usize::MAX, 0]`).
769pub(crate) fn checked_numel(shape: &[usize]) -> Result<usize> {
770    if shape.contains(&0) {
771        return Ok(0);
772    }
773    shape.iter().try_fold(1usize, |acc, &dim| {
774        acc.checked_mul(dim)
775            .ok_or_else(|| CortexError::SizeOverflow {
776                shape: shape.to_vec(),
777            })
778    })
779}
780
781/// Rejects a `Vec<f32>` length whose byte size exceeds `isize::MAX`.
782pub(crate) fn check_f32_alloc(numel: usize, shape: &[usize]) -> Result<()> {
783    Layout::array::<f32>(numel)
784        .map(|_| ())
785        .map_err(|_| CortexError::SizeOverflow {
786            shape: shape.to_vec(),
787        })
788}
789
790/// Row-major strides for `shape`, using checked arithmetic.
791///
792/// Strides are never stored on [`Tensor`]; this helper backs both the
793/// public [`Tensor::try_row_major_strides`] recompute path and the
794/// construction-time overflow guard that rejects shapes whose stride product
795/// is not representable. The last stride is `1` and each earlier stride is the
796/// product of all following dimensions. A zero-sized axis can still overflow a
797/// leading stride (for example `[0, usize::MAX, 2]`).
798pub(crate) fn try_compute_strides(shape: &[usize]) -> Result<Vec<usize>> {
799    if shape.is_empty() {
800        return Ok(Vec::new());
801    }
802    let mut strides = vec![1usize; shape.len()];
803    for i in (0..shape.len().saturating_sub(1)).rev() {
804        strides[i] =
805            strides[i + 1]
806                .checked_mul(shape[i + 1])
807                .ok_or_else(|| CortexError::SizeOverflow {
808                    shape: shape.to_vec(),
809                })?;
810    }
811    Ok(strides)
812}
813
814/// Reserves exactly `numel` elements of `f32` storage for `shape`, or returns
815/// [`CortexError::AllocationFailed`] when the allocator refuses.
816///
817/// `vec![x; n]` and `Vec::with_capacity(n)` call `handle_alloc_error` on
818/// failure, which aborts the process. A caller-controlled shape that passes
819/// the `isize::MAX` layout check (see [`check_f32_alloc`]) can therefore
820/// still take the whole process down instead of surfacing an `Err`. Every
821/// fresh output buffer sized by a shape goes through this helper so the
822/// failure stays a value.
823///
824/// This guards the *reservation*. On systems with memory overcommit (Linux
825/// default) the reservation can succeed and the kernel may still kill the
826/// process when the pages are first touched; that is outside what a library
827/// can turn into an `Err`.
828///
829/// Limitation: buffers sized by an existing tensor's storage (`scale`,
830/// elementwise ops, transpose, softmax, the attention head reshapes) still
831/// use `vec!`/`collect`. Their source is alive while they allocate, so peak
832/// memory doubles and a second allocation of the same size can still abort.
833/// In practice this means the *first* `nh·seq²` buffer of
834/// `MultiHeadAttention::try_forward` is fallible and the later ones are not;
835/// closing that gap is tracked under issue #103.
836pub(crate) fn try_reserve_f32(numel: usize, shape: &[usize]) -> Result<Vec<f32>> {
837    let mut data: Vec<f32> = Vec::new();
838    data.try_reserve_exact(numel)
839        .map_err(|_| CortexError::AllocationFailed {
840            shape: shape.to_vec(),
841            bytes: numel.saturating_mul(std::mem::size_of::<f32>()),
842        })?;
843    Ok(data)
844}
845
846/// Element count of a fresh `f32` buffer for `shape`, after proving the
847/// count, its byte layout, and the row-major strides are all representable.
848///
849/// Every path that allocates a new buffer from a shape (constructors, `randn`,
850/// and the ops that produce a fresh output) goes through this check before
851/// reserving storage with [`try_reserve_f32`].
852pub(crate) fn checked_alloc_len(shape: &[usize]) -> Result<usize> {
853    let numel = checked_numel(shape)?;
854    check_f32_alloc(numel, shape)?;
855    let _ = try_compute_strides(shape)?;
856    Ok(numel)
857}
858
859/// Allocates a buffer for `shape` filled with `val`, fallibly. Shared by the
860/// constructors and the ops that produce a fresh output tensor.
861pub(crate) fn try_alloc_filled(shape: &[usize], val: f32) -> Result<Vec<f32>> {
862    let numel = checked_alloc_len(shape)?;
863    let mut data = try_reserve_f32(numel, shape)?;
864    data.resize(numel, val);
865    Ok(data)
866}
867
868/// Allocates a filled buffer only after numel and row-major strides are
869/// representable and the allocation itself succeeds.
870fn try_filled(shape: &[usize], val: f32) -> Result<Tensor> {
871    let data = try_alloc_filled(shape, val)?;
872    Ok(Tensor {
873        data,
874        shape: shape.to_vec(),
875    })
876}
877
878impl fmt::Debug for Tensor {
879    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880        write!(f, "Tensor(shape={:?}, data=[", self.shape)?;
881        let n = self.data.len().min(8);
882        for (i, v) in self.data[..n].iter().enumerate() {
883            if i > 0 {
884                write!(f, ", ")?;
885            }
886            write!(f, "{v:.4}")?;
887        }
888        if self.data.len() > 8 {
889            write!(f, ", ...")?;
890        }
891        write!(f, "])")
892    }
893}
894
895#[cfg(test)]
896mod tests {
897    use super::*;
898
899    /// Largest `f32` count that passes the `isize::MAX` layout check, so the
900    /// failure must come from the allocator, not from `SizeOverflow`.
901    const UNBACKABLE_NUMEL: usize = isize::MAX as usize / std::mem::size_of::<f32>();
902
903    #[test]
904    fn unbackable_shape_is_an_error_not_an_abort() {
905        let shape = [UNBACKABLE_NUMEL];
906        for result in [
907            Tensor::try_zeros(&shape),
908            Tensor::try_ones(&shape),
909            Tensor::try_full(&shape, 2.5),
910            Tensor::try_randn(&shape, 0.0, 1.0),
911            Tensor::try_randn_with_rng(&shape, 0.0, 1.0, &mut seeded_rng(7)),
912        ] {
913            match result {
914                Err(CortexError::AllocationFailed { shape: got, bytes }) => {
915                    assert_eq!(got, shape);
916                    assert_eq!(bytes, UNBACKABLE_NUMEL * std::mem::size_of::<f32>());
917                }
918                Err(other) => panic!("expected AllocationFailed, got {other}"),
919                Ok(t) => panic!("allocated {} elements", t.numel()),
920            }
921        }
922        // The two guards stay distinct: one past the layout limit is still
923        // `SizeOverflow`, not an allocator failure.
924        assert!(matches!(
925            Tensor::try_zeros(&[UNBACKABLE_NUMEL + 1]),
926            Err(CortexError::SizeOverflow { .. })
927        ));
928    }
929
930    #[test]
931    fn allocation_failed_message_names_shape_and_bytes() {
932        let err = Tensor::try_zeros(&[UNBACKABLE_NUMEL]).unwrap_err();
933        let msg = err.to_string();
934        assert!(msg.contains("allocation of"), "{msg}");
935        assert!(msg.contains(&UNBACKABLE_NUMEL.to_string()), "{msg}");
936    }
937
938    #[test]
939    fn try_randn_rejects_overflowing_std() {
940        assert!(matches!(
941            Tensor::try_randn(&[64], 0.0, f32::MAX),
942            Err(CortexError::InvalidConfig(_))
943        ));
944    }
945
946    #[test]
947    fn try_randn_rejects_bad_params() {
948        for (m, s) in [
949            (0.0, f32::NAN),
950            (0.0, -1.0),
951            (0.0, f32::INFINITY),
952            (f32::NAN, 1.0),
953            (f32::INFINITY, 1.0),
954        ] {
955            assert!(matches!(
956                Tensor::try_randn(&[3], m, s),
957                Err(CortexError::InvalidConfig(_))
958            ));
959        }
960        assert!(Tensor::try_randn(&[3], 0.0, 0.0).is_ok());
961    }
962
963    #[test]
964    fn try_randn_with_rng_is_reproducible() {
965        let mk = |seed| {
966            let mut rng = seeded_rng(seed);
967            Tensor::try_randn_with_rng(&[5, 7], 0.0, 1.0, &mut rng).unwrap()
968        };
969        assert_eq!(mk(7).data(), mk(7).data());
970        assert_ne!(mk(7).data(), mk(8).data());
971        assert!(mk(7).data().iter().all(|v| v.is_finite()));
972    }
973
974    #[test]
975    fn test_from_vec_and_shape() {
976        let t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
977        assert_eq!(t.shape(), &[2, 3]);
978        assert_eq!(t.numel(), 6);
979        assert_eq!(t.row_major_strides(), &[3, 1]);
980    }
981
982    #[test]
983    fn try_from_vec_matches_from_vec_on_valid_input() {
984        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
985        let a = Tensor::from_vec(data.clone(), &[2, 3]);
986        let b = Tensor::try_from_vec(data, &[2, 3]).unwrap();
987        assert_eq!(a.data(), b.data());
988        assert_eq!(a.shape(), b.shape());
989        assert_eq!(a.row_major_strides(), b.row_major_strides());
990    }
991
992    #[test]
993    fn test_transpose() {
994        let t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
995        let tt = t.transpose();
996        assert_eq!(tt.shape(), &[3, 2]);
997        assert_eq!(tt.data(), &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
998    }
999
1000    #[test]
1001    fn try_transpose_zero_axis_returns_without_iterating_huge_extent() {
1002        // numel is 0 but one axis is enormous: the loops must not run.
1003        for shape in [
1004            [0usize, 1 << 40],
1005            [1 << 40, 0],
1006            [usize::MAX, 0],
1007            [0, usize::MAX],
1008            [0, 0],
1009        ] {
1010            let t = Tensor::try_from_vec(vec![], &shape).unwrap();
1011            let tt = t.try_transpose().unwrap();
1012            assert_eq!(tt.shape(), &[shape[1], shape[0]]);
1013            assert_eq!(tt.numel(), 0);
1014        }
1015    }
1016
1017    #[test]
1018    fn test_softmax() {
1019        let t = Tensor::from_vec(vec![1.0, 2.0, 3.0], &[3]);
1020        let s = t.softmax_last();
1021        let sum: f32 = s.data().iter().sum();
1022        assert!((sum - 1.0).abs() < 1e-5);
1023    }
1024
1025    #[test]
1026    fn test_softmax_last_rejects_rank_3() {
1027        let t = Tensor::from_vec(vec![1.0; 8], &[2, 2, 2]);
1028        let err = t.try_softmax_last().unwrap_err();
1029        assert!(matches!(
1030            err,
1031            CortexError::RankMismatch {
1032                expected: 2,
1033                got: 3
1034            }
1035        ));
1036        let err = crate::tensor::ops::try_softmax(&t).unwrap_err();
1037        assert!(matches!(
1038            err,
1039            CortexError::RankMismatch {
1040                expected: 2,
1041                got: 3
1042            }
1043        ));
1044    }
1045
1046    #[test]
1047    #[should_panic(expected = "Tensor::softmax_last")]
1048    fn test_softmax_last_panic_carries_migration_hint() {
1049        let t = Tensor::from_vec(vec![1.0; 8], &[2, 2, 2]);
1050        let _ = t.softmax_last();
1051    }
1052
1053    #[test]
1054    fn test_softmax_2d_rows_and_all_masked() {
1055        let t = Tensor::from_vec(
1056            vec![
1057                1.0,
1058                2.0,
1059                3.0,
1060                f32::NEG_INFINITY,
1061                f32::NEG_INFINITY,
1062                f32::NEG_INFINITY,
1063            ],
1064            &[2, 3],
1065        );
1066        let s = t.softmax_last();
1067        let row0: f32 = s.data()[0..3].iter().sum();
1068        assert!((row0 - 1.0).abs() < 1e-5);
1069        for p in &s.data()[3..6] {
1070            assert!((p - 1.0 / 3.0).abs() < 1e-6);
1071        }
1072    }
1073
1074    #[test]
1075    fn try_elementwise_ops_report_shape_mismatch() {
1076        let a = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
1077        let b = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
1078        for (name, err) in [
1079            ("add", a.try_add(&b).unwrap_err()),
1080            ("sub", a.try_sub(&b).unwrap_err()),
1081            ("mul", a.try_mul(&b).unwrap_err()),
1082        ] {
1083            assert!(
1084                matches!(
1085                    err,
1086                    CortexError::ShapeMismatch { ref expected, ref got }
1087                        if expected == &[2, 2] && got == &[2, 3]
1088                ),
1089                "{name}: {err}"
1090            );
1091        }
1092    }
1093
1094    #[test]
1095    fn try_reshape_and_transpose_validate() {
1096        let t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
1097        assert!(matches!(
1098            t.try_reshape(&[4, 2]).unwrap_err(),
1099            CortexError::ShapeMismatch { .. }
1100        ));
1101        assert_eq!(t.try_reshape(&[3, 2]).unwrap().shape(), &[3, 2]);
1102        assert!(matches!(
1103            Tensor::from_vec(vec![1.0, 2.0], &[2])
1104                .try_transpose()
1105                .unwrap_err(),
1106            CortexError::RankMismatch {
1107                expected: 2,
1108                got: 1
1109            }
1110        ));
1111    }
1112
1113    #[test]
1114    fn reshape_and_transpose_are_copies_not_views() {
1115        // reshape copies: the result owns storage disjoint from the source, so
1116        // mutating one never aliases the other.
1117        let mut src = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
1118        let reshaped = src.reshape(&[3, 2]);
1119        assert_eq!(reshaped.shape(), &[3, 2]);
1120        assert_eq!(reshaped.data(), src.data()); // same row-major order
1121        src.data_mut()[0] = 99.0;
1122        assert_eq!(reshaped.data()[0], 1.0, "reshape must not alias source");
1123
1124        // transpose materializes a reordered buffer.
1125        let t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
1126        let tt = t.transpose();
1127        assert_eq!(tt.shape(), &[3, 2]);
1128        assert_eq!(tt.data(), &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
1129    }
1130
1131    #[test]
1132    fn reshape_in_place_reuses_buffer_without_copy() {
1133        let mut t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
1134        t.reshape_in_place(&[6]).unwrap();
1135        assert_eq!(t.shape(), &[6]);
1136        assert_eq!(t.data(), &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
1137
1138        // Element-count change is rejected AND leaves the tensor unchanged, so
1139        // a caller can keep using it after a failed reshape.
1140        let mut t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
1141        assert!(matches!(
1142            t.reshape_in_place(&[3, 2]).unwrap_err(),
1143            CortexError::ShapeMismatch { .. }
1144        ));
1145        assert_eq!(t.shape(), &[2, 2], "failed reshape must not mutate shape");
1146        assert_eq!(t.data(), &[1.0, 2.0, 3.0, 4.0], "data must be intact");
1147    }
1148
1149    #[test]
1150    fn row_major_strides_recomputes_from_shape() {
1151        let t = Tensor::from_vec(vec![0.0; 24], &[2, 3, 4]);
1152        assert_eq!(t.row_major_strides(), &[12, 4, 1]);
1153        assert_eq!(t.try_row_major_strides().unwrap(), vec![12, 4, 1]);
1154        let scalar = Tensor::try_from_vec(vec![1.0], &[]).unwrap();
1155        assert!(scalar.row_major_strides().is_empty());
1156    }
1157
1158    #[test]
1159    fn deserialize_rejects_legacy_strides_field() {
1160        let json = r#"{"data":[1.0,2.0,3.0,4.0,5.0,6.0],"shape":[2,3],"strides":[3,1]}"#;
1161        assert!(serde_json::from_str::<Tensor>(json).is_err());
1162    }
1163
1164    #[test]
1165    fn serialized_form_has_no_strides_field() {
1166        let t = Tensor::from_vec(vec![1.0, 2.0], &[2]);
1167        let json = serde_json::to_string(&t).unwrap();
1168        assert!(
1169            !json.contains("strides"),
1170            "serialized form leaks strides: {json}"
1171        );
1172        assert!(json.contains("\"shape\""));
1173        assert!(json.contains("\"data\""));
1174    }
1175
1176    #[test]
1177    fn elementwise_ops_require_exact_shape_no_broadcast() {
1178        // Exact-shape contract: no NumPy broadcasting on add/sub/mul, not even
1179        // against a size-1 axis that broadcasting would otherwise expand.
1180        let a = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
1181        let row = Tensor::from_vec(vec![10.0, 20.0, 30.0], &[1, 3]);
1182        let scalar_like = Tensor::from_vec(vec![10.0], &[1]);
1183        for (name, err) in [
1184            ("add row", a.try_add(&row).unwrap_err()),
1185            ("sub row", a.try_sub(&row).unwrap_err()),
1186            ("mul row", a.try_mul(&row).unwrap_err()),
1187            ("add scalar-like", a.try_add(&scalar_like).unwrap_err()),
1188        ] {
1189            assert!(
1190                matches!(err, CortexError::ShapeMismatch { .. }),
1191                "{name}: {err}"
1192            );
1193        }
1194        // Exact match succeeds.
1195        let b = Tensor::from_vec(vec![6.0, 5.0, 4.0, 3.0, 2.0, 1.0], &[2, 3]);
1196        assert_eq!(
1197            a.try_add(&b).unwrap().data(),
1198            &[7.0, 7.0, 7.0, 7.0, 7.0, 7.0]
1199        );
1200    }
1201
1202    #[test]
1203    fn try_row_bounds_check() {
1204        let t = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
1205        assert_eq!(t.try_row(1).unwrap().data(), &[3.0, 4.0]);
1206        assert!(matches!(
1207            t.try_row(9).unwrap_err(),
1208            CortexError::IndexOutOfBounds {
1209                axis: 0,
1210                index: 9,
1211                size: 2
1212            }
1213        ));
1214        let rank1 = Tensor::from_vec(vec![1.0], &[1]);
1215        assert!(matches!(
1216            rank1.try_row(0).unwrap_err(),
1217            CortexError::RankMismatch {
1218                expected: 2,
1219                got: 1
1220            }
1221        ));
1222    }
1223
1224    #[test]
1225    fn corrupted_storage_is_rejected_on_deserialize() {
1226        let json = r#"{"schema_version":1,"data":[1.0],"shape":[2,2]}"#;
1227        assert!(serde_json::from_str::<Tensor>(json).is_err());
1228    }
1229
1230    #[test]
1231    fn argmax_nan_uses_ieee_total_order_without_panic() {
1232        // total_cmp: positive NaN sorts above +Inf, so NaN wins argmax.
1233        let t = Tensor::from_vec(vec![1.0, f32::NAN, 3.0], &[3]);
1234        assert_eq!(t.argmax(), 1);
1235        // Negative NaN sorts below -Inf and never wins.
1236        let neg = f32::from_bits(0xffc0_0000);
1237        let t = Tensor::from_vec(vec![neg, 1.0, 3.0], &[3]);
1238        assert_eq!(t.argmax(), 2);
1239        // All-NaN input is still panic-free.
1240        let t = Tensor::from_vec(vec![f32::NAN, f32::NAN], &[2]);
1241        let _ = t.argmax();
1242        // Empty tensor returns 0.
1243        let t = Tensor::try_from_vec(vec![], &[0]).unwrap();
1244        assert_eq!(t.argmax(), 0);
1245    }
1246
1247    #[test]
1248    fn softmax_last_all_neg_inf_is_uniform() {
1249        let t = Tensor::from_vec(vec![f32::NEG_INFINITY, f32::NEG_INFINITY], &[2]);
1250        let s = t.softmax_last();
1251        assert!(s.data().iter().all(|p| (p - 0.5).abs() < 1e-6));
1252    }
1253
1254    #[test]
1255    fn test_gelu() {
1256        let t = Tensor::from_vec(vec![0.0, 1.0, -1.0], &[3]);
1257        let g = t.gelu();
1258        assert!((g.data()[0] - 0.0).abs() < 1e-4);
1259        assert!(g.data()[1] > 0.8); // GELU(1) ≈ 0.841
1260    }
1261
1262    #[test]
1263    fn try_from_vec_accepts_empty_and_zero_axes() {
1264        let empty = Tensor::try_from_vec(vec![], &[0, 3]).unwrap();
1265        assert_eq!(empty.numel(), 0);
1266        assert_eq!(empty.shape(), &[0, 3]);
1267        assert_eq!(empty.row_major_strides(), &[3, 1]);
1268
1269        let zero_1d = Tensor::try_from_vec(vec![], &[0]).unwrap();
1270        assert_eq!(zero_1d.numel(), 0);
1271        assert_eq!(zero_1d.row_major_strides(), &[1]);
1272
1273        let scalar = Tensor::try_from_vec(vec![3.5], &[]).unwrap();
1274        assert_eq!(scalar.numel(), 1);
1275        assert!(scalar.row_major_strides().is_empty());
1276        assert_eq!(scalar.data(), &[3.5]);
1277    }
1278
1279    #[test]
1280    fn try_from_vec_error_table() {
1281        struct Case {
1282            name: &'static str,
1283            data: Vec<f32>,
1284            shape: Vec<usize>,
1285            check: fn(&CortexError) -> bool,
1286        }
1287        let cases = [
1288            Case {
1289                name: "length mismatch",
1290                data: vec![1.0, 2.0],
1291                shape: vec![2, 3],
1292                check: |e| {
1293                    matches!(
1294                        e,
1295                        CortexError::ShapeMismatch {
1296                            expected,
1297                            got
1298                        } if expected == &[2, 3] && got == &[2]
1299                    )
1300                },
1301            },
1302            Case {
1303                name: "empty data for non-empty shape",
1304                data: vec![],
1305                shape: vec![4],
1306                check: |e| matches!(e, CortexError::ShapeMismatch { .. }),
1307            },
1308            Case {
1309                name: "scalar requires one element",
1310                data: vec![],
1311                shape: vec![],
1312                check: |e| {
1313                    matches!(
1314                        e,
1315                        CortexError::ShapeMismatch { expected, got }
1316                            if expected.is_empty() && got == &[0]
1317                    )
1318                },
1319            },
1320            Case {
1321                name: "product overflow",
1322                data: vec![],
1323                shape: vec![usize::MAX, 2],
1324                check: |e| {
1325                    matches!(
1326                        e,
1327                        CortexError::SizeOverflow { shape } if shape == &[usize::MAX, 2]
1328                    )
1329                },
1330            },
1331            Case {
1332                name: "stride overflow with zero numel",
1333                data: vec![],
1334                shape: vec![0, usize::MAX, 2],
1335                check: |e| matches!(e, CortexError::SizeOverflow { .. }),
1336            },
1337        ];
1338        for case in cases {
1339            let err = Tensor::try_from_vec(case.data, &case.shape).expect_err(case.name);
1340            assert!((case.check)(&err), "{}: {err}", case.name);
1341        }
1342    }
1343
1344    #[test]
1345    fn overflow_shapes_fail_without_giant_allocation() {
1346        let shapes: &[&[usize]] = &[
1347            &[usize::MAX, 2],
1348            &[2, usize::MAX],
1349            &[usize::MAX, usize::MAX],
1350            &[usize::MAX / 2 + 1, 2],
1351            &[0, usize::MAX, 2],
1352            &[0, 2, usize::MAX],
1353        ];
1354        for shape in shapes {
1355            let err = Tensor::try_from_vec(Vec::new(), shape).unwrap_err();
1356            assert!(
1357                matches!(err, CortexError::SizeOverflow { shape: ref got } if got.as_slice() == *shape),
1358                "shape {shape:?} -> {err}"
1359            );
1360        }
1361
1362        // A zero axis can cancel a huge leading extent so numel is 0 and
1363        // strides stay representable.
1364        let cancelled = Tensor::try_from_vec(vec![], &[usize::MAX, 0, 2]).unwrap();
1365        assert_eq!(cancelled.numel(), 0);
1366        assert_eq!(cancelled.row_major_strides(), &[0, 2, 1]);
1367
1368        // A trailing zero must not be lost to a left-to-right overflow.
1369        let trailing = Tensor::try_from_vec(vec![], &[3, usize::MAX, 0]).unwrap();
1370        assert_eq!(trailing.numel(), 0);
1371        assert_eq!(trailing.row_major_strides(), &[0, 0, 1]);
1372    }
1373
1374    #[test]
1375    fn zeros_overflow_panics_without_allocating() {
1376        let panicked = std::panic::catch_unwind(|| {
1377            let _ = Tensor::zeros(&[usize::MAX, 2]);
1378        });
1379        assert!(panicked.is_err());
1380    }
1381
1382    /// Guards against unchecked shape products wrapping to `numel == 0` in release.
1383    #[test]
1384    fn equal_power_of_two_extents_reject_without_wrapped_numel() {
1385        const EXT: usize = 1usize << (usize::BITS / 2);
1386        let shape = [EXT, EXT];
1387        for (name, result) in [
1388            ("try_zeros", Tensor::try_zeros(&shape)),
1389            ("try_ones", Tensor::try_ones(&shape)),
1390            ("try_full", Tensor::try_full(&shape, 1.0)),
1391            ("try_from_vec", Tensor::try_from_vec(Vec::new(), &shape)),
1392        ] {
1393            assert!(
1394                matches!(result, Err(CortexError::SizeOverflow { shape: ref got }) if got.as_slice() == shape),
1395                "{name}: {result:?}"
1396            );
1397        }
1398        assert!(checked_numel(&shape).is_err());
1399    }
1400
1401    /// Empty tensors divide by zero in `mean()`; rank-0 scalars use the sole element.
1402    #[test]
1403    fn mean_of_zero_element_tensor_is_nan() {
1404        let empty = Tensor::try_zeros(&[0, 3]).unwrap();
1405        assert!(empty.mean().is_nan());
1406        let scalar = Tensor::try_from_vec(vec![4.0], &[]).unwrap();
1407        assert_eq!(scalar.mean(), 4.0);
1408    }
1409
1410    // ── Finite-value policy: activations and whole-tensor reductions (issue 95) ──
1411
1412    const NEG_NAN: f32 = f32::from_bits(0xffc0_0000);
1413
1414    #[test]
1415    fn relu_propagates_nan_and_keeps_infinities() {
1416        let t = Tensor::from_vec(
1417            vec![f32::NAN, 1.0, -2.0, f32::INFINITY, f32::NEG_INFINITY, 0.0],
1418            &[6],
1419        );
1420        let r = t.relu();
1421        assert!(r.data()[0].is_nan(), "relu must not erase NaN via f32::max");
1422        assert_eq!(r.data()[1], 1.0);
1423        assert_eq!(r.data()[2].to_bits(), 0.0f32.to_bits());
1424        assert_eq!(r.data()[3], f32::INFINITY);
1425        assert_eq!(r.data()[4].to_bits(), 0.0f32.to_bits());
1426        assert_eq!(r.data()[5].to_bits(), 0.0f32.to_bits());
1427        let neg = Tensor::from_vec(vec![NEG_NAN, -0.0], &[2]).relu();
1428        assert!(neg.data()[0].is_nan());
1429        // Negative zero is clamped to canonical +0.0 (deterministic bit pattern).
1430        assert_eq!(neg.data()[1].to_bits(), 0.0f32.to_bits());
1431    }
1432
1433    #[test]
1434    fn max_val_propagates_nan_and_documents_empty() {
1435        let t = Tensor::from_vec(vec![f32::NAN, 1.0, -2.0], &[3]);
1436        assert!(
1437            t.max_val().is_nan(),
1438            "max_val must not drop NaN via f32::max"
1439        );
1440        // Positive NaN: argmax picks the NaN and max_val is NaN, so the two agree.
1441        assert!(t.data()[t.argmax()].is_nan());
1442        let neg = Tensor::from_vec(vec![NEG_NAN, 1.0, 3.0], &[3]);
1443        assert!(neg.max_val().is_nan());
1444        let fin = Tensor::from_vec(vec![-3.0, f32::NEG_INFINITY, 2.5, 2.5], &[4]);
1445        assert_eq!(fin.max_val(), 2.5);
1446        assert_eq!(fin.data()[fin.argmax()], fin.max_val());
1447        let inf = Tensor::from_vec(vec![1.0, f32::INFINITY], &[2]);
1448        assert_eq!(inf.max_val(), f32::INFINITY);
1449        let empty = Tensor::try_from_vec(vec![], &[0]).unwrap();
1450        assert_eq!(empty.max_val(), f32::NEG_INFINITY);
1451    }
1452
1453    #[test]
1454    fn activations_at_infinity_return_their_limits() {
1455        let t = Tensor::from_vec(vec![f32::NEG_INFINITY, f32::INFINITY, f32::NAN], &[3]);
1456        let silu = t.silu();
1457        assert_eq!(silu.data()[0], 0.0, "silu(-Inf) = 0, not -Inf/Inf = NaN");
1458        assert_eq!(silu.data()[1], f32::INFINITY);
1459        assert!(silu.data()[2].is_nan());
1460        let gelu = t.gelu();
1461        assert_eq!(gelu.data()[0], 0.0, "gelu(-Inf) = 0, not -Inf*0 = NaN");
1462        assert_eq!(gelu.data()[1], f32::INFINITY);
1463        assert!(gelu.data()[2].is_nan());
1464        let fs = t.fast_sigmoid();
1465        assert_eq!(fs.data()[0], -1.0, "fast_sigmoid(-Inf) = -1, not Inf/Inf");
1466        assert_eq!(fs.data()[1], 1.0);
1467        assert!(fs.data()[2].is_nan());
1468        let relu = t.relu();
1469        assert_eq!(relu.data()[0], 0.0);
1470        assert_eq!(relu.data()[1], f32::INFINITY);
1471        assert!(relu.data()[2].is_nan());
1472    }
1473
1474    #[test]
1475    fn activations_stay_finite_for_large_finite_inputs() {
1476        // x³ overflows f32 well before x does; the tanh argument must not turn
1477        // a finite input into NaN, and the result must approach the ±Inf limits.
1478        let t = Tensor::from_vec(vec![-1e20, 1e20, -3e38, 3e38, -100.0, 100.0], &[6]);
1479        for (name, out) in [
1480            ("gelu", t.gelu()),
1481            ("silu", t.silu()),
1482            ("fast_sigmoid", t.fast_sigmoid()),
1483            ("relu", t.relu()),
1484        ] {
1485            for (x, y) in t.data().iter().zip(out.data()) {
1486                assert!(y.is_finite(), "{name}({x}) = {y} is not finite");
1487            }
1488        }
1489        assert_eq!(t.gelu().data()[0], 0.0);
1490        assert_eq!(t.gelu().data()[1], 1e20);
1491        assert_eq!(t.silu().data()[0], 0.0);
1492        assert_eq!(t.silu().data()[1], 1e20);
1493        // Finite fast sigmoid lies in the closed interval [-1, 1]: once
1494        // |x| >= 2^24, `1 + |x|` rounds to `|x|` in f32 and the result is ±1.
1495        let fs = Tensor::from_vec(vec![16_777_216.0, -16_777_216.0, 1e20], &[3]).fast_sigmoid();
1496        assert_eq!(fs.data(), &[1.0, -1.0, 1.0]);
1497        let fs = Tensor::from_vec(vec![16_777_215.0], &[1]).fast_sigmoid();
1498        assert!(fs.data()[0] < 1.0 && fs.data()[0] > 0.99);
1499    }
1500
1501    #[test]
1502    fn sum_and_mean_accumulate_in_f64() {
1503        // f32 accumulation stalls at 2^24: 16777216 + 1 rounds back to 16777216.
1504        let t = Tensor::from_vec(vec![16_777_216.0, 1.0, 1.0], &[3]);
1505        assert_eq!(t.sum(), 16_777_218.0);
1506        // 2^24 + 2 ones: the f32 running sum would freeze at 2^24.
1507        let n = (1usize << 24) + 2;
1508        let ones = Tensor::ones(&[n]);
1509        assert_eq!(ones.sum(), n as f32);
1510        assert_eq!(ones.mean(), 1.0);
1511        // Intermediate f32 overflow must not leak into a finite true sum.
1512        let t = Tensor::from_vec(vec![f32::MAX, f32::MAX, -f32::MAX], &[3]);
1513        assert_eq!(t.sum(), f32::MAX);
1514        // Compensation keeps a term that plain f64 cancels away: 1e20 is below
1515        // half an f64 ulp of f32::MAX (~7.5e22), so MAX + 1e20 - MAX would be 0.
1516        let t = Tensor::from_vec(vec![f32::MAX, 1e20, -f32::MAX], &[3]);
1517        assert_eq!(t.sum(), 1e20);
1518        assert_eq!(t.mean(), 1e20 / 3.0);
1519        // A true sum outside the f32 range still rounds to the signed infinity.
1520        let t = Tensor::from_vec(vec![f32::MAX, f32::MAX], &[2]);
1521        assert_eq!(t.sum(), f32::INFINITY);
1522        // Non-finite inputs follow IEEE: NaN propagates, Inf - Inf is NaN.
1523        assert!(Tensor::from_vec(vec![1.0, f32::NAN], &[2]).sum().is_nan());
1524        assert_eq!(
1525            Tensor::from_vec(vec![1.0, f32::INFINITY], &[2]).sum(),
1526            f32::INFINITY
1527        );
1528        assert!(
1529            Tensor::from_vec(vec![f32::INFINITY, f32::NEG_INFINITY], &[2])
1530                .sum()
1531                .is_nan()
1532        );
1533        // The reference golden (sum 21, mean 3.5) is unchanged.
1534        let a = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
1535        assert_eq!((a.sum(), a.mean()), (21.0, 3.5));
1536        // Mean is computed from the f64 sum, not the rounded f32 sum.
1537        let t = Tensor::from_vec(vec![16_777_216.0, 1.0, 1.0, 0.0], &[4]);
1538        assert_eq!(t.mean(), 16_777_218.0 / 4.0);
1539    }
1540
1541    #[test]
1542    fn property_accepted_shapes_match_numel_and_strides() {
1543        fn check(shape: &[usize]) {
1544            let numel = match checked_numel(shape) {
1545                Ok(n) => n,
1546                Err(CortexError::SizeOverflow { shape: got }) => {
1547                    assert_eq!(got, shape);
1548                    return;
1549                }
1550                Err(other) => panic!("numel check failed unexpectedly: {other}"),
1551            };
1552            match try_compute_strides(shape) {
1553                Ok(strides) => {
1554                    let t = Tensor::try_from_vec(vec![0.5; numel], shape)
1555                        .expect("shape with representable numel and strides must construct");
1556                    assert_eq!(t.numel(), numel);
1557                    assert_eq!(t.data().len(), numel);
1558                    assert_eq!(t.shape(), shape);
1559                    assert_eq!(t.row_major_strides(), strides.as_slice());
1560                    if shape.is_empty() {
1561                        assert!(strides.is_empty());
1562                    } else {
1563                        assert_eq!(*strides.last().unwrap(), 1);
1564                        for i in (0..shape.len().saturating_sub(1)).rev() {
1565                            let expected = strides[i + 1]
1566                                .checked_mul(shape[i + 1])
1567                                .expect("successful stride vector is overflow-free");
1568                            assert_eq!(strides[i], expected);
1569                        }
1570                    }
1571                }
1572                Err(CortexError::SizeOverflow { .. }) => {
1573                    assert!(Tensor::try_from_vec(vec![0.5; numel], shape).is_err());
1574                }
1575                Err(other) => panic!("stride check failed unexpectedly: {other}"),
1576            }
1577        }
1578
1579        fn rec(prefix: &mut Vec<usize>, max_rank: usize, max_dim: usize) {
1580            check(prefix);
1581            if prefix.len() >= max_rank {
1582                return;
1583            }
1584            for d in 0..=max_dim {
1585                prefix.push(d);
1586                rec(prefix, max_rank, max_dim);
1587                prefix.pop();
1588            }
1589        }
1590
1591        rec(&mut Vec::new(), 4, 4);
1592    }
1593}