burn_ndarray/
tensor.rs

1use core::mem;
2
3use burn_tensor::{
4    DType, Element, Shape, TensorData, TensorMetadata,
5    quantization::{
6        QParams, QTensorPrimitive, QuantInputType, QuantLevel, QuantMode, QuantScheme,
7        QuantizationStrategy, 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                        if vec.len() > shape.num_elements() {
212                            vec.drain(shape.num_elements()..vec.len());
213                        }
214                        vec
215                    }
216                    Err(array) => array.into_iter().collect(),
217                }
218            } else {
219                self.array.into_iter().collect()
220            };
221
222            TensorData::new(vec, shape)
223        }
224
225        pub(crate) fn is_contiguous(&self) -> bool {
226            let shape = self.array.shape();
227            let mut strides = Vec::with_capacity(self.array.strides().len());
228
229            for &stride in self.array.strides() {
230                if stride <= 0 {
231                    return false;
232                }
233                strides.push(stride as usize);
234            }
235            is_contiguous(shape, &strides)
236        }
237    }
238}
239
240/// Converts a slice of usize to a typed dimension.
241#[macro_export(local_inner_macros)]
242macro_rules! to_typed_dims {
243    (
244        $n:expr,
245        $dims:expr,
246        justdim
247    ) => {{
248        let mut dims = [0; $n];
249        for i in 0..$n {
250            dims[i] = $dims[i];
251        }
252        let dim: Dim<[usize; $n]> = Dim(dims);
253        dim
254    }};
255}
256
257/// Reshapes an array into a tensor.
258#[macro_export(local_inner_macros)]
259macro_rules! reshape {
260    (
261        ty $ty:ty,
262        n $n:expr,
263        shape $shape:expr,
264        array $array:expr
265    ) => {{
266        let dim = $crate::to_typed_dims!($n, $shape.dims, justdim);
267        let array: ndarray::ArcArray<$ty, Dim<[usize; $n]>> = match $array.is_standard_layout() {
268            true => {
269                match $array.to_shape(dim) {
270                    Ok(val) => val.into_shared(),
271                    Err(err) => {
272                        core::panic!("Shape should be compatible shape={dim:?}: {err:?}");
273                    }
274                }
275            },
276            false => $array.to_shape(dim).unwrap().as_standard_layout().into_shared(),
277        };
278        let array = array.into_dyn();
279
280        NdArrayTensor::new(array)
281    }};
282    (
283        ty $ty:ty,
284        shape $shape:expr,
285        array $array:expr,
286        d $D:expr
287    ) => {{
288        match $D {
289            1 => reshape!(ty $ty, n 1, shape $shape, array $array),
290            2 => reshape!(ty $ty, n 2, shape $shape, array $array),
291            3 => reshape!(ty $ty, n 3, shape $shape, array $array),
292            4 => reshape!(ty $ty, n 4, shape $shape, array $array),
293            5 => reshape!(ty $ty, n 5, shape $shape, array $array),
294            6 => reshape!(ty $ty, n 6, shape $shape, array $array),
295            _ => core::panic!("NdArray supports arrays up to 6 dimensions, received: {}", $D),
296        }
297    }};
298}
299
300impl<E> NdArrayTensor<E>
301where
302    E: Element,
303{
304    /// Create a new [ndarray tensor](NdArrayTensor) from [data](TensorData).
305    pub fn from_data(mut data: TensorData) -> NdArrayTensor<E> {
306        let shape = mem::take(&mut data.shape);
307
308        let array = match data.into_vec::<E>() {
309            // Safety: TensorData checks shape validity on creation, so we don't need to repeat that check here
310            Ok(vec) => unsafe { ArrayD::from_shape_vec_unchecked(shape, vec) }.into_shared(),
311            Err(err) => panic!("Data should have the same element type as the tensor {err:?}"),
312        };
313
314        NdArrayTensor::new(array)
315    }
316}
317
318/// A quantized tensor for the ndarray backend.
319#[derive(Clone, Debug)]
320pub struct NdArrayQTensor<Q: QuantElement> {
321    /// The quantized tensor.
322    pub qtensor: NdArrayTensor<Q>,
323    /// The quantization scheme.
324    pub scheme: QuantScheme,
325    /// The quantization parameters.
326    pub qparams: Vec<QParams<f32, Q>>,
327}
328
329impl<Q: QuantElement> NdArrayQTensor<Q> {
330    /// Returns the quantization strategy, including quantization parameters, for the given tensor.
331    pub fn strategy(&self) -> QuantizationStrategy {
332        match self.scheme {
333            QuantScheme {
334                level: QuantLevel::Tensor,
335                mode: QuantMode::Symmetric,
336                q_type: QuantInputType::QInt8,
337                ..
338            } => QuantizationStrategy::PerTensorSymmetricInt8(SymmetricQuantization::init(
339                self.qparams[0].scale,
340            )),
341        }
342    }
343}
344
345impl<Q: QuantElement> QTensorPrimitive for NdArrayQTensor<Q> {
346    fn scheme(&self) -> &QuantScheme {
347        &self.scheme
348    }
349}
350
351impl<Q: QuantElement> TensorMetadata for NdArrayQTensor<Q> {
352    fn dtype(&self) -> DType {
353        DType::QFloat(self.scheme)
354    }
355
356    fn shape(&self) -> Shape {
357        self.qtensor.shape()
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use crate::NdArray;
364
365    use super::*;
366    use burn_common::rand::get_seeded_rng;
367    use burn_tensor::{
368        Distribution,
369        ops::{FloatTensorOps, QTensorOps},
370        quantization::QuantizationParametersPrimitive,
371    };
372
373    #[test]
374    fn should_support_into_and_from_data_1d() {
375        let data_expected = TensorData::random::<f32, _, _>(
376            Shape::new([3]),
377            Distribution::Default,
378            &mut get_seeded_rng(),
379        );
380        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
381
382        let data_actual = tensor.into_data();
383
384        assert_eq!(data_expected, data_actual);
385    }
386
387    #[test]
388    fn should_support_into_and_from_data_2d() {
389        let data_expected = TensorData::random::<f32, _, _>(
390            Shape::new([2, 3]),
391            Distribution::Default,
392            &mut get_seeded_rng(),
393        );
394        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
395
396        let data_actual = tensor.into_data();
397
398        assert_eq!(data_expected, data_actual);
399    }
400
401    #[test]
402    fn should_support_into_and_from_data_3d() {
403        let data_expected = TensorData::random::<f32, _, _>(
404            Shape::new([2, 3, 4]),
405            Distribution::Default,
406            &mut get_seeded_rng(),
407        );
408        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
409
410        let data_actual = tensor.into_data();
411
412        assert_eq!(data_expected, data_actual);
413    }
414
415    #[test]
416    fn should_support_into_and_from_data_4d() {
417        let data_expected = TensorData::random::<f32, _, _>(
418            Shape::new([2, 3, 4, 2]),
419            Distribution::Default,
420            &mut get_seeded_rng(),
421        );
422        let tensor = NdArrayTensor::<f32>::from_data(data_expected.clone());
423
424        let data_actual = tensor.into_data();
425
426        assert_eq!(data_expected, data_actual);
427    }
428
429    #[test]
430    fn should_support_qtensor_strategy() {
431        type B = NdArray<f32, i64, i8>;
432        let scale: f32 = 0.009_019_608;
433        let device = Default::default();
434
435        let tensor = B::float_from_data(TensorData::from([-1.8f32, -1.0, 0.0, 0.5]), &device);
436        let scheme = QuantScheme::default();
437        let qparams = QuantizationParametersPrimitive {
438            scale: B::float_from_data(TensorData::from([scale]), &device),
439            offset: None,
440        };
441        let qtensor: NdArrayQTensor<i8> = B::quantize(tensor, &scheme, qparams);
442
443        assert_eq!(qtensor.scheme(), &scheme);
444        assert_eq!(
445            qtensor.strategy(),
446            QuantizationStrategy::PerTensorSymmetricInt8(SymmetricQuantization::init(scale))
447        );
448    }
449}