burn_ndarray/
tensor.rs

1use core::mem;
2
3use burn_tensor::{
4    DType, Element, Shape, TensorData, TensorMetadata,
5    quantization::{
6        QParams, QTensorPrimitive, QuantizationMode, QuantizationScheme, QuantizationStrategy,
7        QuantizationType, SymmetricQuantization,
8    },
9};
10
11use alloc::vec::Vec;
12use ndarray::{ArcArray, ArrayD, IxDyn};
13
14use crate::element::QuantElement;
15
16/// Tensor primitive used by the [ndarray backend](crate::NdArray).
17#[derive(new, Debug, Clone)]
18pub struct NdArrayTensor<E> {
19    /// Dynamic array that contains the data of type E.
20    pub array: ArcArray<E, IxDyn>,
21}
22
23impl<E: Element> TensorMetadata for NdArrayTensor<E> {
24    fn dtype(&self) -> DType {
25        E::dtype()
26    }
27
28    fn shape(&self) -> Shape {
29        Shape::from(self.array.shape().to_vec())
30    }
31}
32
33/// Float tensor primitive.
34#[derive(Debug, Clone)]
35pub enum NdArrayTensorFloat {
36    /// 32-bit float.
37    F32(NdArrayTensor<f32>),
38    /// 64-bit float.
39    F64(NdArrayTensor<f64>),
40}
41
42impl From<NdArrayTensor<f32>> for NdArrayTensorFloat {
43    fn from(value: NdArrayTensor<f32>) -> Self {
44        NdArrayTensorFloat::F32(value)
45    }
46}
47
48impl From<NdArrayTensor<f64>> for NdArrayTensorFloat {
49    fn from(value: NdArrayTensor<f64>) -> Self {
50        NdArrayTensorFloat::F64(value)
51    }
52}
53
54impl TensorMetadata for NdArrayTensorFloat {
55    fn dtype(&self) -> DType {
56        match self {
57            NdArrayTensorFloat::F32(tensor) => tensor.dtype(),
58            NdArrayTensorFloat::F64(tensor) => tensor.dtype(),
59        }
60    }
61
62    fn shape(&self) -> Shape {
63        match self {
64            NdArrayTensorFloat::F32(tensor) => tensor.shape(),
65            NdArrayTensorFloat::F64(tensor) => tensor.shape(),
66        }
67    }
68}
69
70/// Macro to create a new [float tensor](NdArrayTensorFloat) based on the element type.
71#[macro_export]
72macro_rules! new_tensor_float {
73    // Op executed with default dtype
74    ($tensor:expr) => {{
75        match E::dtype() {
76            burn_tensor::DType::F64 => $crate::NdArrayTensorFloat::F64($tensor),
77            burn_tensor::DType::F32 => $crate::NdArrayTensorFloat::F32($tensor),
78            // FloatNdArrayElement only implemented for f64 and f32
79            _ => unimplemented!("Unsupported dtype"),
80        }
81    }};
82}
83
84/// Macro to execute an operation a given element type.
85///
86/// # Panics
87/// Since there is no automatic type cast at this time, binary operations for different
88/// floating point precision data types will panic with a data type mismatch.
89#[macro_export]
90macro_rules! execute_with_float_dtype {
91    // Binary op: type automatically inferred by the compiler
92    (($lhs:expr, $rhs:expr), $op:expr) => {{
93        let lhs_dtype = burn_tensor::TensorMetadata::dtype(&$lhs);
94        let rhs_dtype = burn_tensor::TensorMetadata::dtype(&$rhs);
95        match ($lhs, $rhs) {
96            ($crate::NdArrayTensorFloat::F64(lhs), $crate::NdArrayTensorFloat::F64(rhs)) => {
97                $crate::NdArrayTensorFloat::F64($op(lhs, rhs))
98            }
99            ($crate::NdArrayTensorFloat::F32(lhs), $crate::NdArrayTensorFloat::F32(rhs)) => {
100                $crate::NdArrayTensorFloat::F32($op(lhs, rhs))
101            }
102            _ => panic!(
103                "Data type mismatch (lhs: {:?}, rhs: {:?})",
104                lhs_dtype, rhs_dtype
105            ),
106        }
107    }};
108
109    // Binary op: generic type cannot be inferred for an operation
110    (($lhs:expr, $rhs:expr), $element:ident, $op:expr) => {{
111        let lhs_dtype = burn_tensor::TensorMetadata::dtype(&$lhs);
112        let rhs_dtype = burn_tensor::TensorMetadata::dtype(&$rhs);
113        match ($lhs, $rhs) {
114            ($crate::NdArrayTensorFloat::F64(lhs), $crate::NdArrayTensorFloat::F64(rhs)) => {
115                type $element = f64;
116                $crate::NdArrayTensorFloat::F64($op(lhs, rhs))
117            }
118            ($crate::NdArrayTensorFloat::F32(lhs), $crate::NdArrayTensorFloat::F32(rhs)) => {
119                type $element = f32;
120                $crate::NdArrayTensorFloat::F32($op(lhs, rhs))
121            }
122            _ => panic!(
123                "Data type mismatch (lhs: {:?}, rhs: {:?})",
124                lhs_dtype, rhs_dtype
125            ),
126        }
127    }};
128
129    // Binary op: type automatically inferred by the compiler but return type is not a float tensor
130    (($lhs:expr, $rhs:expr) => $op:expr) => {{
131        let lhs_dtype = burn_tensor::TensorMetadata::dtype(&$lhs);
132        let rhs_dtype = burn_tensor::TensorMetadata::dtype(&$rhs);
133        match ($lhs, $rhs) {
134            ($crate::NdArrayTensorFloat::F64(lhs), $crate::NdArrayTensorFloat::F64(rhs)) => {
135                $op(lhs, rhs)
136            }
137            ($crate::NdArrayTensorFloat::F32(lhs), $crate::NdArrayTensorFloat::F32(rhs)) => {
138                $op(lhs, rhs)
139            }
140            _ => panic!(
141                "Data type mismatch (lhs: {:?}, rhs: {:?})",
142                lhs_dtype, rhs_dtype
143            ),
144        }
145    }};
146
147    // Unary op: type automatically inferred by the compiler
148    ($tensor:expr, $op:expr) => {{
149        match $tensor {
150            $crate::NdArrayTensorFloat::F64(tensor) => $crate::NdArrayTensorFloat::F64($op(tensor)),
151            $crate::NdArrayTensorFloat::F32(tensor) => $crate::NdArrayTensorFloat::F32($op(tensor)),
152        }
153    }};
154
155    // Unary op: generic type cannot be inferred for an operation
156    ($tensor:expr, $element:ident, $op:expr) => {{
157        match $tensor {
158            $crate::NdArrayTensorFloat::F64(tensor) => {
159                type $element = f64;
160                $crate::NdArrayTensorFloat::F64($op(tensor))
161            }
162            $crate::NdArrayTensorFloat::F32(tensor) => {
163                type $element = f32;
164                $crate::NdArrayTensorFloat::F32($op(tensor))
165            }
166        }
167    }};
168
169    // Unary op: type automatically inferred by the compiler but return type is not a float tensor
170    ($tensor:expr => $op:expr) => {{
171        match $tensor {
172            $crate::NdArrayTensorFloat::F64(tensor) => $op(tensor),
173            $crate::NdArrayTensorFloat::F32(tensor) => $op(tensor),
174        }
175    }};
176
177    // Unary op: generic type cannot be inferred for an operation and return type is not a float tensor
178    ($tensor:expr, $element:ident => $op:expr) => {{
179        match $tensor {
180            $crate::NdArrayTensorFloat::F64(tensor) => {
181                type $element = f64;
182                $op(tensor)
183            }
184            $crate::NdArrayTensorFloat::F32(tensor) => {
185                type $element = f32;
186                $op(tensor)
187            }
188        }
189    }};
190}
191
192mod utils {
193    use burn_common::tensor::is_contiguous;
194
195    use super::*;
196
197    impl<E> NdArrayTensor<E>
198    where
199        E: Element,
200    {
201        pub(crate) fn into_data(self) -> TensorData {
202            let shape = self.shape();
203
204            let vec = if self.is_contiguous() {
205                match self.array.try_into_owned_nocopy() {
206                    Ok(owned) => {
207                        let (mut vec, offset) = owned.into_raw_vec_and_offset();
208                        if let Some(offset) = offset {
209                            vec.drain(..offset);
210                        }
211                        vec
212                    }
213                    Err(array) => array.into_iter().collect(),
214                }
215            } else {
216                self.array.into_iter().collect()
217            };
218
219            TensorData::new(vec, shape)
220        }
221
222        pub(crate) fn is_contiguous(&self) -> bool {
223            let shape = self.array.shape();
224            let mut strides = Vec::with_capacity(self.array.strides().len());
225
226            for &stride in self.array.strides() {
227                if stride <= 0 {
228                    return false;
229                }
230                strides.push(stride as usize);
231            }
232            is_contiguous(shape, &strides)
233        }
234    }
235}
236
237/// Converts a slice of usize to a typed dimension.
238#[macro_export(local_inner_macros)]
239macro_rules! to_typed_dims {
240    (
241        $n:expr,
242        $dims:expr,
243        justdim
244    ) => {{
245        let mut dims = [0; $n];
246        for i in 0..$n {
247            dims[i] = $dims[i];
248        }
249        let dim: Dim<[usize; $n]> = Dim(dims);
250        dim
251    }};
252}
253
254/// Reshapes an array into a tensor.
255#[macro_export(local_inner_macros)]
256macro_rules! reshape {
257    (
258        ty $ty:ty,
259        n $n:expr,
260        shape $shape:expr,
261        array $array:expr
262    ) => {{
263        let dim = $crate::to_typed_dims!($n, $shape.dims, justdim);
264        let array: ndarray::ArcArray<$ty, Dim<[usize; $n]>> = match $array.is_standard_layout() {
265            true => {
266                match $array.to_shape(dim) {
267                    Ok(val) => val.into_shared(),
268                    Err(err) => {
269                        core::panic!("Shape should be compatible shape={dim:?}: {err:?}");
270                    }
271                }
272            },
273            false => $array.to_shape(dim).unwrap().as_standard_layout().into_shared(),
274        };
275        let array = array.into_dyn();
276
277        NdArrayTensor::new(array)
278    }};
279    (
280        ty $ty:ty,
281        shape $shape:expr,
282        array $array:expr,
283        d $D:expr
284    ) => {{
285        match $D {
286            1 => reshape!(ty $ty, n 1, shape $shape, array $array),
287            2 => reshape!(ty $ty, n 2, shape $shape, array $array),
288            3 => reshape!(ty $ty, n 3, shape $shape, array $array),
289            4 => reshape!(ty $ty, n 4, shape $shape, array $array),
290            5 => reshape!(ty $ty, n 5, shape $shape, array $array),
291            6 => reshape!(ty $ty, n 6, shape $shape, array $array),
292            _ => core::panic!("NdArray supports arrays up to 6 dimensions, received: {}", $D),
293        }
294    }};
295}
296
297impl<E> NdArrayTensor<E>
298where
299    E: Element,
300{
301    /// Create a new [ndarray tensor](NdArrayTensor) from [data](TensorData).
302    pub fn from_data(mut data: TensorData) -> NdArrayTensor<E> {
303        let shape = mem::take(&mut data.shape);
304
305        let array = match data.into_vec::<E>() {
306            // Safety: TensorData checks shape validity on creation, so we don't need to repeat that check here
307            Ok(vec) => unsafe { ArrayD::from_shape_vec_unchecked(shape, vec) }.into_shared(),
308            Err(err) => panic!("Data should have the same element type as the tensor {err:?}"),
309        };
310
311        NdArrayTensor::new(array)
312    }
313}
314
315/// A quantized tensor for the ndarray backend.
316#[derive(Clone, Debug)]
317pub struct NdArrayQTensor<Q: QuantElement> {
318    /// The quantized tensor.
319    pub qtensor: NdArrayTensor<Q>,
320    /// The quantization scheme.
321    pub scheme: QuantizationScheme,
322    /// The quantization parameters.
323    pub qparams: Vec<QParams<f32, Q>>,
324}
325
326impl<Q: QuantElement> NdArrayQTensor<Q> {
327    /// Returns the quantization strategy, including quantization parameters, for the given tensor.
328    pub fn strategy(&self) -> QuantizationStrategy {
329        match self.scheme {
330            QuantizationScheme::PerTensor(QuantizationMode::Symmetric, QuantizationType::QInt8) => {
331                QuantizationStrategy::PerTensorSymmetricInt8(SymmetricQuantization::init(
332                    self.qparams[0].scale,
333                ))
334            }
335        }
336    }
337}
338
339impl<Q: QuantElement> QTensorPrimitive for NdArrayQTensor<Q> {
340    fn scheme(&self) -> &QuantizationScheme {
341        &self.scheme
342    }
343}
344
345impl<Q: QuantElement> TensorMetadata for NdArrayQTensor<Q> {
346    fn dtype(&self) -> DType {
347        DType::QFloat(self.scheme)
348    }
349
350    fn shape(&self) -> Shape {
351        self.qtensor.shape()
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use crate::NdArray;
358
359    use super::*;
360    use burn_common::rand::get_seeded_rng;
361    use burn_tensor::{
362        Distribution,
363        ops::{FloatTensorOps, QTensorOps},
364        quantization::{QuantizationParametersPrimitive, QuantizationType},
365    };
366
367    #[test]
368    fn should_support_into_and_from_data_1d() {
369        let data_expected = TensorData::random::<f32, _, _>(
370            Shape::new([3]),
371            Distribution::Default,
372            &mut get_seeded_rng(),
373        );
374        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
375
376        let data_actual = tensor.into_data();
377
378        assert_eq!(data_expected, data_actual);
379    }
380
381    #[test]
382    fn should_support_into_and_from_data_2d() {
383        let data_expected = TensorData::random::<f32, _, _>(
384            Shape::new([2, 3]),
385            Distribution::Default,
386            &mut get_seeded_rng(),
387        );
388        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
389
390        let data_actual = tensor.into_data();
391
392        assert_eq!(data_expected, data_actual);
393    }
394
395    #[test]
396    fn should_support_into_and_from_data_3d() {
397        let data_expected = TensorData::random::<f32, _, _>(
398            Shape::new([2, 3, 4]),
399            Distribution::Default,
400            &mut get_seeded_rng(),
401        );
402        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
403
404        let data_actual = tensor.into_data();
405
406        assert_eq!(data_expected, data_actual);
407    }
408
409    #[test]
410    fn should_support_into_and_from_data_4d() {
411        let data_expected = TensorData::random::<f32, _, _>(
412            Shape::new([2, 3, 4, 2]),
413            Distribution::Default,
414            &mut get_seeded_rng(),
415        );
416        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
417
418        let data_actual = tensor.into_data();
419
420        assert_eq!(data_expected, data_actual);
421    }
422
423    #[test]
424    fn should_support_qtensor_strategy() {
425        type B = NdArray<f32, i64, i8>;
426        let scale: f32 = 0.009_019_608;
427        let device = Default::default();
428
429        let tensor = B::float_from_data(TensorData::from([-1.8f32, -1.0, 0.0, 0.5]), &device);
430        let scheme =
431            QuantizationScheme::PerTensor(QuantizationMode::Symmetric, QuantizationType::QInt8);
432        let qparams = QuantizationParametersPrimitive {
433            scale: B::float_from_data(TensorData::from([scale]), &device),
434            offset: None,
435        };
436        let qtensor: NdArrayQTensor<i8> = B::quantize(tensor, &scheme, qparams);
437
438        assert_eq!(qtensor.scheme(), &scheme);
439        assert_eq!(
440            qtensor.strategy(),
441            QuantizationStrategy::PerTensorSymmetricInt8(SymmetricQuantization::init(scale))
442        );
443    }
444}