Skip to main content

yscv_tensor/
tensor.rs

1use std::sync::Arc;
2
3use super::aligned::AlignedVec;
4use super::error::{DType, TensorError};
5use super::shape::{compute_strides, shape_element_count};
6
7// ── Inline shape/strides storage (no heap alloc for ≤6D tensors) ─────────
8
9// WHY 6: covers all common tensor ranks (scalar(0)..conv weight(5)) without heap allocation.
10pub(crate) const INLINE_CAP: usize = 6;
11
12/// Stack-allocated small vector for tensor shape/strides.
13/// Stores up to 6 dimensions inline; falls back to heap for higher ranks.
14#[derive(Clone)]
15pub(crate) enum DimsVec {
16    Inline { buf: [usize; INLINE_CAP], len: u8 },
17    Heap(Vec<usize>),
18}
19
20impl DimsVec {
21    #[inline]
22    const fn new() -> Self {
23        DimsVec::Inline {
24            buf: [0; INLINE_CAP],
25            len: 0,
26        }
27    }
28
29    #[inline]
30    fn as_slice(&self) -> &[usize] {
31        match self {
32            DimsVec::Inline { buf, len } => &buf[..*len as usize],
33            DimsVec::Heap(v) => v,
34        }
35    }
36
37    #[inline]
38    fn to_vec(&self) -> Vec<usize> {
39        self.as_slice().to_vec()
40    }
41}
42
43impl std::ops::Deref for DimsVec {
44    type Target = [usize];
45    #[inline]
46    fn deref(&self) -> &[usize] {
47        self.as_slice()
48    }
49}
50
51impl From<Vec<usize>> for DimsVec {
52    #[inline]
53    fn from(v: Vec<usize>) -> Self {
54        if v.len() <= INLINE_CAP {
55            let mut buf = [0usize; INLINE_CAP];
56            buf[..v.len()].copy_from_slice(&v);
57            DimsVec::Inline {
58                buf,
59                len: v.len() as u8,
60            }
61        } else {
62            DimsVec::Heap(v)
63        }
64    }
65}
66
67impl From<&[usize]> for DimsVec {
68    #[inline]
69    fn from(s: &[usize]) -> Self {
70        if s.len() <= INLINE_CAP {
71            let mut buf = [0usize; INLINE_CAP];
72            buf[..s.len()].copy_from_slice(s);
73            DimsVec::Inline {
74                buf,
75                len: s.len() as u8,
76            }
77        } else {
78            DimsVec::Heap(s.to_vec())
79        }
80    }
81}
82
83impl PartialEq for DimsVec {
84    #[inline]
85    fn eq(&self, other: &Self) -> bool {
86        self.as_slice() == other.as_slice()
87    }
88}
89
90impl std::fmt::Debug for DimsVec {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        self.as_slice().fmt(f)
93    }
94}
95
96/// Logical device where a tensor resides.
97///
98/// This is currently a metadata tag only — no actual data transfer occurs.
99/// GPU data movement is handled externally (e.g. via `GpuSession` in yscv-kernels).
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
101pub enum Device {
102    /// CPU (host) memory — the default.
103    #[default]
104    Cpu,
105    /// GPU device with the given index.
106    Gpu(usize),
107}
108
109/// Memory-layout tag describing how Conv-shaped tensors are laid out.
110///
111/// NCHW is ONNX's native layout and the default. NHWC is what yscv's CPU
112/// runner currently uses internally for Conv hot paths. NCHWc packs
113/// channels into SIMD-sized blocks (8 for AVX2/NEON, 16 for AVX-512),
114/// which lets 3×3 non-depthwise Conv use direct SIMD loads over the
115/// C-block stride rather than paying tail-handling cost.
116///
117/// The tag is **metadata** — it does not change how `data()` / `shape()`
118/// are interpreted by Tensor itself. Consumers (conv kernels, layout
119/// transformers) read the tag to pick the right kernel dispatch.
120/// Shape ordering matches the layout: NCHW tensors have shape
121/// `[N, C, H, W]`, NHWC `[N, H, W, C]`, NCHWc `[N, C/block, H, W, block]`
122/// (5-D). Data is always contiguous in its declared ordering.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
124pub enum Layout {
125    /// ONNX default: `[N, C, H, W]`.
126    #[default]
127    NCHW,
128    /// Channels-last: `[N, H, W, C]`. Used by yscv's CPU conv paths.
129    NHWC,
130    /// Blocked channels-first: `[N, C/block, H, W, block]`. `block` is a
131    /// SIMD-lane-aligned chunk size (8 on AVX2/NEON, 16 on AVX-512).
132    NCHWc {
133        /// Channels-per-block. Must be a power of two.
134        block: u8,
135    },
136}
137
138/// Internal typed storage for tensor data.
139#[derive(Debug, Clone)]
140pub(crate) enum Storage {
141    F32(AlignedVec<f32>),
142    F16(Vec<u16>),
143    BF16(Vec<u16>),
144}
145
146impl PartialEq for Storage {
147    fn eq(&self, other: &Self) -> bool {
148        match (self, other) {
149            (Storage::F32(a), Storage::F32(b)) => a == b,
150            (Storage::F16(a), Storage::F16(b)) => a == b,
151            (Storage::BF16(a), Storage::BF16(b)) => a == b,
152            _ => false,
153        }
154    }
155}
156
157impl Storage {
158    const fn len(&self) -> usize {
159        match self {
160            Storage::F32(v) => v.len(),
161            Storage::F16(v) => v.len(),
162            Storage::BF16(v) => v.len(),
163        }
164    }
165
166    const fn dtype(&self) -> DType {
167        match self {
168            Storage::F32(_) => DType::F32,
169            Storage::F16(_) => DType::F16,
170            Storage::BF16(_) => DType::BF16,
171        }
172    }
173}
174
175/// A compact, contiguous multi-dtype tensor representation.
176///
177/// Default dtype is `F32`. FP16 and BF16 dtypes are stored natively as `u16` bit patterns
178/// and can be created via `from_f16` / `from_bf16` or converted via `to_dtype`.
179#[derive(Debug, Clone, PartialEq)]
180pub struct Tensor {
181    shape: DimsVec,
182    strides: DimsVec,
183    // Arc-shared storage so `Tensor::clone()` / `reshape()` are O(1) refcount
184    // bumps. Writes go through `Arc::make_mut` (copy-on-write): free when
185    // refcount == 1, clone-once semantics otherwise. This lets the runtime
186    // pass `Arc<PackedWeight>` around at zero cost and makes Reshape a
187    // pointer-swap. Storage itself is still typed (F32/F16/BF16) — the Arc
188    // only guards the data buffer, not the dtype tag.
189    storage: Arc<Storage>,
190    device: Device,
191    layout: Layout,
192}
193
194impl Tensor {
195    /// Builds a scalar tensor from one value.
196    pub fn scalar(value: f32) -> Self {
197        Self {
198            shape: DimsVec::new(),
199            strides: DimsVec::new(),
200            storage: Arc::new(Storage::F32(AlignedVec::filled(1, value))),
201            device: Device::Cpu,
202            layout: Layout::NCHW,
203        }
204    }
205
206    /// Creates a tensor from shape, contiguous strides, and aligned data.
207    ///
208    /// This low-level constructor keeps its infallible API for the many
209    /// internal kernel call sites, so malformed metadata is rejected with a
210    /// panic instead of being allowed to create a tensor whose indexing can
211    /// reach outside its allocation. No heap allocation is needed for
212    /// shape/strides up to six dimensions.
213    ///
214    /// # Panics
215    /// Panics when the stride rank, contiguous stride layout, or shape product
216    /// does not match `data.len()`.
217    #[inline]
218    pub fn from_raw_parts(shape: &[usize], strides: &[usize], data: AlignedVec<f32>) -> Self {
219        let expected =
220            shape_element_count(shape).expect("from_raw_parts: shape element count overflow");
221        assert_eq!(
222            expected,
223            data.len(),
224            "from_raw_parts: shape product != data.len()"
225        );
226        let expected_strides =
227            compute_strides(shape).expect("from_raw_parts: stride computation overflow");
228        assert_eq!(
229            strides.len(),
230            shape.len(),
231            "from_raw_parts: shape/stride rank mismatch"
232        );
233        assert_eq!(
234            strides,
235            expected_strides.as_slice(),
236            "from_raw_parts: only contiguous strides are supported"
237        );
238        Self {
239            shape: DimsVec::from(shape),
240            strides: DimsVec::from(strides),
241            storage: Arc::new(Storage::F32(data)),
242            device: Device::Cpu,
243            layout: Layout::NCHW,
244        }
245    }
246
247    /// Builds a tensor from `shape` and a pre-filled [`AlignedVec`].
248    ///
249    /// This avoids the extra copy that [`from_vec`](Self::from_vec) performs when
250    /// converting a `Vec<f32>` into aligned storage.  Use this when the output
251    /// buffer was already allocated as an `AlignedVec` (e.g. via
252    /// [`AlignedVec::uninitialized`] filled by a BLAS/SIMD kernel).
253    pub fn from_aligned(shape: Vec<usize>, data: AlignedVec<f32>) -> Result<Self, TensorError> {
254        let expected = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
255            shape: shape.clone(),
256        })?;
257        if expected != data.len() {
258            return Err(TensorError::SizeMismatch {
259                shape,
260                data_len: data.len(),
261            });
262        }
263
264        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
265            shape: shape.clone(),
266        })?;
267
268        Ok(Self {
269            shape: DimsVec::from(shape),
270            strides,
271            storage: Arc::new(Storage::F32(data)),
272            device: Device::Cpu,
273            layout: Layout::NCHW,
274        })
275    }
276
277    /// Builds a tensor from `shape` and raw contiguous `f32` data.
278    pub fn from_vec(shape: Vec<usize>, data: Vec<f32>) -> Result<Self, TensorError> {
279        let expected = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
280            shape: shape.clone(),
281        })?;
282        if expected != data.len() {
283            return Err(TensorError::SizeMismatch {
284                shape,
285                data_len: data.len(),
286            });
287        }
288
289        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
290            shape: shape.clone(),
291        })?;
292
293        Ok(Self {
294            shape: DimsVec::from(shape),
295            strides,
296            storage: Arc::new(Storage::F32(AlignedVec::from_vec(data))),
297            device: Device::Cpu,
298            layout: Layout::NCHW,
299        })
300    }
301
302    /// Builds a tensor from `shape` and raw FP16 bit patterns (`u16`).
303    pub fn from_f16(shape: Vec<usize>, data: Vec<u16>) -> Result<Self, TensorError> {
304        let expected = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
305            shape: shape.clone(),
306        })?;
307        if expected != data.len() {
308            return Err(TensorError::SizeMismatch {
309                shape,
310                data_len: data.len(),
311            });
312        }
313        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
314            shape: shape.clone(),
315        })?;
316        Ok(Self {
317            shape: DimsVec::from(shape),
318            strides,
319            storage: Arc::new(Storage::F16(data)),
320            device: Device::Cpu,
321            layout: Layout::NCHW,
322        })
323    }
324
325    /// Builds a tensor from `shape` and raw BF16 bit patterns (`u16`).
326    pub fn from_bf16(shape: Vec<usize>, data: Vec<u16>) -> Result<Self, TensorError> {
327        let expected = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
328            shape: shape.clone(),
329        })?;
330        if expected != data.len() {
331            return Err(TensorError::SizeMismatch {
332                shape,
333                data_len: data.len(),
334            });
335        }
336        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
337            shape: shape.clone(),
338        })?;
339        Ok(Self {
340            shape: DimsVec::from(shape),
341            strides,
342            storage: Arc::new(Storage::BF16(data)),
343            device: Device::Cpu,
344            layout: Layout::NCHW,
345        })
346    }
347
348    /// Builds a 1-D tensor from a slice. Equivalent to `from_vec(vec![data.len()], data.to_vec())`.
349    pub fn from_slice(data: &[f32]) -> Self {
350        let n = data.len();
351        Self {
352            shape: DimsVec::from(vec![n]),
353            strides: DimsVec::from(vec![1usize]),
354            storage: Arc::new(Storage::F32(AlignedVec::from_vec(data.to_vec()))),
355            device: Device::Cpu,
356            layout: Layout::NCHW,
357        }
358    }
359
360    /// Builds a value-initialized tensor for a given shape.
361    ///
362    /// Alias: [`full`](Self::full) is provided as a more familiar name.
363    pub fn filled(shape: Vec<usize>, value: f32) -> Result<Self, TensorError> {
364        let count = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
365            shape: shape.clone(),
366        })?;
367        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
368            shape: shape.clone(),
369        })?;
370
371        Ok(Self {
372            shape: DimsVec::from(shape),
373            strides,
374            storage: Arc::new(Storage::F32(AlignedVec::filled(count, value))),
375            device: Device::Cpu,
376            layout: Layout::NCHW,
377        })
378    }
379
380    /// Builds a zero-initialized tensor for a given shape.
381    ///
382    /// Uses `alloc_zeroed` under the hood so the OS can provide pre-zeroed pages
383    /// without writing every byte — significantly faster for large tensors.
384    pub fn zeros(shape: Vec<usize>) -> Result<Self, TensorError> {
385        let count = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
386            shape: shape.clone(),
387        })?;
388        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
389            shape: shape.clone(),
390        })?;
391
392        Ok(Self {
393            shape: DimsVec::from(shape),
394            strides,
395            storage: Arc::new(Storage::F32(AlignedVec::calloc(count))),
396            device: Device::Cpu,
397            layout: Layout::NCHW,
398        })
399    }
400
401    /// Builds a one-initialized tensor for a given shape.
402    pub fn ones(shape: Vec<usize>) -> Result<Self, TensorError> {
403        Self::filled(shape, 1.0)
404    }
405
406    /// Builds a tensor filled with `value`. Alias for [`filled`](Self::filled).
407    pub fn full(shape: Vec<usize>, value: f32) -> Result<Self, TensorError> {
408        Self::filled(shape, value)
409    }
410
411    /// Returns the tensor shape.
412    pub fn shape(&self) -> &[usize] {
413        &self.shape
414    }
415
416    /// Returns the tensor strides.
417    pub fn strides(&self) -> &[usize] {
418        &self.strides
419    }
420
421    /// Returns tensor rank (number of axes).
422    pub fn rank(&self) -> usize {
423        self.shape.len()
424    }
425
426    /// Returns element count.
427    pub fn len(&self) -> usize {
428        self.storage.len()
429    }
430
431    /// Returns `true` if tensor contains zero elements.
432    pub fn is_empty(&self) -> bool {
433        self.storage.len() == 0
434    }
435
436    /// Returns the element data type.
437    pub fn dtype(&self) -> DType {
438        self.storage.dtype()
439    }
440
441    /// Returns the logical device this tensor is associated with.
442    pub const fn device(&self) -> Device {
443        self.device
444    }
445
446    /// Returns a copy of this tensor tagged with the given device.
447    ///
448    /// This is currently a metadata-only operation — no actual data transfer
449    /// occurs. GPU data movement is handled by `GpuSession` in yscv-kernels.
450    pub fn to_device(&self, device: Device) -> Self {
451        Self {
452            shape: self.shape.clone(),
453            strides: self.strides.clone(),
454            storage: self.storage.clone(),
455            device,
456            layout: self.layout,
457        }
458    }
459
460    /// Returns the memory-layout tag. Defaults to `Layout::NCHW`.
461    pub const fn layout(&self) -> Layout {
462        self.layout
463    }
464
465    /// Returns a clone of this tensor retagged with `layout`. This is a
466    /// **metadata** change only — the caller is responsible for having
467    /// already laid out the data correctly for the new layout (use
468    /// `yscv_kernels::ops::layout` kernels for actual reordering).
469    pub const fn with_layout(mut self, layout: Layout) -> Self {
470        self.layout = layout;
471        self
472    }
473
474    /// Returns `true` if the tensor stores f32 data.
475    pub fn is_f32(&self) -> bool {
476        matches!(&*self.storage, Storage::F32(_))
477    }
478
479    /// Fallible version of `data()` — returns an error for non-F32 tensors.
480    pub fn try_data(&self) -> Result<&[f32], TensorError> {
481        match &*self.storage {
482            Storage::F32(v) => Ok(v),
483            _ => Err(TensorError::DTypeMismatch {
484                expected: DType::F32,
485                got: self.dtype(),
486            }),
487        }
488    }
489
490    /// Fallible version of `data_mut()` — returns an error for non-F32 tensors.
491    ///
492    /// Triggers a copy-on-write clone of the underlying storage if it is shared
493    /// (`Arc::strong_count > 1`). When this tensor uniquely owns its storage —
494    /// the common case — the call is a no-op and returns a direct `&mut [f32]`.
495    pub fn try_data_mut(&mut self) -> Result<&mut [f32], TensorError> {
496        let dt = self.storage.dtype();
497        match Arc::make_mut(&mut self.storage) {
498            Storage::F32(v) => Ok(v),
499            _ => Err(TensorError::DTypeMismatch {
500                expected: DType::F32,
501                got: dt,
502            }),
503        }
504    }
505
506    /// Returns an immutable view over contiguous f32 storage.
507    ///
508    /// # Panics
509    /// Panics if the tensor dtype is not F32. Use `try_data()` for a fallible version.
510    #[inline]
511    pub fn data(&self) -> &[f32] {
512        match self.try_data() {
513            Ok(s) => s,
514            Err(_) => panic_not_f32(),
515        }
516    }
517
518    /// Returns a mutable view over contiguous f32 storage.
519    ///
520    /// # Panics
521    /// Panics if the tensor dtype is not F32. Use `try_data_mut()` for a fallible version.
522    #[inline]
523    pub fn data_mut(&mut self) -> &mut [f32] {
524        match self.try_data_mut() {
525            Ok(s) => s,
526            Err(_) => panic_not_f32(),
527        }
528    }
529
530    /// Alias for `try_data()` for backward compatibility.
531    pub fn try_data_f32(&self) -> Result<&[f32], TensorError> {
532        self.try_data()
533    }
534
535    /// Returns raw FP16 bit-pattern data if dtype is F16.
536    pub fn data_f16(&self) -> Result<&[u16], TensorError> {
537        match &*self.storage {
538            Storage::F16(v) => Ok(v),
539            _ => Err(TensorError::DTypeMismatch {
540                expected: DType::F16,
541                got: self.dtype(),
542            }),
543        }
544    }
545
546    /// Returns raw BF16 bit-pattern data if dtype is BF16.
547    pub fn data_bf16(&self) -> Result<&[u16], TensorError> {
548        match &*self.storage {
549            Storage::BF16(v) => Ok(v),
550            _ => Err(TensorError::DTypeMismatch {
551                expected: DType::BF16,
552                got: self.dtype(),
553            }),
554        }
555    }
556
557    /// Converts this tensor to the specified dtype, returning a new tensor.
558    /// Converting to the same dtype is a no-op clone.
559    pub fn to_dtype(&self, target: DType) -> Self {
560        if self.dtype() == target {
561            return self.clone();
562        }
563        let f32_data = self.to_f32_vec();
564        let storage = match target {
565            DType::F32 => Storage::F32(AlignedVec::from_vec(f32_data)),
566            DType::F16 => Storage::F16(f32_data.iter().map(|&v| f32_to_fp16_bits(v)).collect()),
567            DType::BF16 => Storage::BF16(f32_data.iter().map(|&v| f32_to_bf16_bits(v)).collect()),
568        };
569        Self {
570            shape: self.shape.clone(),
571            strides: self.strides.clone(),
572            storage: Arc::new(storage),
573            device: self.device,
574            layout: self.layout,
575        }
576    }
577
578    /// Returns f32 data regardless of internal dtype (converts if necessary).
579    pub(crate) fn to_f32_vec(&self) -> Vec<f32> {
580        match &*self.storage {
581            Storage::F32(v) => v.as_slice().to_vec(),
582            Storage::F16(v) => v.iter().map(|&bits| fp16_bits_to_f32(bits)).collect(),
583            Storage::BF16(v) => v.iter().map(|&bits| bf16_bits_to_f32(bits)).collect(),
584        }
585    }
586
587    /// Reads one element by multi-dimensional index (always returns f32).
588    pub fn get(&self, indices: &[usize]) -> Result<f32, TensorError> {
589        let offset = self.offset_from_indices(indices)?;
590        Ok(match &*self.storage {
591            Storage::F32(v) => v[offset],
592            Storage::F16(v) => fp16_bits_to_f32(v[offset]),
593            Storage::BF16(v) => bf16_bits_to_f32(v[offset]),
594        })
595    }
596
597    /// Writes one element by multi-dimensional index (stores as native dtype).
598    ///
599    /// Triggers a copy-on-write clone of the underlying storage if it is shared
600    /// with another `Tensor` (`Arc::strong_count > 1`). Single-owner writes are
601    /// in-place.
602    pub fn set(&mut self, indices: &[usize], value: f32) -> Result<(), TensorError> {
603        let offset = self.offset_from_indices(indices)?;
604        match Arc::make_mut(&mut self.storage) {
605            Storage::F32(v) => v[offset] = value,
606            Storage::F16(v) => v[offset] = f32_to_fp16_bits(value),
607            Storage::BF16(v) => v[offset] = f32_to_bf16_bits(value),
608        }
609        Ok(())
610    }
611
612    /// Returns a reshaped tensor that shares the underlying data buffer
613    /// with the original via `Arc`. This is an O(1) refcount bump — no
614    /// allocation, no copy. If either tensor is subsequently written via
615    /// `data_mut` or `set`, the storage is cloned lazily (copy-on-write).
616    pub fn reshape(&self, new_shape: Vec<usize>) -> Result<Self, TensorError> {
617        let new_count =
618            shape_element_count(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
619                shape: new_shape.clone(),
620            })?;
621        if new_count != self.len() {
622            return Err(TensorError::ReshapeSizeMismatch {
623                from: self.shape.to_vec(),
624                to: new_shape,
625            });
626        }
627
628        let new_strides = compute_strides(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
629            shape: new_shape.clone(),
630        })?;
631
632        Ok(Self {
633            shape: DimsVec::from(new_shape),
634            strides: new_strides,
635            storage: self.storage.clone(),
636            device: self.device,
637            layout: self.layout,
638        })
639    }
640
641    /// Consumes the tensor and returns a reshaped version without copying data.
642    pub fn into_reshape(self, new_shape: Vec<usize>) -> Result<Self, TensorError> {
643        let new_count =
644            shape_element_count(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
645                shape: new_shape.clone(),
646            })?;
647        if new_count != self.len() {
648            return Err(TensorError::ReshapeSizeMismatch {
649                from: self.shape.to_vec(),
650                to: new_shape,
651            });
652        }
653
654        let new_strides = compute_strides(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
655            shape: new_shape.clone(),
656        })?;
657
658        Ok(Self {
659            shape: DimsVec::from(new_shape),
660            strides: new_strides,
661            storage: self.storage,
662            device: self.device,
663            layout: self.layout,
664        })
665    }
666
667    pub(crate) fn offset_from_indices(&self, indices: &[usize]) -> Result<usize, TensorError> {
668        if indices.len() != self.rank() {
669            return Err(TensorError::InvalidIndexRank {
670                expected: self.rank(),
671                got: indices.len(),
672            });
673        }
674
675        let mut offset = 0usize;
676        for (axis, (index, dim)) in indices.iter().zip(self.shape.iter()).enumerate() {
677            if *index >= *dim {
678                return Err(TensorError::IndexOutOfBounds {
679                    axis,
680                    index: *index,
681                    dim: *dim,
682                });
683            }
684            offset = offset
685                .checked_add(index.checked_mul(self.strides[axis]).ok_or_else(|| {
686                    TensorError::SizeOverflow {
687                        shape: self.shape.to_vec(),
688                    }
689                })?)
690                .ok_or_else(|| TensorError::SizeOverflow {
691                    shape: self.shape.to_vec(),
692                })?;
693        }
694        Ok(offset)
695    }
696}
697
698/// Outlined panic for `Tensor::data()` / `data_mut()` non-F32 path. Marked
699/// `#[cold]` so LLVM moves it out of the hot path's I-cache footprint;
700/// `#[inline(never)]` so the panic-format code is emitted ONCE rather than
701/// duplicated into every caller. The fast path stays inline.
702#[cold]
703#[inline(never)]
704#[track_caller]
705fn panic_not_f32() -> ! {
706    panic!("tensor is not F32");
707}
708
709// ── FP16/BF16 bit conversion primitives ────────────────────────────
710
711const fn f32_to_fp16_bits(val: f32) -> u16 {
712    let bits = val.to_bits();
713    let sign = ((bits >> 16) & 0x8000) as u16;
714    let exponent = ((bits >> 23) & 0xFF) as i32;
715    let mantissa = bits & 0x007FFFFF;
716
717    if exponent == 0xFF {
718        return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 };
719    }
720    let unbiased = exponent - 127;
721    if unbiased < -24 {
722        return sign;
723    }
724    if unbiased < -14 {
725        let shift = -1 - unbiased;
726        let subnormal = ((mantissa | 0x00800000) >> (shift + 13)) as u16;
727        return sign | subnormal;
728    }
729    if unbiased > 15 {
730        return sign | 0x7C00;
731    }
732    let fp16_exp = ((unbiased + 15) as u16) << 10;
733    let fp16_man = (mantissa >> 13) as u16;
734    sign | fp16_exp | fp16_man
735}
736
737const fn fp16_bits_to_f32(half: u16) -> f32 {
738    let sign = ((half & 0x8000) as u32) << 16;
739    let exponent = (half >> 10) & 0x1F;
740    let mantissa = (half & 0x03FF) as u32;
741    if exponent == 0 {
742        if mantissa == 0 {
743            return f32::from_bits(sign);
744        }
745        let mut e = 0i32;
746        let mut m = mantissa;
747        while m & 0x0400 == 0 {
748            m <<= 1;
749            e += 1;
750        }
751        let f32_exp = ((127 - 15 - e) as u32) << 23;
752        let f32_man = (m & 0x03FF) << 13;
753        return f32::from_bits(sign | f32_exp | f32_man);
754    }
755    if exponent == 31 {
756        let f32_bits = sign | 0x7F800000 | if mantissa != 0 { 0x00400000 } else { 0 };
757        return f32::from_bits(f32_bits);
758    }
759    let f32_exp = ((exponent as u32) + 112) << 23;
760    let f32_man = mantissa << 13;
761    f32::from_bits(sign | f32_exp | f32_man)
762}
763
764const fn f32_to_bf16_bits(val: f32) -> u16 {
765    let bits = val.to_bits();
766    // Round to nearest even
767    let rounding_bias = 0x7FFF + ((bits >> 16) & 1);
768    ((bits.wrapping_add(rounding_bias)) >> 16) as u16
769}
770
771const fn bf16_bits_to_f32(bits: u16) -> f32 {
772    f32::from_bits((bits as u32) << 16)
773}
774
775// ── Display impl ────────────────────────────────────────────────────
776
777impl std::fmt::Display for Tensor {
778    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
779        let shape = self.shape();
780        let dtype = self.dtype();
781        let n = self.len();
782
783        write!(f, "Tensor({shape:?}, {dtype:?}")?;
784
785        // Show first few and last few values for a compact preview.
786        const MAX_SHOW: usize = 6;
787        if n == 0 {
788            write!(f, ", []")?;
789        } else {
790            let vals = self.to_f32_vec();
791            write!(f, ", [")?;
792            if n <= MAX_SHOW {
793                for (i, v) in vals.iter().enumerate() {
794                    if i > 0 {
795                        write!(f, ", ")?;
796                    }
797                    write!(f, "{v}")?;
798                }
799            } else {
800                let head = MAX_SHOW / 2;
801                let tail = MAX_SHOW - head;
802                for (i, v) in vals[..head].iter().enumerate() {
803                    if i > 0 {
804                        write!(f, ", ")?;
805                    }
806                    write!(f, "{v}")?;
807                }
808                write!(f, ", ...")?;
809                for v in &vals[n - tail..] {
810                    write!(f, ", {v}")?;
811                }
812            }
813            write!(f, "]")?;
814        }
815        write!(f, ")")
816    }
817}
818
819// ── Operator overloading (std::ops) ─────────────────────────────────
820
821impl std::ops::Add for &Tensor {
822    type Output = Tensor;
823    /// Element-wise addition. Panics on shape mismatch.
824    fn add(self, rhs: Self) -> Tensor {
825        Tensor::add(self, rhs).expect("Tensor + Tensor: shape mismatch")
826    }
827}
828
829impl std::ops::Add for Tensor {
830    type Output = Tensor;
831    fn add(self, rhs: Self) -> Tensor {
832        Tensor::add(&self, &rhs).expect("Tensor + Tensor: shape mismatch")
833    }
834}
835
836impl std::ops::Sub for &Tensor {
837    type Output = Tensor;
838    fn sub(self, rhs: Self) -> Tensor {
839        Tensor::sub(self, rhs).expect("Tensor - Tensor: shape mismatch")
840    }
841}
842
843impl std::ops::Sub for Tensor {
844    type Output = Tensor;
845    fn sub(self, rhs: Self) -> Tensor {
846        Tensor::sub(&self, &rhs).expect("Tensor - Tensor: shape mismatch")
847    }
848}
849
850impl std::ops::Mul for &Tensor {
851    type Output = Tensor;
852    /// Element-wise multiplication. Panics on shape mismatch.
853    fn mul(self, rhs: Self) -> Tensor {
854        Tensor::mul(self, rhs).expect("Tensor * Tensor: shape mismatch")
855    }
856}
857
858impl std::ops::Mul for Tensor {
859    type Output = Tensor;
860    fn mul(self, rhs: Self) -> Tensor {
861        Tensor::mul(&self, &rhs).expect("Tensor * Tensor: shape mismatch")
862    }
863}
864
865impl std::ops::Mul<f32> for &Tensor {
866    type Output = Tensor;
867    /// Scalar multiplication.
868    fn mul(self, rhs: f32) -> Tensor {
869        Tensor::scale(self, rhs)
870    }
871}
872
873impl std::ops::Mul<f32> for Tensor {
874    type Output = Tensor;
875    fn mul(self, rhs: f32) -> Tensor {
876        Tensor::scale(&self, rhs)
877    }
878}
879
880impl std::ops::Div for &Tensor {
881    type Output = Tensor;
882    fn div(self, rhs: Self) -> Tensor {
883        Tensor::div(self, rhs).expect("Tensor / Tensor: shape mismatch")
884    }
885}
886
887impl std::ops::Div for Tensor {
888    type Output = Tensor;
889    fn div(self, rhs: Self) -> Tensor {
890        Tensor::div(&self, &rhs).expect("Tensor / Tensor: shape mismatch")
891    }
892}
893
894impl std::ops::Neg for &Tensor {
895    type Output = Tensor;
896    fn neg(self) -> Tensor {
897        Tensor::neg(self)
898    }
899}
900
901impl std::ops::Neg for Tensor {
902    type Output = Tensor;
903    fn neg(self) -> Tensor {
904        Tensor::neg(&self)
905    }
906}