1use 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
12use 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
20use 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 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 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 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 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 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(
283 dim: usize,
284 tensor: NdArrayTensor,
285 indices: NdArrayTensor,
286 value: NdArrayTensor,
287 update: burn_backend::tensor::IndexingUpdateOp,
288 ) -> NdArrayTensor {
289 match update {
290 burn_backend::tensor::IndexingUpdateOp::Add => {
291 Self::int_scatter_add(dim, tensor, indices, value)
292 }
293 burn_backend::tensor::IndexingUpdateOp::Assign => {
294 execute_with_int_dtype!((tensor, value), I, |tensor, value| -> NdArrayTensor {
295 execute_with_int_dtype!(indices, |idx_array| NdArrayOps::<I>::scatter_assign(
296 dim, tensor, idx_array, value
297 ))
298 })
299 }
300 other => unimplemented!("int_scatter with {other:?} update is not implemented"),
301 }
302 }
303
304 fn int_scatter_nd(
305 data: NdArrayTensor,
306 indices: NdArrayTensor,
307 values: NdArrayTensor,
308 reduction: burn_backend::tensor::IndexingUpdateOp,
309 ) -> NdArrayTensor {
310 execute_with_int_dtype!((data, values), I, |data, values| -> NdArrayTensor {
311 execute_with_int_dtype!(indices, |idx_array| NdArrayOps::<I>::scatter_nd(
312 data, idx_array, values, reduction
313 ))
314 })
315 }
316
317 fn int_gather_nd(data: NdArrayTensor, indices: NdArrayTensor) -> NdArrayTensor {
318 execute_with_int_dtype!(data, E, |array| -> NdArrayTensor {
319 execute_with_int_dtype!(indices, |idx_array| NdArrayOps::gather_nd(array, idx_array))
320 })
321 }
322
323 fn int_select(tensor: NdArrayTensor, dim: usize, indices: NdArrayTensor) -> NdArrayTensor {
324 execute_with_int_dtype!(tensor, E, |array| -> NdArrayTensor {
325 execute_with_int_dtype!(indices, |idx_array| NdArrayMathOps::select(
326 array, dim, idx_array
327 ))
328 })
329 }
330
331 fn int_select_add(
332 tensor: NdArrayTensor,
333 dim: usize,
334 indices: NdArrayTensor,
335 value: NdArrayTensor,
336 ) -> NdArrayTensor {
337 execute_with_int_dtype!((tensor, value), I, |tensor, value| -> NdArrayTensor {
338 execute_with_int_dtype!(indices, |idx_array| NdArrayMathOps::<I>::select_assign(
339 tensor, dim, idx_array, value
340 ))
341 })
342 }
343
344 fn int_select_assign(
345 tensor: NdArrayTensor,
346 dim: usize,
347 indices: NdArrayTensor,
348 value: NdArrayTensor,
349 update: burn_backend::tensor::IndexingUpdateOp,
350 ) -> NdArrayTensor {
351 match update {
352 burn_backend::tensor::IndexingUpdateOp::Add => {
353 Self::int_select_add(tensor, dim, indices, value)
354 }
355 burn_backend::tensor::IndexingUpdateOp::Assign => {
356 execute_with_int_dtype!((tensor, value), I, |tensor, value| -> NdArrayTensor {
357 execute_with_int_dtype!(indices, |idx_array| {
358 NdArrayMathOps::<I>::select_assign_replace(tensor, dim, idx_array, value)
359 })
360 })
361 }
362 other => unimplemented!("int_select_assign with {other:?} update is not implemented"),
363 }
364 }
365 fn int_argmax(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
366 execute_with_int_dtype!(tensor, E, |array: SharedArray<E>| {
368 NdArrayMathOps::argmax_view::<E>(array.view(), dim)
369 })
370 }
371
372 fn int_argmin(tensor: NdArrayTensor, dim: usize) -> NdArrayTensor {
373 execute_with_int_dtype!(tensor, E, |array: SharedArray<E>| {
375 NdArrayMathOps::argmin_view::<E>(array.view(), dim)
376 })
377 }
378
379 fn int_clamp_min(tensor: NdArrayTensor, min: Scalar) -> NdArrayTensor {
380 execute_with_int_dtype!(tensor, |array| NdArrayMathOps::clamp_min(array, min.elem()))
381 }
382
383 fn int_clamp_max(tensor: NdArrayTensor, max: Scalar) -> NdArrayTensor {
384 execute_with_int_dtype!(tensor, |array| NdArrayMathOps::clamp_max(array, max.elem()))
385 }
386
387 fn int_clamp(tensor: NdArrayTensor, min: Scalar, max: Scalar) -> NdArrayTensor {
388 execute_with_int_dtype!(tensor, |array| NdArrayMathOps::clamp(
389 array,
390 min.elem(),
391 max.elem()
392 ))
393 }
394
395 fn int_abs(tensor: NdArrayTensor) -> NdArrayTensor {
396 match tensor.dtype() {
397 DType::I64 | DType::I32 | DType::I16 | DType::I8 => {
398 execute_with_dtype!(tensor, I, NdArrayMathOps::abs, [
399 I64 => i64, I32 => i32, I16 => i16, I8 => i8
400 ])
401 }
402 DType::U64 | DType::U32 | DType::U16 | DType::U8 => tensor,
404 other => panic!("Unsupported dtype: {other:?}"),
405 }
406 }
407
408 fn int_into_float(tensor: NdArrayTensor, out_dtype: FloatDType) -> FloatTensor<Self> {
409 execute_with_float_out_dtype!(out_dtype, F, {
410 execute_with_int_dtype!(tensor, IntElem, |array: SharedArray<IntElem>| {
411 array.mapv(|a: IntElem| a.elem::<F>()).into_shared()
412 })
413 })
414 }
415
416 fn int_swap_dims(tensor: NdArrayTensor, dim1: usize, dim2: usize) -> NdArrayTensor {
417 execute_with_int_dtype!(tensor, |array| NdArrayOps::swap_dims(array, dim1, dim2))
418 }
419
420 fn int_random(
421 shape: Shape,
422 distribution: Distribution,
423 device: &NdArrayDevice,
424 dtype: IntDType,
425 ) -> NdArrayTensor {
426 let mut seed = SEED.lock();
427 let mut rng = seed.take().unwrap_or_else(get_seeded_rng);
428
429 let effective_distribution = if distribution == Distribution::Default {
430 Distribution::Uniform(0.0, 255.0) } else {
432 distribution
433 };
434
435 let tensor = execute_with_int_out_dtype!(
436 dtype,
437 I,
438 Self::int_from_data(
439 TensorData::random::<I, _, _>(shape, effective_distribution, &mut rng),
440 device,
441 )
442 );
443 *seed = Some(rng);
444 tensor
445 }
446
447 fn int_powi(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
448 execute_with_int_dtype!((lhs, rhs), I, |lhs, rhs| NdArrayMathOps::elementwise_op(
449 lhs,
450 rhs,
451 |a: &I, b: &I| { (a.elem::<i64>().pow(b.elem::<u32>())).elem() }
452 ))
453 }
454
455 fn int_permute(tensor: NdArrayTensor, axes: &[usize]) -> NdArrayTensor {
456 execute_with_int_dtype!(tensor, |array| NdArrayOps::permute(array, axes))
457 }
458
459 fn int_flip(tensor: NdArrayTensor, axes: &[usize]) -> NdArrayTensor {
460 execute_with_int_dtype!(tensor, |array| NdArrayOps::flip(array, axes))
461 }
462
463 fn int_sign(tensor: NdArrayTensor) -> NdArrayTensor {
464 match tensor.dtype() {
465 DType::I64 | DType::I32 | DType::I16 | DType::I8 => {
466 execute_with_dtype!(tensor, I, NdArrayMathOps::sign_op, [
467 I64 => i64, I32 => i32, I16 => i16, I8 => i8
468 ])
469 }
470 DType::U64 | DType::U32 | DType::U16 | DType::U8 => {
471 Self::int_greater_elem(tensor, 0.into(), BoolDType::Native)
472 }
473 other => panic!("Unsupported dtype: {other:?}"),
474 }
475 }
476
477 fn int_expand(tensor: NdArrayTensor, shape: Shape) -> NdArrayTensor {
478 execute_with_int_dtype!(tensor, |array| NdArrayOps::expand(array, shape))
479 }
480
481 fn bitwise_and(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
482 execute_with_int_dtype!((lhs, rhs), NdArrayBitOps::bitand)
483 }
484
485 fn bitwise_and_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
486 execute_with_int_dtype!(lhs, |array| NdArrayBitOps::bitand_scalar(array, rhs.elem()))
487 }
488
489 fn bitwise_or(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
490 execute_with_int_dtype!((lhs, rhs), NdArrayBitOps::bitor)
491 }
492
493 fn bitwise_or_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
494 execute_with_int_dtype!(lhs, |array| NdArrayBitOps::bitor_scalar(array, rhs.elem()))
495 }
496
497 fn bitwise_xor(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
498 execute_with_int_dtype!((lhs, rhs), NdArrayBitOps::bitxor)
499 }
500
501 fn bitwise_xor_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
502 execute_with_int_dtype!(lhs, |array| NdArrayBitOps::bitxor_scalar(array, rhs.elem()))
503 }
504
505 fn bitwise_not(tensor: NdArrayTensor) -> NdArrayTensor {
506 execute_with_int_dtype!(tensor, NdArrayBitOps::bitnot)
507 }
508
509 fn bitwise_left_shift(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
510 execute_with_int_dtype!((lhs, rhs), I, |lhs, rhs| {
511 NdArrayMathOps::elementwise_op(lhs, rhs, |a: &I, b: &I| {
512 (a.elem::<i64>() << (b.elem::<u32>())).elem()
513 })
514 })
515 }
516
517 fn bitwise_left_shift_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
518 execute_with_int_dtype!(lhs, I, |array| {
519 NdArrayMathOps::elementwise_op_scalar(array, |a: I| {
520 (a.elem::<i64>() << rhs.elem::<u32>()).elem()
521 })
522 })
523 }
524
525 fn bitwise_right_shift(lhs: NdArrayTensor, rhs: NdArrayTensor) -> NdArrayTensor {
526 execute_with_int_dtype!((lhs, rhs), I, |lhs, rhs| {
527 NdArrayMathOps::elementwise_op(lhs, rhs, |a: &I, b: &I| {
528 (a.elem::<i64>() >> (b.elem::<u32>())).elem()
529 })
530 })
531 }
532
533 fn bitwise_right_shift_scalar(lhs: NdArrayTensor, rhs: Scalar) -> NdArrayTensor {
534 execute_with_int_dtype!(lhs, I, |array| {
535 NdArrayMathOps::elementwise_op_scalar(array, |a: I| {
536 (a.elem::<i64>() >> rhs.elem::<u32>()).elem()
537 })
538 })
539 }
540
541 fn int_cast(tensor: IntTensor<Self>, dtype: IntDType) -> IntTensor<Self> {
542 execute_with_int_dtype!(tensor, |array| cast_to_dtype(array, dtype.into()))
543 }
544
545 fn int_unfold(
546 tensor: IntTensor<Self>,
547 dim: usize,
548 size: usize,
549 step: usize,
550 ) -> IntTensor<Self> {
551 execute_with_int_dtype!(tensor, |array| NdArrayOps::unfold(array, dim, size, step))
552 }
553
554 fn int_powi_scalar_impl(lhs: IntTensor<Self>, rhs: Scalar) -> IntTensor<Self> {
555 execute_with_int_dtype!(lhs, I, |array| {
556 NdArrayMathOps::elementwise_op_scalar(array, |a: I| a.powi_elem(rhs.elem()))
557 })
558 }
559}