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.
10const 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    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    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    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 pre-validated shape, strides, and data.
207    /// No validation, no heap allocation (shape/strides stored inline for ≤6D).
208    #[inline]
209    pub fn from_raw_parts(shape: &[usize], strides: &[usize], data: AlignedVec<f32>) -> Self {
210        debug_assert_eq!(
211            shape.iter().copied().product::<usize>(),
212            data.len(),
213            "from_raw_parts: shape product != data.len()"
214        );
215        Self {
216            shape: DimsVec::from(shape),
217            strides: DimsVec::from(strides),
218            storage: Arc::new(Storage::F32(data)),
219            device: Device::Cpu,
220            layout: Layout::NCHW,
221        }
222    }
223
224    /// Builds a tensor from `shape` and a pre-filled [`AlignedVec`].
225    ///
226    /// This avoids the extra copy that [`from_vec`](Self::from_vec) performs when
227    /// converting a `Vec<f32>` into aligned storage.  Use this when the output
228    /// buffer was already allocated as an `AlignedVec` (e.g. via
229    /// [`AlignedVec::uninitialized`] filled by a BLAS/SIMD kernel).
230    pub fn from_aligned(shape: Vec<usize>, data: AlignedVec<f32>) -> Result<Self, TensorError> {
231        let expected = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
232            shape: shape.clone(),
233        })?;
234        if expected != data.len() {
235            return Err(TensorError::SizeMismatch {
236                shape,
237                data_len: data.len(),
238            });
239        }
240
241        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
242            shape: shape.clone(),
243        })?;
244
245        Ok(Self {
246            shape: DimsVec::from(shape),
247            strides: DimsVec::from(strides),
248            storage: Arc::new(Storage::F32(data)),
249            device: Device::Cpu,
250            layout: Layout::NCHW,
251        })
252    }
253
254    /// Builds a tensor from `shape` and raw contiguous `f32` data.
255    pub fn from_vec(shape: Vec<usize>, data: Vec<f32>) -> Result<Self, TensorError> {
256        let expected = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
257            shape: shape.clone(),
258        })?;
259        if expected != data.len() {
260            return Err(TensorError::SizeMismatch {
261                shape,
262                data_len: data.len(),
263            });
264        }
265
266        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
267            shape: shape.clone(),
268        })?;
269
270        Ok(Self {
271            shape: DimsVec::from(shape),
272            strides: DimsVec::from(strides),
273            storage: Arc::new(Storage::F32(AlignedVec::from_vec(data))),
274            device: Device::Cpu,
275            layout: Layout::NCHW,
276        })
277    }
278
279    /// Builds a tensor from `shape` and raw FP16 bit patterns (`u16`).
280    pub fn from_f16(shape: Vec<usize>, data: Vec<u16>) -> Result<Self, TensorError> {
281        let expected = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
282            shape: shape.clone(),
283        })?;
284        if expected != data.len() {
285            return Err(TensorError::SizeMismatch {
286                shape,
287                data_len: data.len(),
288            });
289        }
290        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
291            shape: shape.clone(),
292        })?;
293        Ok(Self {
294            shape: DimsVec::from(shape),
295            strides: DimsVec::from(strides),
296            storage: Arc::new(Storage::F16(data)),
297            device: Device::Cpu,
298            layout: Layout::NCHW,
299        })
300    }
301
302    /// Builds a tensor from `shape` and raw BF16 bit patterns (`u16`).
303    pub fn from_bf16(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: DimsVec::from(strides),
319            storage: Arc::new(Storage::BF16(data)),
320            device: Device::Cpu,
321            layout: Layout::NCHW,
322        })
323    }
324
325    /// Builds a 1-D tensor from a slice. Equivalent to `from_vec(vec![data.len()], data.to_vec())`.
326    pub fn from_slice(data: &[f32]) -> Self {
327        let n = data.len();
328        Self {
329            shape: DimsVec::from(vec![n]),
330            strides: DimsVec::from(vec![1usize]),
331            storage: Arc::new(Storage::F32(AlignedVec::from_vec(data.to_vec()))),
332            device: Device::Cpu,
333            layout: Layout::NCHW,
334        }
335    }
336
337    /// Builds a value-initialized tensor for a given shape.
338    ///
339    /// Alias: [`full`](Self::full) is provided as a more familiar name.
340    pub fn filled(shape: Vec<usize>, value: f32) -> Result<Self, TensorError> {
341        let count = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
342            shape: shape.clone(),
343        })?;
344        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
345            shape: shape.clone(),
346        })?;
347
348        Ok(Self {
349            shape: DimsVec::from(shape),
350            strides: DimsVec::from(strides),
351            storage: Arc::new(Storage::F32(AlignedVec::filled(count, value))),
352            device: Device::Cpu,
353            layout: Layout::NCHW,
354        })
355    }
356
357    /// Builds a zero-initialized tensor for a given shape.
358    ///
359    /// Uses `alloc_zeroed` under the hood so the OS can provide pre-zeroed pages
360    /// without writing every byte — significantly faster for large tensors.
361    pub fn zeros(shape: Vec<usize>) -> Result<Self, TensorError> {
362        let count = shape_element_count(&shape).ok_or_else(|| TensorError::SizeOverflow {
363            shape: shape.clone(),
364        })?;
365        let strides = compute_strides(&shape).ok_or_else(|| TensorError::SizeOverflow {
366            shape: shape.clone(),
367        })?;
368
369        Ok(Self {
370            shape: DimsVec::from(shape),
371            strides: DimsVec::from(strides),
372            storage: Arc::new(Storage::F32(AlignedVec::calloc(count))),
373            device: Device::Cpu,
374            layout: Layout::NCHW,
375        })
376    }
377
378    /// Builds a one-initialized tensor for a given shape.
379    pub fn ones(shape: Vec<usize>) -> Result<Self, TensorError> {
380        Self::filled(shape, 1.0)
381    }
382
383    /// Builds a tensor filled with `value`. Alias for [`filled`](Self::filled).
384    pub fn full(shape: Vec<usize>, value: f32) -> Result<Self, TensorError> {
385        Self::filled(shape, value)
386    }
387
388    /// Returns the tensor shape.
389    pub fn shape(&self) -> &[usize] {
390        &self.shape
391    }
392
393    /// Returns the tensor strides.
394    pub fn strides(&self) -> &[usize] {
395        &self.strides
396    }
397
398    /// Returns tensor rank (number of axes).
399    pub fn rank(&self) -> usize {
400        self.shape.len()
401    }
402
403    /// Returns element count.
404    pub fn len(&self) -> usize {
405        self.storage.len()
406    }
407
408    /// Returns `true` if tensor contains zero elements.
409    pub fn is_empty(&self) -> bool {
410        self.storage.len() == 0
411    }
412
413    /// Returns the element data type.
414    pub fn dtype(&self) -> DType {
415        self.storage.dtype()
416    }
417
418    /// Returns the logical device this tensor is associated with.
419    pub fn device(&self) -> Device {
420        self.device
421    }
422
423    /// Returns a copy of this tensor tagged with the given device.
424    ///
425    /// This is currently a metadata-only operation — no actual data transfer
426    /// occurs. GPU data movement is handled by `GpuSession` in yscv-kernels.
427    pub fn to_device(&self, device: Device) -> Self {
428        Self {
429            shape: self.shape.clone(),
430            strides: self.strides.clone(),
431            storage: self.storage.clone(),
432            device,
433            layout: self.layout,
434        }
435    }
436
437    /// Returns the memory-layout tag. Defaults to `Layout::NCHW`.
438    pub fn layout(&self) -> Layout {
439        self.layout
440    }
441
442    /// Returns a clone of this tensor retagged with `layout`. This is a
443    /// **metadata** change only — the caller is responsible for having
444    /// already laid out the data correctly for the new layout (use
445    /// `yscv_kernels::ops::layout` kernels for actual reordering).
446    pub fn with_layout(mut self, layout: Layout) -> Self {
447        self.layout = layout;
448        self
449    }
450
451    /// Returns `true` if the tensor stores f32 data.
452    pub fn is_f32(&self) -> bool {
453        matches!(&*self.storage, Storage::F32(_))
454    }
455
456    /// Fallible version of `data()` — returns an error for non-F32 tensors.
457    pub fn try_data(&self) -> Result<&[f32], TensorError> {
458        match &*self.storage {
459            Storage::F32(v) => Ok(v),
460            _ => Err(TensorError::DTypeMismatch {
461                expected: DType::F32,
462                got: self.dtype(),
463            }),
464        }
465    }
466
467    /// Fallible version of `data_mut()` — returns an error for non-F32 tensors.
468    ///
469    /// Triggers a copy-on-write clone of the underlying storage if it is shared
470    /// (`Arc::strong_count > 1`). When this tensor uniquely owns its storage —
471    /// the common case — the call is a no-op and returns a direct `&mut [f32]`.
472    pub fn try_data_mut(&mut self) -> Result<&mut [f32], TensorError> {
473        let dt = self.storage.dtype();
474        match Arc::make_mut(&mut self.storage) {
475            Storage::F32(v) => Ok(v),
476            _ => Err(TensorError::DTypeMismatch {
477                expected: DType::F32,
478                got: dt,
479            }),
480        }
481    }
482
483    /// Returns an immutable view over contiguous f32 storage.
484    ///
485    /// # Panics
486    /// Panics if the tensor dtype is not F32. Use `try_data()` for a fallible version.
487    #[inline]
488    pub fn data(&self) -> &[f32] {
489        match self.try_data() {
490            Ok(s) => s,
491            Err(_) => panic_not_f32(),
492        }
493    }
494
495    /// Returns a mutable view over contiguous f32 storage.
496    ///
497    /// # Panics
498    /// Panics if the tensor dtype is not F32. Use `try_data_mut()` for a fallible version.
499    #[inline]
500    pub fn data_mut(&mut self) -> &mut [f32] {
501        match self.try_data_mut() {
502            Ok(s) => s,
503            Err(_) => panic_not_f32(),
504        }
505    }
506
507    /// Alias for `try_data()` for backward compatibility.
508    pub fn try_data_f32(&self) -> Result<&[f32], TensorError> {
509        self.try_data()
510    }
511
512    /// Returns raw FP16 bit-pattern data if dtype is F16.
513    pub fn data_f16(&self) -> Result<&[u16], TensorError> {
514        match &*self.storage {
515            Storage::F16(v) => Ok(v),
516            _ => Err(TensorError::DTypeMismatch {
517                expected: DType::F16,
518                got: self.dtype(),
519            }),
520        }
521    }
522
523    /// Returns raw BF16 bit-pattern data if dtype is BF16.
524    pub fn data_bf16(&self) -> Result<&[u16], TensorError> {
525        match &*self.storage {
526            Storage::BF16(v) => Ok(v),
527            _ => Err(TensorError::DTypeMismatch {
528                expected: DType::BF16,
529                got: self.dtype(),
530            }),
531        }
532    }
533
534    /// Converts this tensor to the specified dtype, returning a new tensor.
535    /// Converting to the same dtype is a no-op clone.
536    pub fn to_dtype(&self, target: DType) -> Self {
537        if self.dtype() == target {
538            return self.clone();
539        }
540        let f32_data = self.to_f32_vec();
541        let storage = match target {
542            DType::F32 => Storage::F32(AlignedVec::from_vec(f32_data)),
543            DType::F16 => Storage::F16(f32_data.iter().map(|&v| f32_to_fp16_bits(v)).collect()),
544            DType::BF16 => Storage::BF16(f32_data.iter().map(|&v| f32_to_bf16_bits(v)).collect()),
545        };
546        Self {
547            shape: self.shape.clone(),
548            strides: self.strides.clone(),
549            storage: Arc::new(storage),
550            device: self.device,
551            layout: self.layout,
552        }
553    }
554
555    /// Returns f32 data regardless of internal dtype (converts if necessary).
556    pub(crate) fn to_f32_vec(&self) -> Vec<f32> {
557        match &*self.storage {
558            Storage::F32(v) => v.as_slice().to_vec(),
559            Storage::F16(v) => v.iter().map(|&bits| fp16_bits_to_f32(bits)).collect(),
560            Storage::BF16(v) => v.iter().map(|&bits| bf16_bits_to_f32(bits)).collect(),
561        }
562    }
563
564    /// Reads one element by multi-dimensional index (always returns f32).
565    pub fn get(&self, indices: &[usize]) -> Result<f32, TensorError> {
566        let offset = self.offset_from_indices(indices)?;
567        Ok(match &*self.storage {
568            Storage::F32(v) => v[offset],
569            Storage::F16(v) => fp16_bits_to_f32(v[offset]),
570            Storage::BF16(v) => bf16_bits_to_f32(v[offset]),
571        })
572    }
573
574    /// Writes one element by multi-dimensional index (stores as native dtype).
575    ///
576    /// Triggers a copy-on-write clone of the underlying storage if it is shared
577    /// with another `Tensor` (`Arc::strong_count > 1`). Single-owner writes are
578    /// in-place.
579    pub fn set(&mut self, indices: &[usize], value: f32) -> Result<(), TensorError> {
580        let offset = self.offset_from_indices(indices)?;
581        match Arc::make_mut(&mut self.storage) {
582            Storage::F32(v) => v[offset] = value,
583            Storage::F16(v) => v[offset] = f32_to_fp16_bits(value),
584            Storage::BF16(v) => v[offset] = f32_to_bf16_bits(value),
585        }
586        Ok(())
587    }
588
589    /// Returns a reshaped tensor that shares the underlying data buffer
590    /// with the original via `Arc`. This is an O(1) refcount bump — no
591    /// allocation, no copy. If either tensor is subsequently written via
592    /// `data_mut` or `set`, the storage is cloned lazily (copy-on-write).
593    pub fn reshape(&self, new_shape: Vec<usize>) -> Result<Self, TensorError> {
594        let new_count =
595            shape_element_count(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
596                shape: new_shape.clone(),
597            })?;
598        if new_count != self.len() {
599            return Err(TensorError::ReshapeSizeMismatch {
600                from: self.shape.to_vec(),
601                to: new_shape,
602            });
603        }
604
605        let new_strides = compute_strides(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
606            shape: new_shape.clone(),
607        })?;
608
609        Ok(Self {
610            shape: DimsVec::from(new_shape),
611            strides: DimsVec::from(new_strides),
612            storage: self.storage.clone(),
613            device: self.device,
614            layout: self.layout,
615        })
616    }
617
618    /// Consumes the tensor and returns a reshaped version without copying data.
619    pub fn into_reshape(self, new_shape: Vec<usize>) -> Result<Self, TensorError> {
620        let new_count =
621            shape_element_count(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
622                shape: new_shape.clone(),
623            })?;
624        if new_count != self.len() {
625            return Err(TensorError::ReshapeSizeMismatch {
626                from: self.shape.to_vec(),
627                to: new_shape,
628            });
629        }
630
631        let new_strides = compute_strides(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
632            shape: new_shape.clone(),
633        })?;
634
635        Ok(Self {
636            shape: DimsVec::from(new_shape),
637            strides: DimsVec::from(new_strides),
638            storage: self.storage,
639            device: self.device,
640            layout: self.layout,
641        })
642    }
643
644    pub(crate) fn offset_from_indices(&self, indices: &[usize]) -> Result<usize, TensorError> {
645        if indices.len() != self.rank() {
646            return Err(TensorError::InvalidIndexRank {
647                expected: self.rank(),
648                got: indices.len(),
649            });
650        }
651
652        let mut offset = 0usize;
653        for (axis, (index, dim)) in indices.iter().zip(self.shape.iter()).enumerate() {
654            if *index >= *dim {
655                return Err(TensorError::IndexOutOfBounds {
656                    axis,
657                    index: *index,
658                    dim: *dim,
659                });
660            }
661            offset = offset
662                .checked_add(index.checked_mul(self.strides[axis]).ok_or_else(|| {
663                    TensorError::SizeOverflow {
664                        shape: self.shape.to_vec(),
665                    }
666                })?)
667                .ok_or_else(|| TensorError::SizeOverflow {
668                    shape: self.shape.to_vec(),
669                })?;
670        }
671        Ok(offset)
672    }
673}
674
675/// Outlined panic for `Tensor::data()` / `data_mut()` non-F32 path. Marked
676/// `#[cold]` so LLVM moves it out of the hot path's I-cache footprint;
677/// `#[inline(never)]` so the panic-format code is emitted ONCE rather than
678/// duplicated into every caller. The fast path stays inline.
679#[cold]
680#[inline(never)]
681#[track_caller]
682fn panic_not_f32() -> ! {
683    panic!("tensor is not F32");
684}
685
686// ── FP16/BF16 bit conversion primitives ────────────────────────────
687
688fn f32_to_fp16_bits(val: f32) -> u16 {
689    let bits = val.to_bits();
690    let sign = ((bits >> 16) & 0x8000) as u16;
691    let exponent = ((bits >> 23) & 0xFF) as i32;
692    let mantissa = bits & 0x007FFFFF;
693
694    if exponent == 0xFF {
695        return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 };
696    }
697    let unbiased = exponent - 127;
698    if unbiased < -24 {
699        return sign;
700    }
701    if unbiased < -14 {
702        let shift = -1 - unbiased;
703        let subnormal = ((mantissa | 0x00800000) >> (shift + 13)) as u16;
704        return sign | subnormal;
705    }
706    if unbiased > 15 {
707        return sign | 0x7C00;
708    }
709    let fp16_exp = ((unbiased + 15) as u16) << 10;
710    let fp16_man = (mantissa >> 13) as u16;
711    sign | fp16_exp | fp16_man
712}
713
714fn fp16_bits_to_f32(half: u16) -> f32 {
715    let sign = ((half & 0x8000) as u32) << 16;
716    let exponent = (half >> 10) & 0x1F;
717    let mantissa = (half & 0x03FF) as u32;
718    if exponent == 0 {
719        if mantissa == 0 {
720            return f32::from_bits(sign);
721        }
722        let mut e = 0i32;
723        let mut m = mantissa;
724        while m & 0x0400 == 0 {
725            m <<= 1;
726            e += 1;
727        }
728        let f32_exp = ((127 - 15 - e) as u32) << 23;
729        let f32_man = (m & 0x03FF) << 13;
730        return f32::from_bits(sign | f32_exp | f32_man);
731    }
732    if exponent == 31 {
733        let f32_bits = sign | 0x7F800000 | if mantissa != 0 { 0x00400000 } else { 0 };
734        return f32::from_bits(f32_bits);
735    }
736    let f32_exp = ((exponent as u32) + 112) << 23;
737    let f32_man = mantissa << 13;
738    f32::from_bits(sign | f32_exp | f32_man)
739}
740
741fn f32_to_bf16_bits(val: f32) -> u16 {
742    let bits = val.to_bits();
743    // Round to nearest even
744    let rounding_bias = 0x7FFF + ((bits >> 16) & 1);
745    ((bits.wrapping_add(rounding_bias)) >> 16) as u16
746}
747
748fn bf16_bits_to_f32(bits: u16) -> f32 {
749    f32::from_bits((bits as u32) << 16)
750}
751
752// ── Display impl ────────────────────────────────────────────────────
753
754impl std::fmt::Display for Tensor {
755    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
756        let shape = self.shape();
757        let dtype = self.dtype();
758        let n = self.len();
759
760        write!(f, "Tensor({shape:?}, {dtype:?}")?;
761
762        // Show first few and last few values for a compact preview.
763        const MAX_SHOW: usize = 6;
764        if n == 0 {
765            write!(f, ", []")?;
766        } else {
767            let vals = self.to_f32_vec();
768            write!(f, ", [")?;
769            if n <= MAX_SHOW {
770                for (i, v) in vals.iter().enumerate() {
771                    if i > 0 {
772                        write!(f, ", ")?;
773                    }
774                    write!(f, "{v}")?;
775                }
776            } else {
777                let head = MAX_SHOW / 2;
778                let tail = MAX_SHOW - head;
779                for (i, v) in vals[..head].iter().enumerate() {
780                    if i > 0 {
781                        write!(f, ", ")?;
782                    }
783                    write!(f, "{v}")?;
784                }
785                write!(f, ", ...")?;
786                for v in &vals[n - tail..] {
787                    write!(f, ", {v}")?;
788                }
789            }
790            write!(f, "]")?;
791        }
792        write!(f, ")")
793    }
794}
795
796// ── Operator overloading (std::ops) ─────────────────────────────────
797
798impl std::ops::Add for &Tensor {
799    type Output = Tensor;
800    /// Element-wise addition. Panics on shape mismatch.
801    fn add(self, rhs: Self) -> Tensor {
802        Tensor::add(self, rhs).expect("Tensor + Tensor: shape mismatch")
803    }
804}
805
806impl std::ops::Add for Tensor {
807    type Output = Tensor;
808    fn add(self, rhs: Self) -> Tensor {
809        Tensor::add(&self, &rhs).expect("Tensor + Tensor: shape mismatch")
810    }
811}
812
813impl std::ops::Sub for &Tensor {
814    type Output = Tensor;
815    fn sub(self, rhs: Self) -> Tensor {
816        Tensor::sub(self, rhs).expect("Tensor - Tensor: shape mismatch")
817    }
818}
819
820impl std::ops::Sub for Tensor {
821    type Output = Tensor;
822    fn sub(self, rhs: Self) -> Tensor {
823        Tensor::sub(&self, &rhs).expect("Tensor - Tensor: shape mismatch")
824    }
825}
826
827impl std::ops::Mul for &Tensor {
828    type Output = Tensor;
829    /// Element-wise multiplication. Panics on shape mismatch.
830    fn mul(self, rhs: Self) -> Tensor {
831        Tensor::mul(self, rhs).expect("Tensor * Tensor: shape mismatch")
832    }
833}
834
835impl std::ops::Mul for Tensor {
836    type Output = Tensor;
837    fn mul(self, rhs: Self) -> Tensor {
838        Tensor::mul(&self, &rhs).expect("Tensor * Tensor: shape mismatch")
839    }
840}
841
842impl std::ops::Mul<f32> for &Tensor {
843    type Output = Tensor;
844    /// Scalar multiplication.
845    fn mul(self, rhs: f32) -> Tensor {
846        Tensor::scale(self, rhs)
847    }
848}
849
850impl std::ops::Mul<f32> for Tensor {
851    type Output = Tensor;
852    fn mul(self, rhs: f32) -> Tensor {
853        Tensor::scale(&self, rhs)
854    }
855}
856
857impl std::ops::Div for &Tensor {
858    type Output = Tensor;
859    fn div(self, rhs: Self) -> Tensor {
860        Tensor::div(self, rhs).expect("Tensor / Tensor: shape mismatch")
861    }
862}
863
864impl std::ops::Div for Tensor {
865    type Output = Tensor;
866    fn div(self, rhs: Self) -> Tensor {
867        Tensor::div(&self, &rhs).expect("Tensor / Tensor: shape mismatch")
868    }
869}
870
871impl std::ops::Neg for &Tensor {
872    type Output = Tensor;
873    fn neg(self) -> Tensor {
874        Tensor::neg(self)
875    }
876}
877
878impl std::ops::Neg for Tensor {
879    type Output = Tensor;
880    fn neg(self) -> Tensor {
881        Tensor::neg(&self)
882    }
883}