burn_ndarray/ops/
int_tensor.rs

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