Skip to main content

burn_ndarray/ops/
int_tensor.rs

1// Language
2use crate::rand::get_seeded_rng;
3use alloc::vec::Vec;
4use burn_backend::backend::ExecutionError;
5use burn_backend::ops::IntTensorOps;
6use burn_backend::tensor::{FloatTensor, IntTensor};
7use burn_backend::{Distribution, IntDType, Scalar, TensorMetadata};
8
9use burn_backend::ElementConversion;
10use burn_std::{BoolDType, FloatDType};
11
12// Current crate
13use crate::SharedArray;
14use crate::execute_with_int_dtype;
15use crate::ops::matmul::matmul;
16use crate::{ExpElement, NdArrayDevice, SEED, execute_with_int_out_dtype, slice};
17use crate::{NdArray, cast_to_dtype, execute_with_dtype, tensor::NdArrayTensor};
18use crate::{cat_with_dtype, execute_with_float_out_dtype};
19
20// Workspace crates
21use super::{NdArrayBitOps, NdArrayMathOps, NdArrayOps};
22use burn_backend::{DType, Shape, TensorData};
23
24impl IntTensorOps<Self> for NdArray {
25    fn int_from_data(data: TensorData, _device: &NdArrayDevice) -> NdArrayTensor {
26        if data.dtype.is_int() || data.dtype.is_uint() {
27            NdArrayTensor::from_data(data)
28        } else {
29            unimplemented!("Unsupported dtype for `int_from_data`: {:?}", data.dtype)
30        }
31    }
32
33    async fn int_into_data(tensor: NdArrayTensor) -> Result<TensorData, ExecutionError> {
34        Ok(tensor.into_data())
35    }
36
37    fn int_to_device(tensor: NdArrayTensor, _device: &NdArrayDevice) -> NdArrayTensor {
38        tensor
39    }
40
41    fn int_reshape(tensor: NdArrayTensor, shape: Shape) -> NdArrayTensor {
42        execute_with_int_dtype!(tensor, |array| NdArrayOps::reshape(array, shape))
43    }
44
45    fn int_slice(tensor: NdArrayTensor, slices: &[burn_backend::Slice]) -> NdArrayTensor {
46        slice!(tensor, slices)
47    }
48
49    fn int_empty(shape: Shape, device: &NdArrayDevice, dtype: IntDType) -> NdArrayTensor {
50        Self::int_zeros(shape, device, dtype)
51    }
52
53    fn int_matmul(lhs: IntTensor<Self>, rhs: IntTensor<Self>) -> IntTensor<Self> {
54        execute_with_int_dtype!((lhs, rhs), matmul)
55    }
56
57    fn int_mask_where(
58        tensor: NdArrayTensor,
59        mask: NdArrayTensor,
60        source: NdArrayTensor,
61    ) -> NdArrayTensor {
62        execute_with_int_dtype!((tensor, source), |tensor, source| {
63            NdArrayOps::mask_where(tensor, mask.bool(), source)
64        })
65    }
66
67    fn int_mask_fill(tensor: NdArrayTensor, mask: NdArrayTensor, value: Scalar) -> NdArrayTensor {
68        execute_with_int_dtype!(tensor, |array| NdArrayOps::mask_fill(
69            array,
70            mask.bool(),
71            value.elem()
72        ))
73    }
74
75    fn int_slice_assign(
76        tensor: NdArrayTensor,
77        slices: &[burn_backend::Slice],
78        value: NdArrayTensor,
79    ) -> NdArrayTensor {
80        execute_with_int_dtype!((tensor, value), |tensor, value| NdArrayOps::slice_assign(
81            tensor, slices, value
82        ))
83    }
84
85    fn int_cat(tensors: Vec<NdArrayTensor>, dim: usize) -> NdArrayTensor {
86        cat_with_dtype!(tensors, dim, [I64, I32, I16, I8, U64, U32, U16, U8])
87    }
88
89    fn int_equal(lhs: NdArrayTensor, rhs: NdArrayTensor, _out_dtype: BoolDType) -> NdArrayTensor {
90        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::equal)
91    }
92
93    fn int_equal_elem(lhs: NdArrayTensor, rhs: Scalar, _out_dtype: BoolDType) -> NdArrayTensor {
94        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::equal_elem(array, rhs.elem()))
95    }
96
97    fn int_greater(lhs: NdArrayTensor, rhs: NdArrayTensor, _out_dtype: BoolDType) -> NdArrayTensor {
98        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::greater)
99    }
100
101    fn int_greater_elem(lhs: NdArrayTensor, rhs: Scalar, _out_dtype: BoolDType) -> NdArrayTensor {
102        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::greater_elem(array, rhs.elem()))
103    }
104
105    fn int_greater_equal(
106        lhs: NdArrayTensor,
107        rhs: NdArrayTensor,
108        _out_dtype: BoolDType,
109    ) -> NdArrayTensor {
110        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::greater_equal)
111    }
112
113    fn int_greater_equal_elem(
114        lhs: NdArrayTensor,
115        rhs: Scalar,
116        _out_dtype: BoolDType,
117    ) -> NdArrayTensor {
118        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::greater_equal_elem(
119            array,
120            rhs.elem()
121        ))
122    }
123
124    fn int_lower(lhs: NdArrayTensor, rhs: NdArrayTensor, _out_dtype: BoolDType) -> NdArrayTensor {
125        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::lower)
126    }
127
128    fn int_lower_elem(lhs: NdArrayTensor, rhs: Scalar, _out_dtype: BoolDType) -> NdArrayTensor {
129        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::lower_elem(array, rhs.elem()))
130    }
131
132    fn int_lower_equal(
133        lhs: NdArrayTensor,
134        rhs: NdArrayTensor,
135        _out_dtype: BoolDType,
136    ) -> NdArrayTensor {
137        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::lower_equal)
138    }
139
140    fn int_lower_equal_elem(
141        lhs: NdArrayTensor,
142        rhs: Scalar,
143        _out_dtype: BoolDType,
144    ) -> NdArrayTensor {
145        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::lower_equal_elem(
146            array,
147            rhs.elem()
148        ))
149    }
150
151    fn int_add(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
152        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::add)
153    }
154
155    fn int_add_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
156        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::add_scalar(array, rhs.elem()))
157    }
158
159    fn int_sub(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
160        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::sub)
161    }
162
163    fn int_sub_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
164        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::sub_scalar(array, rhs.elem()))
165    }
166
167    fn int_mul(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
168        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::mul)
169    }
170
171    fn int_mul_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
172        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::mul_scalar(array, rhs.elem()))
173    }
174
175    fn int_div(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
176        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::div)
177    }
178
179    fn int_div_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
180        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::div_scalar(array, rhs.elem()))
181    }
182
183    fn int_remainder(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
184        execute_with_int_dtype!((lhs, rhs), NdArrayMathOps::remainder)
185    }
186
187    fn int_remainder_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
188        execute_with_int_dtype!(lhs, |array| NdArrayMathOps::remainder_scalar(
189            array,
190            rhs.elem()
191        ))
192    }
193
194    fn int_sum(tensor: NdArrayTensor) -> NdArrayTensor {
195        // Use view() for zero-copy on borrowed storage
196        execute_with_int_dtype!(tensor, E, |array: SharedArray<E>| NdArrayMathOps::sum_view(
197            array.view()
198        ))
199    }
200
201    fn int_sum_dim(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
202        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::sum_dim(array, dim))
203    }
204
205    fn int_prod(tensor: NdArrayTensor) -> NdArrayTensor {
206        // Use view() for zero-copy on borrowed storage
207        execute_with_int_dtype!(
208            tensor,
209            E,
210            |array: SharedArray<E>| NdArrayMathOps::prod_view(array.view())
211        )
212    }
213
214    fn int_prod_dim(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
215        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::prod_dim(array, dim))
216    }
217
218    fn int_mean(tensor: NdArrayTensor) -> NdArrayTensor {
219        // Use view() for zero-copy on borrowed storage
220        execute_with_int_dtype!(
221            tensor,
222            E,
223            |array: SharedArray<E>| NdArrayMathOps::mean_view(array.view())
224        )
225    }
226
227    fn int_mean_dim(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
228        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::mean_dim(array, dim))
229    }
230
231    fn int_max(tensor: NdArrayTensor) -> NdArrayTensor {
232        // Use view() for zero-copy on borrowed storage
233        execute_with_int_dtype!(tensor, E, |array: SharedArray<E>| NdArrayMathOps::max_view(
234            array.view()
235        ))
236    }
237
238    fn int_min(tensor: NdArrayTensor) -> NdArrayTensor {
239        // Use view() for zero-copy on borrowed storage
240        execute_with_int_dtype!(tensor, E, |array: SharedArray<E>| NdArrayMathOps::min_view(
241            array.view()
242        ))
243    }
244
245    fn int_cumsum(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
246        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::cumsum(array, dim))
247    }
248
249    fn int_cumprod(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
250        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::cumprod(array, dim))
251    }
252
253    fn int_cummin(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
254        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::cummin(array, dim))
255    }
256
257    fn int_cummax(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
258        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::cummax(array, dim))
259    }
260
261    fn int_gather(dim: usize, tensor: NdArrayTensor, indices: NdArrayTensor) -> NdArrayTensor {
262        execute_with_int_dtype!(tensor, E, |array| -> NdArrayTensor {
263            execute_with_int_dtype!(indices, |idx_array| NdArrayOps::gather(
264                dim, array, idx_array
265            ))
266        })
267    }
268
269    fn int_scatter_add(
270        dim: usize,
271        tensor: NdArrayTensor,
272        indices: NdArrayTensor,
273        value: NdArrayTensor,
274    ) -> NdArrayTensor {
275        execute_with_int_dtype!((tensor, value), I, |tensor, value| -> NdArrayTensor {
276            execute_with_int_dtype!(indices, |idx_array| NdArrayOps::<I>::scatter(
277                dim, tensor, idx_array, value
278            ))
279        })
280    }
281
282    fn int_scatter_nd(
283        data: NdArrayTensor,
284        indices: NdArrayTensor,
285        values: NdArrayTensor,
286        reduction: burn_backend::tensor::IndexingUpdateOp,
287    ) -> NdArrayTensor {
288        execute_with_int_dtype!((data, values), I, |data, values| -> NdArrayTensor {
289            execute_with_int_dtype!(indices, |idx_array| NdArrayOps::<I>::scatter_nd(
290                data, idx_array, values, reduction
291            ))
292        })
293    }
294
295    fn int_gather_nd(data: NdArrayTensor, indices: NdArrayTensor) -> NdArrayTensor {
296        execute_with_int_dtype!(data, E, |array| -> NdArrayTensor {
297            execute_with_int_dtype!(indices, |idx_array| NdArrayOps::gather_nd(array, idx_array))
298        })
299    }
300
301    fn int_select(tensor: NdArrayTensor, dim: usize, indices: NdArrayTensor) -> NdArrayTensor {
302        execute_with_int_dtype!(tensor, E, |array| -> NdArrayTensor {
303            execute_with_int_dtype!(indices, |idx_array| NdArrayMathOps::select(
304                array, dim, idx_array
305            ))
306        })
307    }
308
309    fn int_select_add(
310        tensor: NdArrayTensor,
311        dim: usize,
312        indices: NdArrayTensor,
313        value: NdArrayTensor,
314    ) -> NdArrayTensor {
315        execute_with_int_dtype!((tensor, value), I, |tensor, value| -> NdArrayTensor {
316            execute_with_int_dtype!(indices, |idx_array| NdArrayMathOps::<I>::select_assign(
317                tensor, dim, idx_array, value
318            ))
319        })
320    }
321    fn int_argmax(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
322        // Use view() for zero-copy on borrowed storage
323        execute_with_int_dtype!(tensor, E, |array: SharedArray<E>| {
324            NdArrayMathOps::argmax_view::<E>(array.view(), dim)
325        })
326    }
327
328    fn int_argmin(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
329        // Use view() for zero-copy on borrowed storage
330        execute_with_int_dtype!(tensor, E, |array: SharedArray<E>| {
331            NdArrayMathOps::argmin_view::<E>(array.view(), dim)
332        })
333    }
334
335    fn int_clamp_min(tensor: NdArrayTensor, min: Scalar) -> NdArrayTensor {
336        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::clamp_min(array, min.elem()))
337    }
338
339    fn int_clamp_max(tensor: NdArrayTensor, max: Scalar) -> NdArrayTensor {
340        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::clamp_max(array, max.elem()))
341    }
342
343    fn int_clamp(tensor: NdArrayTensor, min: Scalar, max: Scalar) -> NdArrayTensor {
344        execute_with_int_dtype!(tensor, |array| NdArrayMathOps::clamp(
345            array,
346            min.elem(),
347            max.elem()
348        ))
349    }
350
351    fn int_abs(tensor: NdArrayTensor) -> NdArrayTensor {
352        match tensor.dtype() {
353            DType::I64 | DType::I32 | DType::I16 | DType::I8 => {
354                execute_with_dtype!(tensor, I, NdArrayMathOps::abs, [
355                    I64 => i64, I32 => i32, I16 => i16, I8 => i8
356                ])
357            }
358            // Already unsigned
359            DType::U64 | DType::U32 | DType::U16 | DType::U8 => tensor,
360            other => panic!("Unsupported dtype: {other:?}"),
361        }
362    }
363
364    fn int_into_float(tensor: NdArrayTensor, out_dtype: FloatDType) -> FloatTensor<Self> {
365        execute_with_float_out_dtype!(out_dtype, F, {
366            execute_with_int_dtype!(tensor, IntElem, |array: SharedArray<IntElem>| {
367                array.mapv(|a: IntElem| a.elem::<F>()).into_shared()
368            })
369        })
370    }
371
372    fn int_swap_dims(tensor: NdArrayTensor, dim1: usize, dim2: usize) -> NdArrayTensor {
373        execute_with_int_dtype!(tensor, |array| NdArrayOps::swap_dims(array, dim1, dim2))
374    }
375
376    fn int_random(
377        shape: Shape,
378        distribution: Distribution,
379        device: &NdArrayDevice,
380        dtype: IntDType,
381    ) -> NdArrayTensor {
382        let mut seed = SEED.lock().unwrap();
383        let mut rng = seed.take().unwrap_or_else(get_seeded_rng);
384
385        let effective_distribution = if distribution == Distribution::Default {
386            Distribution::Uniform(0.0, 255.0) // Assuming UniformInt is the integer variant
387        } else {
388            distribution
389        };
390
391        let tensor = execute_with_int_out_dtype!(
392            dtype,
393            I,
394            Self::int_from_data(
395                TensorData::random::<I, _, _>(shape, effective_distribution, &mut rng),
396                device,
397            )
398        );
399        *seed = Some(rng);
400        tensor
401    }
402
403    fn int_powi(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
404        execute_with_int_dtype!((lhs, rhs), I, |lhs, rhs| NdArrayMathOps::elementwise_op(
405            lhs,
406            rhs,
407            |a: &I, b: &I| { (a.elem::<i64>().pow(b.elem::<u32>())).elem() }
408        ))
409    }
410
411    fn int_permute(tensor: NdArrayTensor, axes: &[usize]) -> NdArrayTensor {
412        execute_with_int_dtype!(tensor, |array| NdArrayOps::permute(array, axes))
413    }
414
415    fn int_flip(tensor: NdArrayTensor, axes: &[usize]) -> NdArrayTensor {
416        execute_with_int_dtype!(tensor, |array| NdArrayOps::flip(array, axes))
417    }
418
419    fn int_sign(tensor: NdArrayTensor) -> NdArrayTensor {
420        match tensor.dtype() {
421            DType::I64 | DType::I32 | DType::I16 | DType::I8 => {
422                execute_with_dtype!(tensor, I, NdArrayMathOps::sign_op, [
423                    I64 => i64, I32 => i32, I16 => i16, I8 => i8
424                ])
425            }
426            DType::U64 | DType::U32 | DType::U16 | DType::U8 => {
427                Self::int_greater_elem(tensor, 0.into(), BoolDType::Native)
428            }
429            other => panic!("Unsupported dtype: {other:?}"),
430        }
431    }
432
433    fn int_expand(tensor: NdArrayTensor, shape: Shape) -> NdArrayTensor {
434        execute_with_int_dtype!(tensor, |array| NdArrayOps::expand(array, shape))
435    }
436
437    fn bitwise_and(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
438        execute_with_int_dtype!((lhs, rhs), NdArrayBitOps::bitand)
439    }
440
441    fn bitwise_and_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
442        execute_with_int_dtype!(lhs, |array| NdArrayBitOps::bitand_scalar(array, rhs.elem()))
443    }
444
445    fn bitwise_or(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
446        execute_with_int_dtype!((lhs, rhs), NdArrayBitOps::bitor)
447    }
448
449    fn bitwise_or_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
450        execute_with_int_dtype!(lhs, |array| NdArrayBitOps::bitor_scalar(array, rhs.elem()))
451    }
452
453    fn bitwise_xor(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
454        execute_with_int_dtype!((lhs, rhs), NdArrayBitOps::bitxor)
455    }
456
457    fn bitwise_xor_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
458        execute_with_int_dtype!(lhs, |array| NdArrayBitOps::bitxor_scalar(array, rhs.elem()))
459    }
460
461    fn bitwise_not(tensor: NdArrayTensor) -> NdArrayTensor {
462        execute_with_int_dtype!(tensor, NdArrayBitOps::bitnot)
463    }
464
465    fn bitwise_left_shift(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
466        execute_with_int_dtype!((lhs, rhs), I, |lhs, rhs| {
467            NdArrayMathOps::elementwise_op(lhs, rhs, |a: &I, b: &I| {
468                (a.elem::<i64>() << (b.elem::<u32>())).elem()
469            })
470        })
471    }
472
473    fn bitwise_left_shift_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
474        execute_with_int_dtype!(lhs, I, |array| {
475            NdArrayMathOps::elementwise_op_scalar(array, |a: I| {
476                (a.elem::<i64>() << rhs.elem::<u32>()).elem()
477            })
478        })
479    }
480
481    fn bitwise_right_shift(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
482        execute_with_int_dtype!((lhs, rhs), I, |lhs, rhs| {
483            NdArrayMathOps::elementwise_op(lhs, rhs, |a: &I, b: &I| {
484                (a.elem::<i64>() >> (b.elem::<u32>())).elem()
485            })
486        })
487    }
488
489    fn bitwise_right_shift_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
490        execute_with_int_dtype!(lhs, I, |array| {
491            NdArrayMathOps::elementwise_op_scalar(array, |a: I| {
492                (a.elem::<i64>() >> rhs.elem::<u32>()).elem()
493            })
494        })
495    }
496
497    fn int_cast(tensor: IntTensor<Self>, dtype: IntDType) -> IntTensor<Self> {
498        execute_with_int_dtype!(tensor, |array| cast_to_dtype(array, dtype.into()))
499    }
500
501    fn int_unfold(
502        tensor: IntTensor<Self>,
503        dim: usize,
504        size: usize,
505        step: usize,
506    ) -> IntTensor<Self> {
507        execute_with_int_dtype!(tensor, |array| NdArrayOps::unfold(array, dim, size, step))
508    }
509
510    fn int_powi_scalar_impl(lhs: IntTensor<Self>, rhs: Scalar) -> IntTensor<Self> {
511        execute_with_int_dtype!(lhs, I, |array| {
512            NdArrayMathOps::elementwise_op_scalar(array, |a: I| a.powi_elem(rhs.elem()))
513        })
514    }
515}