1use std::sync::Arc;
2
3use super::aligned::AlignedVec;
4use super::error::{DType, TensorError};
5use super::shape::{compute_strides, shape_element_count};
6
7const INLINE_CAP: usize = 6;
11
12#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
101pub enum Device {
102 #[default]
104 Cpu,
105 Gpu(usize),
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
124pub enum Layout {
125 #[default]
127 NCHW,
128 NHWC,
130 NCHWc {
133 block: u8,
135 },
136}
137
138#[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#[derive(Debug, Clone, PartialEq)]
180pub struct Tensor {
181 shape: DimsVec,
182 strides: DimsVec,
183 storage: Arc<Storage>,
190 device: Device,
191 layout: Layout,
192}
193
194impl Tensor {
195 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 #[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 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 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 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 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 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 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 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 pub fn ones(shape: Vec<usize>) -> Result<Self, TensorError> {
380 Self::filled(shape, 1.0)
381 }
382
383 pub fn full(shape: Vec<usize>, value: f32) -> Result<Self, TensorError> {
385 Self::filled(shape, value)
386 }
387
388 pub fn shape(&self) -> &[usize] {
390 &self.shape
391 }
392
393 pub fn strides(&self) -> &[usize] {
395 &self.strides
396 }
397
398 pub fn rank(&self) -> usize {
400 self.shape.len()
401 }
402
403 pub fn len(&self) -> usize {
405 self.storage.len()
406 }
407
408 pub fn is_empty(&self) -> bool {
410 self.storage.len() == 0
411 }
412
413 pub fn dtype(&self) -> DType {
415 self.storage.dtype()
416 }
417
418 pub fn device(&self) -> Device {
420 self.device
421 }
422
423 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 pub fn layout(&self) -> Layout {
439 self.layout
440 }
441
442 pub fn with_layout(mut self, layout: Layout) -> Self {
447 self.layout = layout;
448 self
449 }
450
451 pub fn is_f32(&self) -> bool {
453 matches!(&*self.storage, Storage::F32(_))
454 }
455
456 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 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 pub fn data(&self) -> &[f32] {
488 self.try_data().expect("tensor is not F32")
489 }
490
491 pub fn data_mut(&mut self) -> &mut [f32] {
496 self.try_data_mut().expect("tensor is not F32")
497 }
498
499 pub fn try_data_f32(&self) -> Result<&[f32], TensorError> {
501 self.try_data()
502 }
503
504 pub fn data_f16(&self) -> Result<&[u16], TensorError> {
506 match &*self.storage {
507 Storage::F16(v) => Ok(v),
508 _ => Err(TensorError::DTypeMismatch {
509 expected: DType::F16,
510 got: self.dtype(),
511 }),
512 }
513 }
514
515 pub fn data_bf16(&self) -> Result<&[u16], TensorError> {
517 match &*self.storage {
518 Storage::BF16(v) => Ok(v),
519 _ => Err(TensorError::DTypeMismatch {
520 expected: DType::BF16,
521 got: self.dtype(),
522 }),
523 }
524 }
525
526 pub fn to_dtype(&self, target: DType) -> Self {
529 if self.dtype() == target {
530 return self.clone();
531 }
532 let f32_data = self.to_f32_vec();
533 let storage = match target {
534 DType::F32 => Storage::F32(AlignedVec::from_vec(f32_data)),
535 DType::F16 => Storage::F16(f32_data.iter().map(|&v| f32_to_fp16_bits(v)).collect()),
536 DType::BF16 => Storage::BF16(f32_data.iter().map(|&v| f32_to_bf16_bits(v)).collect()),
537 };
538 Self {
539 shape: self.shape.clone(),
540 strides: self.strides.clone(),
541 storage: Arc::new(storage),
542 device: self.device,
543 layout: self.layout,
544 }
545 }
546
547 pub(crate) fn to_f32_vec(&self) -> Vec<f32> {
549 match &*self.storage {
550 Storage::F32(v) => v.as_slice().to_vec(),
551 Storage::F16(v) => v.iter().map(|&bits| fp16_bits_to_f32(bits)).collect(),
552 Storage::BF16(v) => v.iter().map(|&bits| bf16_bits_to_f32(bits)).collect(),
553 }
554 }
555
556 pub fn get(&self, indices: &[usize]) -> Result<f32, TensorError> {
558 let offset = self.offset_from_indices(indices)?;
559 Ok(match &*self.storage {
560 Storage::F32(v) => v[offset],
561 Storage::F16(v) => fp16_bits_to_f32(v[offset]),
562 Storage::BF16(v) => bf16_bits_to_f32(v[offset]),
563 })
564 }
565
566 pub fn set(&mut self, indices: &[usize], value: f32) -> Result<(), TensorError> {
572 let offset = self.offset_from_indices(indices)?;
573 match Arc::make_mut(&mut self.storage) {
574 Storage::F32(v) => v[offset] = value,
575 Storage::F16(v) => v[offset] = f32_to_fp16_bits(value),
576 Storage::BF16(v) => v[offset] = f32_to_bf16_bits(value),
577 }
578 Ok(())
579 }
580
581 pub fn reshape(&self, new_shape: Vec<usize>) -> Result<Self, TensorError> {
586 let new_count =
587 shape_element_count(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
588 shape: new_shape.clone(),
589 })?;
590 if new_count != self.len() {
591 return Err(TensorError::ReshapeSizeMismatch {
592 from: self.shape.to_vec(),
593 to: new_shape,
594 });
595 }
596
597 let new_strides = compute_strides(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
598 shape: new_shape.clone(),
599 })?;
600
601 Ok(Self {
602 shape: DimsVec::from(new_shape),
603 strides: DimsVec::from(new_strides),
604 storage: self.storage.clone(),
605 device: self.device,
606 layout: self.layout,
607 })
608 }
609
610 pub fn into_reshape(self, new_shape: Vec<usize>) -> Result<Self, TensorError> {
612 let new_count =
613 shape_element_count(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
614 shape: new_shape.clone(),
615 })?;
616 if new_count != self.len() {
617 return Err(TensorError::ReshapeSizeMismatch {
618 from: self.shape.to_vec(),
619 to: new_shape,
620 });
621 }
622
623 let new_strides = compute_strides(&new_shape).ok_or_else(|| TensorError::SizeOverflow {
624 shape: new_shape.clone(),
625 })?;
626
627 Ok(Self {
628 shape: DimsVec::from(new_shape),
629 strides: DimsVec::from(new_strides),
630 storage: self.storage,
631 device: self.device,
632 layout: self.layout,
633 })
634 }
635
636 pub(crate) fn offset_from_indices(&self, indices: &[usize]) -> Result<usize, TensorError> {
637 if indices.len() != self.rank() {
638 return Err(TensorError::InvalidIndexRank {
639 expected: self.rank(),
640 got: indices.len(),
641 });
642 }
643
644 let mut offset = 0usize;
645 for (axis, (index, dim)) in indices.iter().zip(self.shape.iter()).enumerate() {
646 if *index >= *dim {
647 return Err(TensorError::IndexOutOfBounds {
648 axis,
649 index: *index,
650 dim: *dim,
651 });
652 }
653 offset = offset
654 .checked_add(index.checked_mul(self.strides[axis]).ok_or_else(|| {
655 TensorError::SizeOverflow {
656 shape: self.shape.to_vec(),
657 }
658 })?)
659 .ok_or_else(|| TensorError::SizeOverflow {
660 shape: self.shape.to_vec(),
661 })?;
662 }
663 Ok(offset)
664 }
665}
666
667fn f32_to_fp16_bits(val: f32) -> u16 {
670 let bits = val.to_bits();
671 let sign = ((bits >> 16) & 0x8000) as u16;
672 let exponent = ((bits >> 23) & 0xFF) as i32;
673 let mantissa = bits & 0x007FFFFF;
674
675 if exponent == 0xFF {
676 return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 };
677 }
678 let unbiased = exponent - 127;
679 if unbiased < -24 {
680 return sign;
681 }
682 if unbiased < -14 {
683 let shift = -1 - unbiased;
684 let subnormal = ((mantissa | 0x00800000) >> (shift + 13)) as u16;
685 return sign | subnormal;
686 }
687 if unbiased > 15 {
688 return sign | 0x7C00;
689 }
690 let fp16_exp = ((unbiased + 15) as u16) << 10;
691 let fp16_man = (mantissa >> 13) as u16;
692 sign | fp16_exp | fp16_man
693}
694
695fn fp16_bits_to_f32(half: u16) -> f32 {
696 let sign = ((half & 0x8000) as u32) << 16;
697 let exponent = (half >> 10) & 0x1F;
698 let mantissa = (half & 0x03FF) as u32;
699 if exponent == 0 {
700 if mantissa == 0 {
701 return f32::from_bits(sign);
702 }
703 let mut e = 0i32;
704 let mut m = mantissa;
705 while m & 0x0400 == 0 {
706 m <<= 1;
707 e += 1;
708 }
709 let f32_exp = ((127 - 15 - e) as u32) << 23;
710 let f32_man = (m & 0x03FF) << 13;
711 return f32::from_bits(sign | f32_exp | f32_man);
712 }
713 if exponent == 31 {
714 let f32_bits = sign | 0x7F800000 | if mantissa != 0 { 0x00400000 } else { 0 };
715 return f32::from_bits(f32_bits);
716 }
717 let f32_exp = ((exponent as u32) + 112) << 23;
718 let f32_man = mantissa << 13;
719 f32::from_bits(sign | f32_exp | f32_man)
720}
721
722fn f32_to_bf16_bits(val: f32) -> u16 {
723 let bits = val.to_bits();
724 let rounding_bias = 0x7FFF + ((bits >> 16) & 1);
726 ((bits.wrapping_add(rounding_bias)) >> 16) as u16
727}
728
729fn bf16_bits_to_f32(bits: u16) -> f32 {
730 f32::from_bits((bits as u32) << 16)
731}
732
733impl std::fmt::Display for Tensor {
736 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
737 let shape = self.shape();
738 let dtype = self.dtype();
739 let n = self.len();
740
741 write!(f, "Tensor({shape:?}, {dtype:?}")?;
742
743 const MAX_SHOW: usize = 6;
745 if n == 0 {
746 write!(f, ", []")?;
747 } else {
748 let vals = self.to_f32_vec();
749 write!(f, ", [")?;
750 if n <= MAX_SHOW {
751 for (i, v) in vals.iter().enumerate() {
752 if i > 0 {
753 write!(f, ", ")?;
754 }
755 write!(f, "{v}")?;
756 }
757 } else {
758 let head = MAX_SHOW / 2;
759 let tail = MAX_SHOW - head;
760 for (i, v) in vals[..head].iter().enumerate() {
761 if i > 0 {
762 write!(f, ", ")?;
763 }
764 write!(f, "{v}")?;
765 }
766 write!(f, ", ...")?;
767 for v in &vals[n - tail..] {
768 write!(f, ", {v}")?;
769 }
770 }
771 write!(f, "]")?;
772 }
773 write!(f, ")")
774 }
775}
776
777impl std::ops::Add for &Tensor {
780 type Output = Tensor;
781 fn add(self, rhs: Self) -> Tensor {
783 Tensor::add(self, rhs).expect("Tensor + Tensor: shape mismatch")
784 }
785}
786
787impl std::ops::Add for Tensor {
788 type Output = Tensor;
789 fn add(self, rhs: Self) -> Tensor {
790 Tensor::add(&self, &rhs).expect("Tensor + Tensor: shape mismatch")
791 }
792}
793
794impl std::ops::Sub for &Tensor {
795 type Output = Tensor;
796 fn sub(self, rhs: Self) -> Tensor {
797 Tensor::sub(self, rhs).expect("Tensor - Tensor: shape mismatch")
798 }
799}
800
801impl std::ops::Sub for Tensor {
802 type Output = Tensor;
803 fn sub(self, rhs: Self) -> Tensor {
804 Tensor::sub(&self, &rhs).expect("Tensor - Tensor: shape mismatch")
805 }
806}
807
808impl std::ops::Mul for &Tensor {
809 type Output = Tensor;
810 fn mul(self, rhs: Self) -> Tensor {
812 Tensor::mul(self, rhs).expect("Tensor * Tensor: shape mismatch")
813 }
814}
815
816impl std::ops::Mul for Tensor {
817 type Output = Tensor;
818 fn mul(self, rhs: Self) -> Tensor {
819 Tensor::mul(&self, &rhs).expect("Tensor * Tensor: shape mismatch")
820 }
821}
822
823impl std::ops::Mul<f32> for &Tensor {
824 type Output = Tensor;
825 fn mul(self, rhs: f32) -> Tensor {
827 Tensor::scale(self, rhs)
828 }
829}
830
831impl std::ops::Mul<f32> for Tensor {
832 type Output = Tensor;
833 fn mul(self, rhs: f32) -> Tensor {
834 Tensor::scale(&self, rhs)
835 }
836}
837
838impl std::ops::Div for &Tensor {
839 type Output = Tensor;
840 fn div(self, rhs: Self) -> Tensor {
841 Tensor::div(self, rhs).expect("Tensor / Tensor: shape mismatch")
842 }
843}
844
845impl std::ops::Div for Tensor {
846 type Output = Tensor;
847 fn div(self, rhs: Self) -> Tensor {
848 Tensor::div(&self, &rhs).expect("Tensor / Tensor: shape mismatch")
849 }
850}
851
852impl std::ops::Neg for &Tensor {
853 type Output = Tensor;
854 fn neg(self) -> Tensor {
855 Tensor::neg(self)
856 }
857}
858
859impl std::ops::Neg for Tensor {
860 type Output = Tensor;
861 fn neg(self) -> Tensor {
862 Tensor::neg(&self)
863 }
864}