burn_tensor/tensor/api/base.rs
1#![allow(clippy::single_range_in_vec_init)]
2use crate::backend::ExecutionError;
3use crate::check::unwrap_shape_reshape;
4
5use burn_backend::Scalar;
6pub use burn_backend::tensor::BasicOps;
7
8use alloc::vec::Vec;
9
10use alloc::format;
11use alloc::string::String;
12use alloc::vec;
13
14use burn_std::{SliceOps, stub::RwLock};
15use core::iter::repeat;
16use core::{fmt::Debug, ops::Range};
17use serde::{Deserialize, Deserializer};
18
19use crate::{AsIndex, Slice, SliceArg, wrap_index};
20use crate::{
21 Bool, ElementConversion, Float, Int, Shape, TensorData, TensorKind, TensorMetadata,
22 backend::Backend, check,
23};
24use crate::{DType, Element};
25use crate::{IndexingUpdateOp, TensorCreationOptions};
26use crate::{cast::ToElement, check::TensorCheck};
27use serde::{Serialize, Serializer};
28
29/// A tensor with a given backend, shape and data type.
30///
31/// # Indexing
32/// Indexing a tensor can be done using [`slice`](Tensor::slice) for all tensor types
33/// or [`select`](Tensor::select) for numeric types.
34///
35/// ## Example
36///
37/// ```rust
38/// use burn_tensor::backend::Backend;
39/// use burn_tensor::Tensor;
40/// use burn_tensor::Int;
41///
42/// fn example<B: Backend>() {
43/// let device = Default::default();
44///
45/// let tensor = Tensor::<B, 2>::from_data(
46/// [
47/// [3.0, 4.9, 2.0],
48/// [2.0, 1.9, 3.0],
49/// [6.0, 1.5, 7.0],
50/// [3.0, 4.9, 9.0],
51/// ],
52/// &device,
53/// );
54///
55/// // Slice the tensor to get the second and third rows:
56/// // [[2.0, 1.9, 3.0], [6.0, 1.5, 7.0]]
57/// // The resulting tensor will have dimensions [2, 3].
58/// let slice = tensor.clone().slice([1..3]);
59/// println!("{slice}");
60///
61/// // Slice the tensor to get the first two rows and the first 2 columns:
62/// // [[3.0, 4.9], [2.0, 1.9]]
63/// // The resulting tensor will have dimensions [2, 2].
64/// let slice = tensor.clone().slice([0..2, 0..2]);
65/// println!("{slice}");
66///
67/// // Index the tensor along the dimension 1 to get the elements 0 and 2:
68/// // [[3.0, 2.0], [2.0, 3.0], [6.0, 7.0], [3.0, 9.0]]
69/// // The resulting tensor will have dimensions [4, 2]
70/// let indices = Tensor::<B, 1, Int>::from_data([0, 2], &device);
71/// let indexed = tensor.select(1, indices);
72/// println!("{indexed}");
73/// }
74/// ```
75#[derive(new, Clone, Debug)]
76pub struct Tensor<B, const D: usize, K = Float>
77where
78 B: Backend,
79 K: TensorKind<B>,
80{
81 pub(crate) primitive: K::Primitive,
82}
83
84impl<B, const D: usize, K, T> From<T> for Tensor<B, D, K>
85where
86 B: Backend,
87 K: BasicOps<B>,
88 T: Into<TensorData>,
89{
90 fn from(value: T) -> Self {
91 Tensor::from_data(value.into(), &Default::default())
92 }
93}
94
95impl<B, const D: usize, K> Tensor<B, D, K>
96where
97 B: Backend,
98 K: BasicOps<B>,
99 K::Elem: Element,
100{
101 /// Executes an operation on the tensor and modifies its value.
102 ///
103 /// # Notes
104 ///
105 /// This won't necessarily reuse the same tensor data/buffer, but it should if there is
106 /// no other reference pointing to the same tensor.
107 ///
108 /// Wrapping operations with inplace is not an optimization, it's mainly there if you
109 /// want to mutate a tensor by using owned operations. A plausible usage would be to
110 /// update the weights of a mutable model reference.
111 pub fn inplace<F: FnOnce(Self) -> Self>(&mut self, func: F) {
112 let mut tensor_owned = Tensor::empty([0; D], &self.device());
113 core::mem::swap(&mut tensor_owned, self);
114
115 let mut tensor_new = func(tensor_owned);
116 core::mem::swap(&mut tensor_new, self);
117 }
118
119 /// Converts the tensor into a primitive tensor.
120 pub fn into_primitive(self) -> K::Primitive {
121 self.primitive
122 }
123
124 /// Converts from a primitive tensor into a tensor.
125 pub fn from_primitive(tensor: K::Primitive) -> Self {
126 Self::new(tensor)
127 }
128
129 /// Returns the number of dimensions of the tensor.
130 pub fn rank(&self) -> usize {
131 self.primitive.rank()
132 }
133
134 /// Returns the tensor primitive data type.
135 ///
136 /// # Note
137 /// Some element types are encoded in different primitive types depending on the backend
138 /// (e.g., bool could be encoded as `u8` or `u32`).
139 pub fn dtype(&self) -> DType {
140 self.primitive.dtype()
141 }
142
143 /// Create an empty tensor of the given shape.
144 ///
145 /// # Arguments
146 ///
147 /// - `shape`: The shape of the tensor.
148 /// - `device`: The device where the tensor will be created.
149 ///
150 /// # Example
151 /// ```rust
152 /// use burn_tensor::backend::Backend;
153 /// use burn_tensor::Tensor;
154 ///
155 /// fn example<B: Backend>() {
156 /// let device = Default::default();
157 /// // Create an empty tensor with dimensions [2, 3, 4].
158 /// let tensor = Tensor::<B, 3>::empty([2, 3, 4], &device);
159 /// }
160 /// ```
161 pub fn empty<S: Into<Shape>>(shape: S, options: impl Into<TensorCreationOptions<B>>) -> Self {
162 let opt = options.into();
163 let shape = shape.into();
164 let dtype = opt.resolve_policy(K::Elem::dtype());
165 check!(TensorCheck::creation_ops::<D>("Empty", &shape));
166 Self::new(K::empty(shape, &opt.device, dtype))
167 }
168
169 /// Create a tensor of the given shape where each element is zero.
170 ///
171 /// # Example
172 ///
173 /// ```rust
174 /// use burn_tensor::backend::Backend;
175 /// use burn_tensor::{Tensor, Shape};
176 ///
177 /// fn example<B: Backend>() {
178 /// let device = B::Device::default();
179 /// let tensor = Tensor::<B, 2>::zeros(Shape::new([2, 3]), &device);
180 /// println!("{tensor}");
181 /// // [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
182 /// }
183 /// ```
184 pub fn zeros<S: Into<Shape>>(shape: S, options: impl Into<TensorCreationOptions<B>>) -> Self {
185 let opt = options.into();
186 let shape = shape.into();
187 let dtype = opt.resolve_policy(K::Elem::dtype());
188 check!(TensorCheck::creation_ops::<D>("Zeros", &shape));
189 Self::new(K::zeros(shape, &opt.device, dtype))
190 }
191
192 /// Returns a new tensor with the same shape, dtype, and device as the current tensor filled with zeros.
193 ///
194 /// # Example
195 ///
196 /// ```rust
197 /// use burn_tensor::backend::Backend;
198 /// use burn_tensor::{Tensor, Shape};
199 ///
200 /// fn example<B: Backend>() {
201 /// let device = B::Device::default();
202 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
203 /// let tensor = tensor.zeros_like();
204 /// println!("{tensor}");
205 /// // [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
206 /// }
207 /// ```
208 pub fn zeros_like(&self) -> Self {
209 Self::new(K::zeros(self.shape(), &self.device(), self.dtype()))
210 }
211
212 /// Create a tensor of the given shape where each element is one.
213 ///
214 /// # Example
215 ///
216 /// ```rust
217 /// use burn_tensor::backend::Backend;
218 /// use burn_tensor::{Tensor, Shape};
219 ///
220 /// fn example<B: Backend>() {
221 /// let device = B::Device::default();
222 /// let tensor = Tensor::<B, 2>::ones(Shape::new([2, 3]), &device);
223 /// println!("{tensor}");
224 /// // [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
225 /// }
226 /// ```
227 pub fn ones<S: Into<Shape>>(shape: S, options: impl Into<TensorCreationOptions<B>>) -> Self {
228 let opt = options.into();
229 let shape = shape.into();
230 let dtype = opt.resolve_policy(K::Elem::dtype());
231 check!(TensorCheck::creation_ops::<D>("Ones", &shape));
232 Self::new(K::ones(shape, &opt.device, dtype))
233 }
234
235 /// Returns a new tensor with the same shape, dtype, and device as the current tensor filled with ones.
236 ///
237 /// # Example
238 ///
239 /// ```rust
240 /// use burn_tensor::backend::Backend;
241 /// use burn_tensor::{Tensor, Shape};
242 ///
243 /// fn example<B: Backend>() {
244 /// let device = B::Device::default();
245 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
246 /// let tensor = tensor.ones_like();
247 /// println!("{tensor}");
248 /// // [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
249 /// }
250 /// ```
251 pub fn ones_like(&self) -> Self {
252 Self::new(K::ones(self.shape(), &self.device(), self.dtype()))
253 }
254
255 /// Create a tensor of the given shape where each element is equal to the provided value.
256 ///
257 /// # Example
258 ///
259 /// ```rust
260 /// use burn_tensor::backend::Backend;
261 /// use burn_tensor::{Tensor, Shape};
262 ///
263 /// fn example<B: Backend>() {
264 /// let device = B::Device::default();
265 /// let tensor = Tensor::<B, 2>::full(Shape::new([2, 3]), 5.0, &device);
266 /// println!("{tensor}");
267 /// // [[5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]
268 /// }
269 /// ```
270 pub fn full<S: Into<Shape>, E: ElementConversion>(
271 shape: S,
272 fill_value: E,
273 options: impl Into<TensorCreationOptions<B>>,
274 ) -> Self {
275 let opt = options.into();
276 let shape = shape.into();
277 let dtype = opt.resolve_policy(K::Elem::dtype());
278 check!(TensorCheck::creation_ops::<D>("Full", &shape));
279 Self::new(K::full(
280 shape,
281 Scalar::new(fill_value, &dtype),
282 &opt.device,
283 dtype,
284 ))
285 }
286
287 /// Returns a new tensor with the same shape, dtype, and device as the current tensor,
288 /// filled with the provided value.
289 ///
290 /// # Example
291 ///
292 /// ```rust
293 /// use burn_tensor::backend::Backend;
294 /// use burn_tensor::{Tensor, Shape};
295 ///
296 /// fn example<B: Backend>() {
297 /// let device = B::Device::default();
298 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
299 /// let tensor = tensor.full_like(5.0);
300 /// println!("{tensor}");
301 /// // [[5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]
302 /// }
303 /// ```
304 pub fn full_like<E: ElementConversion>(&self, fill_value: E) -> Self {
305 let dtype = self.dtype();
306 Self::new(K::full(
307 self.shape(),
308 Scalar::new(fill_value, &dtype),
309 &self.device(),
310 dtype,
311 ))
312 }
313
314 /// Returns the dimensions of the current tensor.
315 ///
316 /// # Example
317 /// ```rust
318 /// use burn_tensor::backend::Backend;
319 /// use burn_tensor::Tensor;
320 ///
321 /// fn example<B: Backend>() {
322 /// let device = Default::default();
323 /// let tensor = Tensor::<B, 3>::ones([2, 3, 4], &device);
324 /// let dims = tensor.dims(); // [2, 3, 4]
325 /// println!("{dims:?}");
326 /// }
327 /// ```
328 pub fn dims(&self) -> [usize; D] {
329 Self::shape(self).dims()
330 }
331
332 /// Returns the shape of the current tensor.
333 ///
334 /// # Example
335 /// ```rust
336 /// use burn_tensor::backend::Backend;
337 /// use burn_tensor::Tensor;
338 ///
339 /// fn example<B: Backend>() {
340 /// let device = Default::default();
341 /// let tensor = Tensor::<B, 3>::ones([2, 3, 4], &device);
342 /// // Shape { dims: [2, 3, 4] }
343 /// let shape = tensor.shape();
344 /// }
345 /// ```
346 pub fn shape(&self) -> Shape {
347 self.primitive.shape()
348 }
349
350 /// Reshape the tensor to have the given shape.
351 ///
352 /// The tensor has the same data and number of elements as the input.
353 ///
354 /// A `-1` in the shape is used to infer the remaining dimensions, e.g.: `[2, -1]`
355 /// will reshape the tensor with [2, 3, 4] dimensions to [2, 12].
356 ///
357 /// A `0` in the shape instructs to keep the current dimension from the original tensor,
358 /// e.g.: `[2, 0, 4]` will reshape the tensor with [2, 3, 4] dimensions to [2, 3, 4].
359 /// This is useful when reshaping tensors with unknown dimensions and combining with `-1`
360 /// to infer the remaining dimensions, e.g. `[0, -1]` will reshape the tensor
361 /// with [1, 3, 4] dimensions to [1, 12].
362 ///
363 /// # Arguments
364 /// - `shape`: The new shape of the tensor.
365 ///
366 /// # Panics
367 /// - If the tensor contains more than one `-1` in the shape.
368 /// - If the tensor contains values that are not positive (other than -1).
369 /// - If the shape does not match the number of elements of the original shape.
370 ///
371 /// # Example
372 ///
373 /// ```rust
374 /// use burn_tensor::backend::Backend;
375 /// use burn_tensor::Tensor;
376 ///
377 /// fn example<B: Backend>() {
378 /// let device = Default::default();
379 /// // Create a tensor with dimensions [2, 3, 4]
380 /// let tensor = Tensor::<B, 3>::ones([2, 3, 4], &device);
381 /// // Reshape it to [2, 12], where 12 is inferred from the number of elements.
382 /// let reshaped = tensor.reshape([2, -1]);
383 /// println!("{reshaped}");
384 /// }
385 /// ```
386 pub fn reshape<const D2: usize, S: ReshapeArgs<D2>>(self, shape: S) -> Tensor<B, D2, K> {
387 // Convert reshape args to shape
388 let shape = shape.into_shape::<D2>(self.shape());
389 Tensor::new(K::reshape(self.primitive, shape))
390 }
391
392 /// Transpose the tensor.
393 ///
394 /// For a 2D tensor, this is the standard matrix transpose. For `D > 2`, the transpose is
395 /// applied on the last two dimensions. For example, the transpose of a tensor with shape
396 /// `[1, 2, 3, 4]` will have shape `[1, 2, 4, 3]`.
397 ///
398 /// See also [`permute`](Tensor::permute).
399 ///
400 /// # Arguments
401 ///
402 /// * `tensor` - The tensor to transpose.
403 ///
404 /// # Returns
405 ///
406 /// The transposed tensor.
407 ///
408 /// # Example
409 ///
410 /// ```rust
411 /// use burn_tensor::backend::Backend;
412 /// use burn_tensor::Tensor;
413 ///
414 /// fn example<B: Backend>() {
415 /// let device = Default::default();
416 /// // Create a 2D tensor of shape [2, 3]
417 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
418 ///
419 /// // Transpose the tensor:
420 /// // [[1.0, 5.0], [-2.0, 9.0], [3.0, 6.0]]
421 /// // The resulting tensor will have dimensions [3, 2].
422 /// let transposed = tensor.transpose();
423 /// println!("{transposed}");
424 /// }
425 /// ```
426 pub fn transpose(self) -> Tensor<B, D, K> {
427 Tensor::new(K::transpose(self.primitive))
428 }
429
430 /// Alias for `transpose`.
431 #[inline(always)]
432 pub fn t(self) -> Tensor<B, D, K> {
433 self.transpose()
434 }
435
436 /// Swaps two dimensions of a tensor.
437 ///
438 /// This is a no-op when `dim1 == dim2`, assuming both are within bounds.
439 ///
440 /// # Arguments
441 ///
442 /// * `tensor` - The tensor to swap the dimensions of.
443 /// * `dim1` - The first dimension to swap, supports negative indexing.
444 /// * `dim2` - The second dimension to swap, supports negative indexing.
445 ///
446 /// # Returns
447 ///
448 /// The tensor with the dimensions swapped.
449 ///
450 /// # Panics
451 ///
452 /// When dimensions are out of bounds.
453 ///
454 /// # Example
455 ///
456 /// ```rust
457 /// use burn_tensor::backend::Backend;
458 /// use burn_tensor::Tensor;
459 ///
460 /// fn example<B: Backend>() {
461 /// let device = Default::default();
462 /// // Create a 2D tensor of shape [2, 3]
463 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
464 ///
465 /// // Swap the dimensions 0 and -1 (equivalent to `tensor.transpose()`):
466 /// // [[1.0, 5.0], [-2.0, 9.0], [3.0, 6.0]]
467 /// // The resulting tensor will have dimensions [3, 2].
468 /// let swapped = tensor.swap_dims(0, -1);
469 /// println!("{swapped}");
470 /// }
471 /// ```
472 pub fn swap_dims<Dim1, Dim2>(self, dim1: Dim1, dim2: Dim2) -> Tensor<B, D, K>
473 where
474 Dim1: AsIndex,
475 Dim2: AsIndex,
476 {
477 let dim1 = dim1.expect_dim_index(D);
478 let dim2 = dim2.expect_dim_index(D);
479 check!(TensorCheck::swap_dims::<D>(dim1, dim2));
480 if dim1 == dim2 {
481 self
482 } else {
483 Tensor::new(K::swap_dims(self.primitive, dim1, dim2))
484 }
485 }
486
487 /// Permute the dimensions of the tensor.
488 ///
489 /// This is a no-op when the resolved `axes` match the current order.
490 ///
491 /// # Arguments
492 ///
493 /// * `axes` - The new order of the dimensions. The length of the axes
494 /// must be equal to the number of dimensions of the tensor.
495 /// The values must be unique and in the range of the number of dimensions.
496 /// The values can be negative, in which case they are used as an offset from the end.
497 ///
498 /// # Returns
499 ///
500 /// The tensor with the dimensions permuted.
501 ///
502 /// # Example
503 ///
504 /// ```rust
505 /// use burn_tensor::backend::Backend;
506 /// use burn_tensor::Tensor;
507 ///
508 /// fn example<B: Backend>() {
509 /// let device = Default::default();
510 /// // Create a 2D tensor of shape [3, 2]
511 /// let tensor = Tensor::<B, 2>::from_data([[1.0, 5.0], [-2.0, 9.0], [3.0, 6.0]], &device);
512 ///
513 /// // Permute the dimensions 1 and 0:
514 /// // [[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]]
515 /// // The resulting tensor will have dimensions [3, 2].
516 /// let permuted = tensor.permute([1, 0]);
517 /// println!("{permuted}");
518 /// }
519 /// ```
520 pub fn permute<Dim>(self, axes: [Dim; D]) -> Tensor<B, D, K>
521 where
522 Dim: AsIndex,
523 {
524 let mut no_op = true;
525 let mut fixed_axes = [0; D];
526 for (i, axis) in axes.into_iter().enumerate() {
527 let dim = axis.expect_dim_index(D);
528 no_op &= dim == i;
529 fixed_axes[i] = dim;
530 }
531
532 if no_op {
533 self
534 } else {
535 check!(TensorCheck::permute(fixed_axes));
536 Tensor::new(K::permute(self.primitive, &fixed_axes))
537 }
538 }
539
540 /// Moves the dimension(s) of input at the position(s) in source to the position(s) in destination.
541 ///
542 /// Other dimensions of input that are not explicitly moved remain in their original order and appear
543 /// at the positions not specified in destination.
544 ///
545 /// # Arguments
546 ///
547 /// * `src` - The dimension(s) to move. The values must be unique and in the range of the number of dimensions.
548 /// The values can be negative, in which case they are used as an offset from the end.
549 ///
550 /// * `dst` - Destination positions for each of the original dims. These must also be unique.
551 ///
552 /// # Panics
553 ///
554 /// - If the source and destination dimensions are not of the same length.
555 /// - If the source and destination vectors contain duplicate values.
556 /// - If the source and destination vectors contain values that are out of bounds.
557 ///
558 /// # Returns
559 ///
560 /// The tensor with the dimensions moved.
561 ///
562 /// # Example
563 ///
564 /// ```rust
565 /// use burn_tensor::backend::Backend;
566 /// use burn_tensor::Tensor;
567 ///
568 /// fn example<B: Backend>() {
569 /// let device = Default::default();
570 /// // Create a 3D tensor of shape [3, 2, 1]
571 /// let tensor = Tensor::<B, 3>::from_data([[[1.0], [5.0]], [[-2.0], [9.0]], [[3.0], [6.0]]], &device);
572 ///
573 /// // Move the dimensions 0 and 1:
574 /// // [[[1.0], [-2.0], [3.0]], [[5.0], [9.0], [6.0]]]
575 /// // The resulting tensor will have dimensions [2, 3, 1].
576 /// let moved = tensor.movedim(1, 0);
577 /// println!("{moved}");
578 /// }
579 /// ```
580 ///
581 /// # Note
582 ///
583 /// This is a syntactic sugar for `permute`. It is used widely enough, so we define a separate Op
584 /// for it
585 pub fn movedim<S1: MovedimArgs, S2: MovedimArgs>(self, src: S1, dst: S2) -> Tensor<B, D, K> {
586 let source_dims = src.into_dim_vec::<D>();
587 let destination_dims = dst.into_dim_vec::<D>();
588
589 check!(TensorCheck::movedim_args_length(
590 &source_dims,
591 &destination_dims
592 ));
593
594 let mut m = [-1; D];
595 for (&d, &s) in destination_dims.iter().zip(source_dims.iter()) {
596 m[d] = s as isize;
597 }
598 let mut axes: [isize; D] = [0; D];
599 let mut source_i = 0;
600 for (dest_i, item) in axes.iter_mut().enumerate().take(D) {
601 *item = if m[dest_i] != -1 {
602 m[dest_i]
603 } else {
604 while source_dims.contains(&source_i) {
605 source_i += 1;
606 }
607 let result = source_i as isize;
608 source_i += 1;
609 result
610 };
611 }
612
613 self.permute(axes)
614 }
615
616 /// Reverse the order of elements in the tensor along the given dimensions.
617 ///
618 /// # Arguments
619 ///
620 /// * `axes` - The dimensions to reverse. The values must be unique and in the range of the number of dimensions.
621 /// The values can be negative, in which case they are used as an offset from the end.
622 ///
623 /// # Returns
624 ///
625 /// The tensor with the axes flipped.
626 ///
627 /// # Example
628 ///
629 /// ```rust
630 /// use burn_tensor::backend::Backend;
631 /// use burn_tensor::Tensor;
632 ///
633 /// fn example<B: Backend>() {
634 /// let device = Default::default();
635 /// // Create a 2D tensor with dimensions [4, 3]
636 /// let tensor = Tensor::<B, 2>::from_data(
637 /// [
638 /// [3.0, 4.9, 2.0],
639 /// [2.0, 1.9, 3.0],
640 /// [4.0, 5.9, 8.0],
641 /// [1.4, 5.8, 6.0],
642 /// ],
643 /// &device,
644 /// );
645 ///
646 /// // Flip the elements in dimensions 0 and 1:
647 /// // [[6.0, 5.8, 1.4],
648 /// // [8.0, 5.9, 4.0],
649 /// // [3.0, 1.9, 2.0],
650 /// // [2.0, 4.9, 3.0]]
651 /// // The resulting tensor will have dimensions [4, 3].
652 /// let flipped = tensor.flip([0, 1]);
653 /// println!("{flipped}");
654 /// }
655 /// ```
656 pub fn flip<const N: usize>(self, axes: [isize; N]) -> Tensor<B, D, K> {
657 // Convert the axes to usize and handle negative values without using vector
658 let mut transformed_axes: [usize; N] = [0; N];
659 for (i, &x) in axes.iter().enumerate() {
660 transformed_axes[i] = if x < 0 {
661 (D as isize + x) as usize
662 } else {
663 x as usize
664 };
665 }
666
667 // Check if the axes are valid
668 check!(TensorCheck::flip(D, &transformed_axes));
669
670 Tensor::new(K::flip(self.primitive, &transformed_axes))
671 }
672
673 /// Flatten the tensor along a given range of dimensions.
674 ///
675 /// This function collapses the specified range of dimensions into a single dimension,
676 /// effectively flattening the tensor in that range.
677 ///
678 /// # Arguments
679 ///
680 /// - `start_dim`: The starting dimension of the range to be flattened,
681 /// supports negative indexing.
682 /// - `end_dim`: The ending dimension of the range to be flattened (inclusive),
683 /// supports negative indexing.
684 ///
685 /// # Type Parameters
686 ///
687 /// - `D2`: The resulting number of dimensions in the flattened tensor.
688 ///
689 /// # Returns
690 ///
691 /// A new `Tensor<B, D2, K>` instance with the specified range of dimensions flattened.
692 ///
693 /// # Example
694 ///
695 /// ```rust
696 ///
697 /// use burn_tensor::backend::Backend;
698 /// use burn_tensor::{Tensor, Shape};
699 ///
700 /// fn example<B: Backend>() {
701 /// let device = Default::default();
702 /// // Create a 3D tensor with dimensions [2, 3, 4]
703 /// let tensor = Tensor::<B, 3>::ones(Shape::new([2, 3, 4]), &device);
704 ///
705 /// // Flatten the tensor from dimensions 1 to 2 (inclusive).
706 /// // The resulting tensor will have dimensions [2, 12]
707 /// let flattened: Tensor<B, 2> = tensor.flatten(1, 2);
708 /// println!("{flattened}");
709 /// }
710 /// ```
711 pub fn flatten<const D2: usize>(
712 self,
713 start_dim: impl AsIndex,
714 end_dim: impl AsIndex,
715 ) -> Tensor<B, D2, K> {
716 let start_dim = start_dim.expect_dim_index(D);
717 let end_dim = end_dim.expect_dim_index(D);
718 check!(TensorCheck::flatten::<D, D2>(start_dim, end_dim));
719 let new_shape = self.shape().flatten_dims(start_dim, end_dim);
720
721 Tensor::new(K::reshape(self.primitive, new_shape))
722 }
723
724 /// Squeeze the tensor along all dimensions, removing dimensions
725 /// of size one, and effectively reducing the rank of the tensor.
726 ///
727 /// # Type Parameters
728 ///
729 /// - `D2`: The resulting number of dimensions in the squeezed tensor.
730 ///
731 /// # Returns
732 ///
733 /// A new `Tensor<B, D2, K>` instance with the specified dimension removed.
734 ///
735 /// # Example
736 ///
737 /// ```rust
738 ///
739 /// use burn_tensor::backend::Backend;
740 /// use burn_tensor::{Tensor, Shape};
741 ///
742 /// fn example<B: Backend>() {
743 /// let device = Default::default();
744 /// // Create a 4D tensor with dimensions [1, 3, 1, 3]
745 /// let tensor = Tensor::<B, 4>::from_data(
746 /// [[[[3.0, 4.9, 2.0]], [[2.0, 1.9, 3.0]], [[4.0, 5.9, 8.0]]]],
747 /// &device,
748 /// );
749 ///
750 /// // Squeeze the tensor dimensions.
751 /// // The resulting tensor will have dimensions [3, 3].
752 /// let squeezed = tensor.squeeze::<2>();
753 /// println!("{squeezed}");
754 /// }
755 /// ```
756 pub fn squeeze<const D2: usize>(self) -> Tensor<B, D2, K> {
757 let new_dims = self
758 .shape()
759 .iter()
760 .filter_map(|&dim| if dim == 1 { None } else { Some(dim) })
761 .collect::<Vec<_>>();
762 check!(TensorCheck::squeeze_dims_len::<D2>(new_dims.len()));
763
764 Tensor::new(K::reshape(self.primitive, new_dims.into()))
765 }
766
767 /// Squeeze the tensor along the given dimension, removing the specified dimension
768 /// of size one, and effectively reducing the rank of the tensor by one.
769 ///
770 /// # Arguments
771 ///
772 /// - `dim`: The dimension to be squeezed.
773 ///
774 /// # Type Parameters
775 ///
776 /// - `D2`: The resulting number of dimensions in the squeezed tensor.
777 ///
778 /// # Panics
779 ///
780 /// If the size in the squeezed dimension is not 1.
781 ///
782 /// # Returns
783 ///
784 /// A new `Tensor<B, D2, K>` instance with the specified dimension removed.
785 ///
786 /// # Example
787 ///
788 /// ```rust
789 ///
790 /// use burn_tensor::backend::Backend;
791 /// use burn_tensor::{Tensor, Shape};
792 ///
793 /// fn example<B: Backend>() {
794 /// let device = Default::default();
795 /// // Create a 3D tensor with dimensions [3, 1, 3]
796 /// let tensor = Tensor::<B, 3>::from_data(
797 /// [[[3.0, 4.9, 2.0]], [[2.0, 1.9, 3.0]], [[4.0, 5.9, 8.0]]],
798 /// &device,
799 /// );
800 ///
801 /// // Squeeze the dimension 1.
802 /// // The resulting tensor will have dimensions [3, 3].
803 /// let squeezed = tensor.squeeze_dim::<2>(1);
804 /// println!("{squeezed}");
805 /// }
806 /// ```
807 pub fn squeeze_dim<const D2: usize>(self, dim: usize) -> Tensor<B, D2, K> {
808 check!(TensorCheck::squeeze::<D2>(dim, &self.shape()));
809
810 let current_dims = self.shape();
811 let mut new_dims: [usize; D2] = [0; D2];
812
813 new_dims[..dim].copy_from_slice(¤t_dims[..dim]);
814 new_dims[dim..].copy_from_slice(¤t_dims[dim + 1..]);
815
816 check!(TensorCheck::squeeze_dims_len::<D2>(new_dims.len()));
817 Tensor::new(K::reshape(self.primitive, new_dims.into()))
818 }
819
820 /// Removes specified dimensions of size 1 from a tensor's shape. This function takes a tensor and
821 /// an array of dimensions (`dims`) to be squeezed. If `dims` is provided, only the dimensions
822 /// specified in this array will be removed. Each dimension in `dims` should correspond to a size of 1
823 /// in the tensor; otherwise, the dimension will not be squeezed. If `dims` is empty, all single-dimensional entries
824 /// in the tensor will be removed. If entries in `dims` are negative, then dimensions will be counted
825 /// from the back.
826 ///
827 /// # Arguments
828 ///
829 /// - `dims`: The dimension(s) to be squeezed.
830 ///
831 /// # Type Parameters
832 ///
833 /// - `D2`: The resulting number of dimensions in the squeezed tensor.
834 ///
835 /// # Returns
836 ///
837 /// A new `Tensor<B, D2, K>` instance with the specified dimensions removed.
838 ///
839 /// # Example
840 ///
841 /// ```rust
842 ///
843 /// use burn_tensor::backend::Backend;
844 /// use burn_tensor::{Tensor, Shape};
845 ///
846 /// fn example<B: Backend>() {
847 /// let device = Default::default();
848 /// // Create a 4D tensor with dimensions [2, 1, 4, 1]
849 /// let tensor = Tensor::<B, 4>::ones(Shape::new([2, 1, 4, 1]), &device);
850 ///
851 /// // Squeeze the dimensions 1 and 3.
852 /// // The resulting tensor will have dimensions [2, 4].
853 /// let squeezed: Tensor<B, 2> = tensor.squeeze_dims(&[1, 3]);
854 /// println!("{squeezed}");
855 /// }
856 /// ```
857 pub fn squeeze_dims<const D2: usize>(self, dims: &[isize]) -> Tensor<B, D2, K> {
858 let current_dims = self.shape();
859 let mut dim_indices: Vec<usize>;
860
861 // Check if dims is empty, if yes then assign dim_indices all single-dimensional entries
862 if dims.is_empty() {
863 dim_indices = current_dims
864 .iter()
865 .enumerate()
866 .filter_map(|(index, &dim)| if dim == 1 { Some(index) } else { None })
867 .collect();
868 } else {
869 // If negative dims, count from the back
870 dim_indices = dims
871 .iter()
872 .map(|&d| {
873 if d < 0 {
874 (current_dims.len() as isize + d) as usize
875 } else {
876 d as usize
877 }
878 })
879 .collect();
880 }
881
882 // Sort indices and remove duplicates
883 dim_indices.sort_unstable();
884 dim_indices.dedup();
885
886 // Make sure squeeze_dims doesn't result in a tensor with < 1 dimensions
887 check!(TensorCheck::squeeze_dims_input::<D2>(
888 &dim_indices,
889 ¤t_dims
890 ));
891
892 // Calculate new dimensions
893 let mut new_dims = Vec::new();
894 for (index, &dim_size) in current_dims.iter().enumerate() {
895 // Exclude the dimension if it's explicitly marked for squeezing
896 if dim_indices.contains(&index) {
897 check!(TensorCheck::squeeze::<D2>(index, ¤t_dims));
898 continue;
899 }
900 new_dims.push(dim_size);
901 }
902
903 // Check that after squeezing, we still respect the D2 size
904 check!(TensorCheck::squeeze_dims_len::<D2>(new_dims.len()));
905
906 Tensor::new(K::reshape(self.primitive, new_dims.into()))
907 }
908
909 /// Unsqueeze the current tensor. Create new leading dimensions to fit the given size.
910 ///
911 /// # Type Parameters
912 ///
913 /// - `D2`: The resulting number of dimensions in the unsqueezed tensor.
914 ///
915 /// # Panics
916 ///
917 /// If the output size `D2` is smaller than the current number of dimensions.
918 ///
919 /// # Returns
920 ///
921 /// A new `Tensor<B, D2, K>` instance with the specified dimensions added.
922 ///
923 /// # Example
924 ///
925 /// ```rust
926 /// use burn_tensor::backend::Backend;
927 /// use burn_tensor::{Tensor, Shape};
928 ///
929 /// fn example<B: Backend>() {
930 /// let device = Default::default();
931 /// // Create a 2D tensor with dimensions [3, 3]
932 /// let tensor = Tensor::<B, 2>::ones(Shape::new([3, 3]), &device);
933 /// // Unsqueeze the tensor up to 4 dimensions.
934 /// // The resulting tensor will have dimensions [1, 1, 3, 3].
935 /// let unsqueezed = tensor.unsqueeze::<4>();
936 /// println!("{unsqueezed}");
937 /// }
938 /// ```
939 pub fn unsqueeze<const D2: usize>(self) -> Tensor<B, D2, K> {
940 check!(TensorCheck::unsqueeze::<D, D2>());
941
942 let mut dims = [1; D2];
943 let num_ones = D2 - D;
944 let shape = self.shape();
945
946 dims[num_ones..(D + num_ones)].copy_from_slice(&shape[..D]);
947
948 let shape = Shape::new(dims);
949 self.reshape(shape)
950 }
951
952 /// Creates a new tensor with a dimension of size one inserted at the specified position.
953 ///
954 /// # Example
955 ///
956 /// ```rust
957 /// use burn_tensor::backend::Backend;
958 /// use burn_tensor::{Tensor, Shape};
959 ///
960 /// fn example<B: Backend>() {
961 /// let device = Default::default();
962 /// // Create a 2D tensor with dimensions [3, 3]
963 /// let tensor = Tensor::<B, 2>::ones(Shape::new([3, 3]), &device);
964 /// // Unsqueeze the dimension 1.
965 /// // The resulting tensor will have dimensions [3, 1, 3].
966 /// let unsqueezed: Tensor<B, 3> = tensor.unsqueeze_dim(1);
967 /// println!("{unsqueezed}");
968 /// }
969 /// ```
970 pub fn unsqueeze_dim<const D2: usize>(self, dim: usize) -> Tensor<B, D2, K> {
971 check!(TensorCheck::unsqueeze_dim::<D, D2>(dim));
972
973 let mut dims = [1; D2];
974 let shape = self.shape();
975
976 dims[0..dim].copy_from_slice(&shape[0..dim]);
977
978 if dim < D {
979 dims[dim] = 1;
980 dims[(dim + 1)..].copy_from_slice(&shape[dim..]);
981 } else {
982 dims[dim] = 1;
983 }
984
985 let shape = Shape::new(dims);
986 self.reshape(shape)
987 }
988
989 /// Creates a new tensor with added dimensions of size one inserted at the specified indices.
990 /// The indices can be negative, in which case they are counted from the last to the first dimension.
991 /// the axes can contain duplicates, in which case the number of dimensions inserted at the index
992 /// is the number of duplicates.
993 /// # Example
994 ///
995 /// ```rust
996 /// use burn_tensor::backend::Backend;
997 /// use burn_tensor::{Tensor, Shape};
998 ///
999 /// fn example<B: Backend>() {
1000 /// let device = Default::default();
1001 /// // Create a 3D tensor with dimensions [3, 4, 5]
1002 /// let tensor = Tensor::<B, 3>::ones(Shape::new([3, 4, 5]), &device);
1003 /// // Unsqueeze the leading dimension (0) once and the trailing dimension (-1) twice.
1004 /// // The resulting tensor will have dimensions [1, 3, 4, 5, 1, 1].
1005 /// let unsqueezed: Tensor<B, 6> = tensor.unsqueeze_dims(&[0, -1, -1]);
1006 /// println!("{unsqueezed}");
1007 /// }
1008 /// ```
1009 pub fn unsqueeze_dims<const D2: usize>(self, axes: &[impl AsIndex]) -> Tensor<B, D2, K> {
1010 let mut new_dims = [1; D2];
1011 let old_dims = self.shape();
1012 //for checking if the dimension is in the acceptable range
1013
1014 //part 1: convert the negative indices to positive
1015 let mut neg_offset = D2;
1016 let mut dim_indices = axes
1017 .iter()
1018 .map(|d| {
1019 let d = d.as_index();
1020 // check if the dimension is in the acceptable range
1021 check!(TensorCheck::unsqueeze_dims::<{ D2 }>(d));
1022 (if d < 0 {
1023 neg_offset -= 1; // handle multiple negative indices (decrease dim value in reverse)
1024 d + neg_offset as isize + 1
1025 } else {
1026 d
1027 }) as usize
1028 })
1029 .collect::<Vec<usize>>();
1030
1031 //sort the indices
1032 dim_indices.sort_unstable();
1033
1034 //Now use this to copy the chunks of the dims
1035 let mut prev_idx: usize = 0;
1036 let mut current_left_b: usize = 0;
1037 let mut current_right_b: usize = 0;
1038 let mut offset: usize = 0;
1039 dim_indices.iter().for_each(|d| {
1040 //check if there is space for at least one dimension
1041 if prev_idx < *d {
1042 current_right_b = *d - offset;
1043 //copy the chunks of the dims
1044 if current_right_b < D {
1045 new_dims[prev_idx..*d]
1046 .copy_from_slice(&old_dims[current_left_b..current_right_b]);
1047 } else {
1048 new_dims[prev_idx..*d].copy_from_slice(&old_dims[current_left_b..]);
1049 }
1050 prev_idx = *d + 1;
1051 //offset is equal to the number of extracted elements from the original shape
1052 offset += current_right_b - current_left_b;
1053 current_left_b = current_right_b;
1054 } else {
1055 //it's sorted so the only reason this would happen
1056 //is if multiple indices are the same
1057 prev_idx += 1;
1058 }
1059 });
1060 //copy over anything past the index of the last new dimension
1061 if current_left_b < D {
1062 new_dims[prev_idx..].copy_from_slice(&old_dims[current_left_b..]);
1063 }
1064
1065 //lastly, create the shape and reshape
1066 let shape = Shape::new(new_dims);
1067 self.reshape(shape)
1068 }
1069
1070 /// Roll operation along a specific dimension; wrapping around the elements.
1071 ///
1072 /// ## Parameters
1073 ///
1074 /// - `shift`: The roll extent; supports negative values and wraps around.
1075 /// - `dim`: The dimension to roll; supports negative indexing.
1076 ///
1077 /// ## Returns
1078 ///
1079 /// A new tensor with the specified dimension rolled by the given shift amount.
1080 pub fn roll_dim<Shift, Dim>(self, shift: Shift, dim: Dim) -> Self
1081 where
1082 Shift: AsIndex,
1083 Dim: AsIndex,
1084 {
1085 let dim = dim.expect_dim_index(D);
1086 let size = self.shape()[dim];
1087 if size == 0 {
1088 // If the dimension is empty, return the tensor as is.
1089 return self;
1090 }
1091
1092 let shift = wrap_index(shift, size);
1093 if shift == 0 {
1094 // If the shift is zero, return the tensor as is.
1095 return self;
1096 }
1097
1098 self.unchecked_roll_dim(shift, dim)
1099 }
1100
1101 /// Internal implementation of `roll_dim` that does not canonicalize dimensions or shifts.
1102 ///
1103 /// ## Parameters
1104 ///
1105 /// - `shift`: The number of positions to shift; must be (0 < shift < size).
1106 /// - `dim`: The dimension to roll; must be a valid index for the tensor's shape.
1107 ///
1108 /// ## Returns
1109 ///
1110 /// A new tensor with the specified dimension rolled by the given shift amount.
1111 #[inline(always)]
1112 fn unchecked_roll_dim(self, shift: usize, dim: usize) -> Self {
1113 #[cfg(debug_assertions)]
1114 {
1115 let size = self.shape()[dim];
1116 assert!(
1117 0 < shift && shift < size,
1118 "Expected: 0 < shift < size: found shift={shift}, size={size}",
1119 );
1120 assert!(
1121 dim < self.shape().num_dims(),
1122 "Expected: dim < num_dims: found dim={dim}, num_dims={size}",
1123 );
1124 }
1125
1126 Tensor::cat(
1127 vec![
1128 self.clone().slice_dim(dim, shift..),
1129 self.slice_dim(dim, ..shift),
1130 ],
1131 dim,
1132 )
1133 }
1134
1135 /// Roll operation.
1136 ///
1137 /// Note: unlike ``pytorch``, `dims` and `shifts` must have the same length.
1138 ///
1139 /// A given `dim` may be rolled multiple times, and the shifts will be applied sequentially.
1140 ///
1141 /// ## Parameters
1142 ///
1143 /// - `shifts`: A slice of shifts corresponding to each dimension;
1144 /// supports negative values and wraps around.
1145 /// - `dims`: A slice of dimensions to roll; supports negative indexing.
1146 ///
1147 /// ## Returns
1148 ///
1149 /// A new tensor with the specified dimensions rolled by the given shifts.
1150 pub fn roll<Shift, Dim>(self, shifts: &[Shift], dims: &[Dim]) -> Self
1151 where
1152 Shift: AsIndex,
1153 Dim: AsIndex,
1154 {
1155 assert_eq!(
1156 dims.len(),
1157 shifts.len(),
1158 "Dimensions and shifts must align; found dims={dims:#?}, shifts={shifts:#?}",
1159 );
1160
1161 // This is a fair amount of complexity, which could be replaced
1162 // by a simple canonicalization of `dims` and wrapping of `shifts`.
1163 // The work is done here to ensure that any roll operation
1164 // which could be a no-op is a no-op; simplifying the accounting
1165 // needed by backend-specific implementations of the inner roll op.
1166
1167 let item_count = dims.len();
1168
1169 let shape = self.shape();
1170
1171 // Accumulate the effective shifts for each dimension.
1172 let mut accumulated_shifts: Vec<isize> = vec![0; shape.len()];
1173 for i in 0..item_count {
1174 let dim = dims[i].expect_dim_index(D);
1175 accumulated_shifts[dim] += shifts[i].as_index();
1176 }
1177
1178 // Do this after we've checked the validity of `dims` and `shifts`.
1179 if self.shape().num_elements() == 0 {
1180 // If the tensor is empty, return it as is.
1181 return self;
1182 }
1183
1184 // Wrap the accumulated shifts, and filter out empty dimensions.
1185 let mut effective_dims: Vec<usize> = Vec::with_capacity(item_count);
1186 let mut effective_shifts: Vec<usize> = Vec::with_capacity(item_count);
1187 for dim in 0..shape.len() {
1188 // `wrap_index` should inline, and has a fast-exit path for zero shifts.
1189 let shift = wrap_index(accumulated_shifts[dim], shape[dim]);
1190 if shift == 0 {
1191 continue;
1192 }
1193
1194 effective_dims.push(dim);
1195 effective_shifts.push(shift);
1196 }
1197
1198 // If no shifts are needed, return the original tensor.
1199 if effective_shifts.is_empty() {
1200 return self;
1201 }
1202
1203 // At this point:
1204 // - `dims` contains the effective dimensions to roll, in index order,
1205 // - `shifts` contains the effective usize shifts for each dimension.
1206 // - Every shift is non-zero, and less than the size of the corresponding dimension.
1207 self.unchecked_roll(&effective_shifts, &effective_dims)
1208 }
1209
1210 /// `roll` internal implementation.
1211 ///
1212 /// ## Parameters
1213 ///
1214 /// - `shifts`: A slice of shifts corresponding to each dimension;
1215 /// must be non-empty, the same length as `dims`, and all ``1..<size>``.
1216 /// - `dims`: A slice of dimensions to roll; must be non-empty;
1217 /// the same length as `shifts`, and must not contain repeats.
1218 ///
1219 /// ## Panics
1220 ///
1221 /// Panics if the shifts and dimensions do not align, or if dimensions contain repeats.
1222 ///
1223 /// ## Returns
1224 ///
1225 /// A new tensor with the specified dimensions rolled by the given shifts.
1226 #[inline(always)]
1227 fn unchecked_roll(self, shifts: &[usize], dims: &[usize]) -> Self {
1228 #[cfg(debug_assertions)]
1229 {
1230 assert!(!shifts.is_empty());
1231 assert_eq!(
1232 shifts.len(),
1233 dims.len(),
1234 "Shifts and dimensions must align; found {} shifts and {} dims",
1235 shifts.len(),
1236 dims.len()
1237 );
1238
1239 let mut unique_dims = dims.to_vec();
1240 unique_dims.dedup();
1241
1242 assert_eq!(
1243 unique_dims.len(),
1244 dims.len(),
1245 "Dimensions must not contain repeats; found {} unique dims and {} total dims",
1246 unique_dims.len(),
1247 dims.len()
1248 )
1249 }
1250
1251 let x = self.unchecked_roll_dim(shifts[0], dims[0]);
1252
1253 if dims.len() == 1 {
1254 x
1255 } else {
1256 x.unchecked_roll(&shifts[1..], &dims[1..])
1257 }
1258 }
1259
1260 /// Returns a tensor containing the elements selected from the given slices.
1261 ///
1262 /// This method provides flexible tensor slicing with support for various range types,
1263 /// negative indices, and stepped slicing. The method accepts both single slices and
1264 /// arrays of slices, with the [`s!`] macro providing convenient syntax for complex patterns.
1265 ///
1266 /// # Arguments
1267 ///
1268 /// * `slices` - Can be:
1269 /// - A single range for 1D slicing (e.g., `0..5`, `..`, `2..`)
1270 /// - An array of ranges (e.g., `[0..2, 1..4]`)
1271 /// - The [`s!`] macro output for advanced slicing with steps
1272 /// - a `&Vec<Slice>` or `&[Slice]`
1273 ///
1274 /// # Behavior
1275 ///
1276 /// - Supports partial and full slicing in any number of dimensions
1277 /// - Handles negative indices by wrapping from the end (-1 is the last element)
1278 /// - Automatically clamps ranges that exceed tensor dimensions
1279 /// - Supports stepped slicing for selecting every nth element
1280 /// - Negative steps reverse the selection order
1281 ///
1282 /// # Panics
1283 ///
1284 /// - If the number of slices exceeds the tensor's dimensions
1285 /// - If a range is descending (e.g., 2..1) or empty (e.g., 1..1) without negative step
1286 /// - If a step is zero
1287 ///
1288 /// # Examples
1289 ///
1290 /// ```rust
1291 /// use burn_tensor::backend::Backend;
1292 /// use burn_tensor::{Tensor, Shape, s};
1293 ///
1294 /// fn example<B: Backend>() {
1295 /// let device = B::Device::default();
1296 ///
1297 /// // Single dimension slicing - no brackets needed!
1298 /// let tensor = Tensor::<B, 1, burn_tensor::Int>::arange(0..10, &device);
1299 /// let slice = tensor.clone().slice(2..8); // Simple range
1300 /// assert_eq!(slice.into_data().to_vec::<i32>().unwrap(), vec![2, 3, 4, 5, 6, 7]);
1301 ///
1302 /// // Using s! macro for single dimension with step
1303 /// let slice = tensor.clone().slice(s![0..10;2]); // Every 2nd element
1304 /// assert_eq!(slice.into_data().to_vec::<i32>().unwrap(), vec![0, 2, 4, 6, 8]);
1305 ///
1306 /// // Reverse a dimension with negative step
1307 /// let slice = tensor.slice(s![..;-1]); // Reverse entire tensor
1308 /// assert_eq!(slice.into_data().to_vec::<i32>().unwrap(), vec![9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
1309 ///
1310 /// // Multi-dimensional slicing
1311 /// let tensor = Tensor::<B, 2>::ones(Shape::new([4, 6]), &device);
1312 ///
1313 /// // Array syntax for simple ranges
1314 /// let slice = tensor.clone().slice([1..3, 2..5]);
1315 /// assert_eq!(slice.dims(), [2, 3]);
1316 ///
1317 /// // Advanced multi-dimensional with s! macro
1318 /// let slice = tensor.clone().slice(s![0..4;2, ..;-1]); // Every 2nd row, reverse columns
1319 /// assert_eq!(slice.dims(), [2, 6]);
1320 ///
1321 /// // Complex 3D example with mixed slice types
1322 /// let tensor = Tensor::<B, 3>::ones(Shape::new([4, 6, 8]), &device);
1323 /// let slice = tensor.slice(s![1..3, ..;2, -3..]); // Rows 1-2, every 2nd col, last 3 depth
1324 /// assert_eq!(slice.dims(), [2, 3, 3]);
1325 ///
1326 /// // Using negative indices
1327 /// let tensor = Tensor::<B, 2>::ones(Shape::new([4, 6]), &device);
1328 /// let slice = tensor.slice(s![-2.., ..-1]); // Last 2 rows, all but last column
1329 /// assert_eq!(slice.dims(), [2, 5]);
1330 /// }
1331 /// ```
1332 ///
1333 /// # See Also
1334 ///
1335 /// - [`s!`] - The recommended macro for creating complex slice specifications
1336 /// - [`slice_assign`](Self::slice_assign) - Assign values to a slice
1337 /// - [`slice_fill`](Self::slice_fill) - Fill a slice with a constant value
1338 /// - [`slice_dim`](Self::slice_dim) - Slice a single dimension
1339 ///
1340 /// [`s!`]: crate::s!
1341 pub fn slice<S>(self, slices: S) -> Self
1342 where
1343 S: SliceArg,
1344 {
1345 let shape = self.shape();
1346 let slices = slices.into_slices(&shape);
1347
1348 // Validate slices
1349 check!(TensorCheck::slice::<D>(&shape, &slices));
1350
1351 // Calculate output shape and check for empty slices
1352 let mut output_dims = shape.clone();
1353 for (dim, slice) in slices.iter().enumerate() {
1354 output_dims[dim] = slice.output_size(shape[dim]);
1355 }
1356
1357 // Return empty tensor if any dimension is 0 (empty slice)
1358 if output_dims.contains(&0) {
1359 return Self::empty(output_dims, &self.device());
1360 }
1361 Self::new(K::slice(self.primitive, &slices))
1362 }
1363
1364 /// Assigns values to a slice of the tensor and returns the updated tensor.
1365 ///
1366 /// This method supports advanced slicing with steps, including negative steps for reverse
1367 /// assignment. Like `slice`, it accepts both single slices and arrays, with the [`s!`] macro
1368 /// providing powerful syntax for complex patterns.
1369 ///
1370 /// # Arguments
1371 ///
1372 /// * `slices` - Slice specification (same format as `slice` method)
1373 /// * `values` - Tensor with values to assign (must match slice dimensions)
1374 ///
1375 /// # Panics
1376 ///
1377 /// - If slices exceed tensor dimensions
1378 /// - If values dimensions don't match the selected slice shape
1379 /// - If a step is zero
1380 ///
1381 /// # Examples
1382 ///
1383 /// ```rust
1384 /// use burn_tensor::backend::Backend;
1385 /// use burn_tensor::{Tensor, s};
1386 ///
1387 /// fn example<B: Backend>() {
1388 /// let device = B::Device::default();
1389 ///
1390 /// // Simple assignment to a sub-region
1391 /// let mut tensor = Tensor::<B, 2>::zeros([4, 6], &device);
1392 /// let values = Tensor::<B, 2>::ones([2, 3], &device);
1393 /// tensor = tensor.slice_assign([1..3, 2..5], values);
1394 /// // Now tensor[1..3, 2..5] contains ones
1395 ///
1396 /// // Single dimension assignment with step
1397 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1398 /// let values = Tensor::<B, 1>::ones([5], &device);
1399 /// tensor = tensor.slice_assign(s![0..10;2], values);
1400 /// // Now every 2nd element is 1: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
1401 ///
1402 /// // Reverse assignment with negative step
1403 /// let mut tensor = Tensor::<B, 1>::from_data([0.0, 1.0, 2.0, 3.0, 4.0], &device);
1404 /// let values = Tensor::<B, 1>::from_data([10.0, 11.0, 12.0, 13.0, 14.0], &device);
1405 /// tensor = tensor.slice_assign(s![..;-1], values);
1406 /// // Assigns in reverse: [14, 13, 12, 11, 10]
1407 ///
1408 /// // Complex multi-dimensional assignment
1409 /// let mut tensor = Tensor::<B, 3>::zeros([4, 6, 8], &device);
1410 /// let values = Tensor::<B, 3>::ones([2, 3, 3], &device);
1411 /// tensor = tensor.slice_assign(s![0..4;2, ..;2, -3..], values);
1412 /// // Assigns to every 2nd row, every 2nd column, last 3 in depth
1413 ///
1414 /// // Mixed syntax example
1415 /// let mut tensor = Tensor::<B, 2>::zeros([8, 8], &device);
1416 /// let pattern = Tensor::<B, 2>::ones([4, 4], &device);
1417 /// tensor = tensor.slice_assign(s![..;2, ..;2], pattern);
1418 /// // Creates a checkerboard pattern with ones
1419 /// }
1420 /// ```
1421 ///
1422 /// # See Also
1423 ///
1424 /// - [`s!`] - The recommended macro for creating complex slice specifications
1425 /// - [`slice`](Self::slice) - Extract a slice from a tensor
1426 /// - [`slice_fill`](Self::slice_fill) - Fill a slice with a constant value
1427 ///
1428 /// [`s!`]: crate::s!
1429 pub fn slice_assign<S>(self, slices: S, values: Self) -> Self
1430 where
1431 S: SliceArg,
1432 {
1433 let shape = self.shape();
1434 let slices = slices.into_slices(&shape);
1435
1436 // Check if any slice produces 0 elements (empty assignment).
1437 // Empty assignments are no-ops and would cause issues in backend implementations.
1438 let is_empty_assignment = slices
1439 .iter()
1440 .enumerate()
1441 .any(|(i, slice)| slice.output_size(shape[i]) == 0);
1442
1443 if is_empty_assignment {
1444 return self;
1445 }
1446
1447 check!(TensorCheck::slice_assign::<D>(
1448 &shape,
1449 &values.shape(),
1450 &slices
1451 ));
1452
1453 Self::new(K::slice_assign(self.primitive, &slices, values.primitive))
1454 }
1455
1456 /// Fills a slice of the tensor with a constant value and returns the updated tensor.
1457 ///
1458 /// Like other slice methods, accepts both single slices and arrays. However, this method
1459 /// currently **does not support stepped slicing** - use [`slice_assign`](Self::slice_assign)
1460 /// with a constant tensor for stepped patterns.
1461 ///
1462 /// # Arguments
1463 ///
1464 /// * `slices` - Slice specification (same format as `slice` method, but no steps)
1465 /// * `value` - The value to fill the slice with
1466 ///
1467 /// # Panics
1468 ///
1469 /// - If slices exceed tensor dimensions
1470 /// - If any slice has a step != 1 (not yet supported)
1471 ///
1472 /// # Examples
1473 ///
1474 /// ```rust
1475 /// use burn_tensor::backend::Backend;
1476 /// use burn_tensor::{Tensor, s};
1477 ///
1478 /// fn example<B: Backend>() {
1479 /// let device = B::Device::default();
1480 ///
1481 /// // Simple fill for a single dimension
1482 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1483 /// tensor = tensor.slice_fill(2..5, 1.0);
1484 /// // Now tensor is [0, 0, 1, 1, 1, 0, 0, 0, 0, 0]
1485 ///
1486 /// // Multi-dimensional fill
1487 /// let mut tensor = Tensor::<B, 2>::zeros([4, 6], &device);
1488 /// tensor = tensor.slice_fill([1..3, 2..5], -1.0);
1489 /// // Fills the rectangle at rows 1-2, columns 2-4 with -1
1490 ///
1491 /// // Using negative indices
1492 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1493 /// tensor = tensor.slice_fill(-3.., 2.0);
1494 /// // Fills the last 3 elements with 2.0
1495 ///
1496 /// // Complex multi-dimensional example
1497 /// let mut tensor = Tensor::<B, 3>::ones([4, 6, 8], &device);
1498 /// tensor = tensor.slice_fill(s![1..3, .., -2..], 0.0);
1499 /// // Sets rows 1-2, all columns, last 2 in depth to 0
1500 ///
1501 /// // Stepped slicing is supported
1502 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1503 /// tensor = tensor.slice_fill(s![0..10;2], 1.0);
1504 /// // Now every 2nd element is 1: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
1505 /// }
1506 /// ```
1507 ///
1508 /// # See Also
1509 ///
1510 /// - [`s!`] - The macro for creating slice specifications with steps
1511 /// - [`slice`](Self::slice) - Extract a slice from a tensor
1512 /// - [`slice_assign`](Self::slice_assign) - Assign tensor values to a slice
1513 ///
1514 /// [`s!`]: crate::s!
1515 pub fn slice_fill<S, E: ElementConversion>(self, slices: S, value: E) -> Self
1516 where
1517 S: SliceArg,
1518 {
1519 let shape = self.shape();
1520 let slices = slices.into_slices(&shape);
1521
1522 check!(TensorCheck::slice::<D>(&shape, &slices));
1523
1524 let slice_shape = shape.slice(&slices).unwrap();
1525 let value = Tensor::<B, 1, K>::from_data_dtype(
1526 [value.elem::<K::Elem>()],
1527 &self.device(),
1528 self.dtype(),
1529 );
1530 let value = value.expand(slice_shape);
1531 self.slice_assign(&slices, value)
1532 }
1533
1534 /// Returns a new tensor with the specified dimension sliced.
1535 ///
1536 /// # Arguments
1537 ///
1538 /// * `dim`: The dimension to slice.
1539 /// * `slice`: The slice specification for the dimension. Can be a range (e.g., `2..5`),
1540 /// slice with step (via `s!` macro, e.g., `s![0..10;2]`), or any type that implements `Into<Slice>`.
1541 ///
1542 /// # Returns
1543 ///
1544 /// A new tensor with the specified dimension sliced.
1545 ///
1546 /// # Panics
1547 ///
1548 /// If the slice is out of bounds for the specified dimension.
1549 ///
1550 /// # Examples
1551 ///
1552 /// ```rust
1553 /// # use burn_tensor::{Tensor, s};
1554 /// # use burn_tensor::backend::Backend;
1555 /// #
1556 /// # fn example<B: Backend>() {
1557 /// # let device = B::Device::default();
1558 /// let tensor = Tensor::<B, 3>::zeros([3, 4, 5], &device);
1559 ///
1560 /// // Simple range slicing
1561 /// let sliced = tensor.clone().slice_dim(1, 1..3);
1562 /// assert_eq!(sliced.shape().as_slice(), [3, 2, 5]);
1563 ///
1564 /// // Slicing with step - take every 2nd element
1565 /// let sliced = tensor.clone().slice_dim(2, s![0..5;2]);
1566 /// assert_eq!(sliced.shape().as_slice(), [3, 4, 3]); // Takes indices 0, 2, 4
1567 ///
1568 /// // Reverse slicing with negative step
1569 /// let sliced = tensor.clone().slice_dim(1, s![..;-1]);
1570 /// assert_eq!(sliced.shape().as_slice(), [3, 4, 5]); // Reverses dimension 1
1571 ///
1572 /// // Select from index 2 with step 3
1573 /// let sliced = tensor.clone().slice_dim(0, s![2..;3]);
1574 /// assert_eq!(sliced.shape().as_slice(), [1, 4, 5]); // Takes only index 2
1575 ///
1576 /// // Select single index (reduces dimension to size 1)
1577 /// let sliced = tensor.slice_dim(0, 1);
1578 /// assert_eq!(sliced.shape().as_slice(), [1, 4, 5]);
1579 /// # }
1580 /// ```
1581 ///
1582 /// # See Also
1583 ///
1584 /// - [`slice`](Self::slice) - Slice multiple dimensions simultaneously
1585 /// - [`s!`] - The macro for creating complex slice specifications
1586 ///
1587 /// [`s!`]: crate::s!
1588 pub fn slice_dim<S>(self, dim: usize, slice: S) -> Self
1589 where
1590 S: Into<Slice>,
1591 {
1592 check!(TensorCheck::check_dim::<D>(dim));
1593 let slice: Slice = slice.into();
1594
1595 let mut slices = vec![Slice::full(); D];
1596 slices[dim] = slice;
1597
1598 self.slice(&slices)
1599 }
1600
1601 /// Returns the device of the current tensor.
1602 pub fn device(&self) -> B::Device {
1603 K::device(&self.primitive)
1604 }
1605
1606 /// Move the tensor to the given device.
1607 pub fn to_device(self, device: &B::Device) -> Self {
1608 Self::new(K::to_device(self.primitive, device))
1609 }
1610
1611 /// Select tensor elements along the given dimension corresponding to the given indices.
1612 ///
1613 /// # Arguments
1614 ///
1615 /// * `dim` - The dimension to select from. Supports negative indexing.
1616 /// * `indices` - The indices of the elements to select.
1617 ///
1618 /// # Example
1619 ///
1620 /// ```rust
1621 /// use burn_tensor::backend::Backend;
1622 /// use burn_tensor::{Tensor, Int};
1623 ///
1624 /// fn example<B: Backend>() {
1625 /// let device = B::Device::default();
1626 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [4.0, 5.0, 6.0]], &device);
1627 /// let indices = Tensor::<B, 1, Int>::from_data([0], &device);
1628 /// let tensor = tensor.select(0, indices);
1629 /// println!("{tensor}");
1630 /// // [[1.0, -2.0, 3.0]]
1631 /// }
1632 /// ```
1633 pub fn select(self, dim: impl AsIndex, indices: Tensor<B, 1, Int>) -> Self {
1634 let dim = dim.expect_dim_index(D);
1635 check!(TensorCheck::select::<D>(dim));
1636 Self::new(K::select(self.primitive, dim, indices.primitive))
1637 }
1638
1639 /// Assign the selected elements along the given dimension corresponding to the given indices
1640 /// from the value tensor to the original tensor using sum reduction.
1641 ///
1642 /// # Note
1643 /// For booleans, the sum operator is logical or.
1644 ///
1645 /// # Arguments
1646 ///
1647 /// * `dim` - The dimension along which to select. Supports negative indexing.
1648 /// * `indices` - The indices to select from the tensor.
1649 /// * `values` - The values to assign to the selected indices.
1650 /// * `update` - The operation used to update the existing values at the indexed positions (e.g., add).
1651 ///
1652 /// # Example
1653 ///
1654 /// Example using a 3D tensor:
1655 ///
1656 /// `input[indices[i], j, k] += values[i, j, k]; // dim = 0`
1657 /// `input[i, indices[j], k] += values[i, j, k]; // dim = 1`
1658 /// `input[i, j, indices[k]] += values[i, j, k]; // dim = 2`
1659 /// `input[i, j, indices[k]] += values[i, j, k]; // dim = -1 (same as dim = 2)`
1660 ///
1661 /// # Warning
1662 ///
1663 /// Not all backends have runtime bound checks for the indices, so make sure they are valid.
1664 /// Otherwise, out of bounds indices could lead to unexpected results instead of panicking.
1665 pub fn select_assign(
1666 self,
1667 dim: impl AsIndex,
1668 indices: Tensor<B, 1, Int>,
1669 values: Tensor<B, D, K>,
1670 update: IndexingUpdateOp,
1671 ) -> Self {
1672 let dim = dim.expect_dim_index(D);
1673 check!(TensorCheck::select_assign::<D>(
1674 dim,
1675 &indices.shape(),
1676 &values.shape()
1677 ));
1678
1679 Self::new(K::select_assign(
1680 self.primitive,
1681 dim,
1682 indices.primitive,
1683 values.primitive,
1684 update,
1685 ))
1686 }
1687
1688 /// Update the given tensor with the value tensor where the mask is true.
1689 ///
1690 /// This is similar to [mask_fill](Tensor::mask_fill), however the value is a tensor instead of
1691 /// a scalar.
1692 ///
1693 /// # Example
1694 ///
1695 /// ```rust
1696 /// use burn_tensor::backend::Backend;
1697 /// use burn_tensor::{Tensor, Shape, Bool};
1698 ///
1699 /// fn example<B: Backend>() {
1700 /// let device = B::Device::default();
1701 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
1702 /// let mask = Tensor::<B, 2, Bool>::from_data([[true, false, true], [false, true, false]], &device);
1703 /// let value = Tensor::<B, 2>::from_data([[2.0, 3.0, 4.0], [1.0, 2.0, 3.0]], &device);
1704 /// let tensor = tensor.mask_where(mask, value);
1705 /// println!("{tensor}");
1706 /// // [[2.0, -2.0, 4.0], [5.0, 2.0, 6.0]]
1707 /// }
1708 /// ```
1709 pub fn mask_where(self, mask: Tensor<B, D, Bool>, value: Self) -> Self {
1710 Self::new(K::mask_where(
1711 self.primitive,
1712 mask.primitive,
1713 value.primitive,
1714 ))
1715 }
1716
1717 /// Update the given tensor with the value where the mask is true.
1718 ///
1719 /// This is similar to [mask_where](Tensor::mask_where), however the value is a scalar instead of
1720 /// a tensor.
1721 ///
1722 /// # Example
1723 ///
1724 /// ```rust
1725 /// use burn_tensor::backend::Backend;
1726 /// use burn_tensor::{Tensor, Shape, Bool};
1727 ///
1728 /// fn example<B: Backend>() {
1729 /// let device = B::Device::default();
1730 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
1731 /// let mask = Tensor::<B, 2, Bool>::from_data([[true, false, true], [false, true, false]], &device);
1732 /// let tensor = tensor.mask_fill(mask, 3.0);
1733 /// println!("{tensor}");
1734 /// // [[3.0, -2.0, 3.0], [5.0, 3.0, 6.0]]
1735 /// }
1736 /// ```
1737 pub fn mask_fill<E: ElementConversion>(self, mask: Tensor<B, D, Bool>, value: E) -> Self {
1738 let value = Scalar::new(value, &self.dtype());
1739 Self::new(K::mask_fill(self.primitive, mask.primitive, value))
1740 }
1741
1742 /// Gather tensor elements corresponding to the given indices from the specified dim.
1743 ///
1744 /// Example using a 3D tensor:
1745 ///
1746 /// `output[i, j, k] = input[indices[i, j, k], j, k]; // dim = 0`
1747 /// `output[i, j, k] = input[i, indices[i, j, k], k]; // dim = 1`
1748 /// `output[i, j, k] = input[i, j, indices[i, j, k]]; // dim = 2`
1749 ///
1750 /// # Notes
1751 ///
1752 /// The index tensor should have the same shape as the original tensor except for the dim
1753 /// specified.
1754 ///
1755 /// # Warning
1756 /// Not all backends have runtime bound checks for the indices, so make sure the they are valid.
1757 /// Otherwise, out of bounds indices could lead to unexpected results instead of panicking.
1758 pub fn gather(self, dim: usize, indices: Tensor<B, D, Int>) -> Self {
1759 check!(TensorCheck::gather::<D>(
1760 dim,
1761 &self.shape(),
1762 &indices.shape()
1763 ));
1764
1765 Self::new(K::gather(dim, self.primitive, indices.primitive))
1766 }
1767
1768 /// Assign the gathered elements corresponding to the given indices along the specified dimension
1769 /// from the value tensor to the original tensor using sum reduction.
1770 ///
1771 /// Example using a 3D tensor:
1772 ///
1773 /// `input[indices[i, j, k], j, k] += values[i, j, k]; // dim = 0`
1774 /// `input[i, indices[i, j, k], k] += values[i, j, k]; // dim = 1`
1775 /// `input[i, j, indices[i, j, k]] += values[i, j, k]; // dim = 2`
1776 ///
1777 /// # Arguments
1778 /// * `dim` - The axis along which to scatter elements.
1779 /// * `indices` - The indices of the elements to scatter.
1780 /// * `values` - The values to scatter into the tensor.
1781 /// * `update` - The operation used to update the existing values at the indexed positions (e.g., add).
1782 ///
1783 /// # Notes
1784 ///
1785 /// The index tensor should have the same shape as the original tensor except for the specified
1786 /// dimension. The value and index tensors should have the same shape.
1787 ///
1788 /// Other references to the input tensor will not be modified by this operation.
1789 ///
1790 /// # Warning
1791 /// Not all backends have runtime bound checks for the indices, so make sure the they are valid.
1792 /// Otherwise, out of bounds indices could lead to unexpected results instead of panicking.
1793 pub fn scatter(
1794 self,
1795 dim: usize,
1796 indices: Tensor<B, D, Int>,
1797 values: Self,
1798 update: IndexingUpdateOp,
1799 ) -> Self {
1800 check!(TensorCheck::scatter::<D>(
1801 dim,
1802 &self.shape(),
1803 &indices.shape(),
1804 &values.shape()
1805 ));
1806
1807 Self::new(K::scatter(
1808 dim,
1809 self.primitive,
1810 indices.primitive,
1811 values.primitive,
1812 update,
1813 ))
1814 }
1815
1816 /// Converts the data of the current tensor.
1817 ///
1818 /// # Note
1819 ///
1820 /// For better performance, prefer using a [Transaction](crate::Transaction) when reading multiple
1821 /// tensors at once. This may improve laziness, especially if executed on a different
1822 /// thread in native environments.
1823 pub fn into_data(self) -> TensorData {
1824 self.try_into_data().expect(
1825 "Error while reading data: use `try_into_data` instead to catch the error at runtime",
1826 )
1827 }
1828
1829 /// Converts the data of the current tensor and returns any error that might have occurred since the
1830 /// last time the device was synchronized.
1831 ///
1832 /// # Note
1833 ///
1834 /// For better performance, prefer using a [Transaction](crate::Transaction) when reading multiple
1835 /// tensors at once. This may improve laziness, especially if executed on a different
1836 /// thread in native environments.
1837 pub fn try_into_data(self) -> Result<TensorData, ExecutionError> {
1838 crate::try_read_sync(self.into_data_async()).expect(
1839 "Failed to read tensor data synchronously.
1840 This can happen on platforms that don't support blocking futures like WASM.
1841 If possible, try using into_data_async instead.",
1842 )
1843 }
1844
1845 /// Converts the data of the current tensor.
1846 ///
1847 /// # Note
1848 ///
1849 /// For better performance, prefer using a [Transaction](crate::Transaction) when reading multiple
1850 /// tensors at once. This may improve laziness, especially if executed on a different
1851 /// thread in native environments.
1852 pub fn to_data(&self) -> TensorData {
1853 self.clone().into_data()
1854 }
1855
1856 /// Returns the data of the current tensor.
1857 pub async fn into_data_async(self) -> Result<TensorData, ExecutionError> {
1858 K::into_data_async(self.primitive).await
1859 }
1860
1861 /// Returns the data of the current tensor.
1862 pub async fn to_data_async(&self) -> Result<TensorData, ExecutionError> {
1863 self.clone().into_data_async().await
1864 }
1865
1866 /// Create a tensor from the given data on the given device.
1867 pub fn from_data<T>(data: T, device: &B::Device) -> Self
1868 where
1869 T: Into<TensorData>,
1870 {
1871 let data = data.into();
1872 check!(TensorCheck::creation_ops::<D>(
1873 "From Data",
1874 data.shape.as_slice()
1875 ));
1876 Self::new(K::from_data(data, device))
1877 }
1878
1879 /// Create a tensor from the given data on the given device enforcing the given data type.
1880 pub fn from_data_dtype<T>(data: T, device: &B::Device, dtype: DType) -> Self
1881 where
1882 T: Into<TensorData>,
1883 {
1884 let data = data.into();
1885 check!(TensorCheck::creation_ops::<D>(
1886 "From Data",
1887 data.shape.as_slice()
1888 ));
1889 Self::new(K::from_data_dtype(data, device, dtype))
1890 }
1891
1892 /// Repeat the tensor along the given dimension.
1893 ///
1894 /// The output tensor has the same shape, except along the given dimension.
1895 ///
1896 /// # Arguments
1897 /// - `dim`: The dimension to repeat.
1898 /// - `times`: The number of times to repeat the tensor along the given dimension in the new tensor.
1899 ///
1900 /// # Returns
1901 ///
1902 /// A new tensor with the given dimension repeated `times` times.
1903 ///
1904 /// # Example
1905 ///
1906 /// ```rust
1907 /// use burn_tensor::backend::Backend;
1908 /// use burn_tensor::Tensor;
1909 ///
1910 /// fn example<B: Backend>() {
1911 /// let device = Default::default();
1912 /// // Create a 2D tensor with dimensions [3, 2]
1913 /// let tensor = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
1914 ///
1915 /// // Repeat the tensor along the dimension 0 twice.
1916 /// // [[3.0, 4.9], [2.0, 1.9], [4.0, 5.9], [3.0, 4.9], [2.0, 1.9], [4.0, 5.9]]
1917 /// // The resulting tensor will have dimensions [6, 2].
1918 /// let repeated = tensor.repeat_dim(0, 2);
1919 /// println!("{repeated}");
1920 /// }
1921 /// ```
1922 pub fn repeat_dim(self, dim: usize, times: usize) -> Self {
1923 if times > 0 {
1924 Self::new(K::repeat_dim(self.primitive, dim, times))
1925 } else {
1926 let shape = self.shape().repeat(dim, times).unwrap();
1927 Self::empty(shape, &self.device())
1928 }
1929 }
1930
1931 /// Repeat the tensor along the given dimensions.
1932 /// # Arguments
1933 /// - `sizes`: Borrowed slice of the number of times to repeat each dimension.
1934 ///
1935 /// # Returns
1936 ///
1937 /// A new tensor with the given dimensions repeated `times` times.
1938 ///
1939 /// # Panics
1940 ///
1941 /// If `sizes` contains more elements than the number of dimensions.
1942 ///
1943 /// # Example
1944 ///
1945 /// ```rust
1946 ///
1947 /// use burn_tensor::backend::Backend;
1948 /// use burn_tensor::Tensor;
1949 ///
1950 /// fn example<B: Backend>() {
1951 /// let device = Default::default();
1952 /// // Create a 2D tensor with dimensions [3, 2]
1953 /// let tensor = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
1954 ///
1955 /// // Repeat the tensor along the dimension 0 twice and the dimension 0 once.
1956 /// // [[3.0, 4.9], [2.0, 1.9], [4.0, 5.9], [3.0, 4.9], [2.0, 1.9], [4.0, 5.9]]
1957 /// // The resulting tensor will have dimensions [6, 2].
1958 /// let repeated = tensor.repeat(&[2, 1]);
1959 /// }
1960 /// ```
1961 pub fn repeat(self, sizes: &[usize]) -> Self {
1962 if sizes.contains(&0) {
1963 let mut shape = self.shape();
1964 for (dim, ×) in sizes.iter().enumerate() {
1965 shape = shape.repeat(dim, times).unwrap();
1966 }
1967
1968 return Self::empty(shape, &self.device());
1969 }
1970
1971 let mut tensor = self;
1972 for (dim, ×) in sizes.iter().enumerate() {
1973 if times > 1 {
1974 tensor = tensor.repeat_dim(dim, times);
1975 }
1976 }
1977 tensor
1978 }
1979
1980 /// Applies element-wise equal comparison.
1981 ///
1982 /// # Returns
1983 /// A boolean tensor that is `true` where input is equal to `other` and `false` elsewhere.
1984 ///
1985 /// # Panics
1986 ///
1987 /// If the two tensors don't have the same shape.
1988 ///
1989 /// # Example
1990 ///
1991 /// ```rust
1992 /// use burn_tensor::backend::Backend;
1993 /// use burn_tensor::Tensor;
1994 ///
1995 /// fn example<B: Backend>() {
1996 /// let device = Default::default();
1997 /// let t1 = Tensor::<B, 2>::from_data([[2.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
1998 /// let t2 = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
1999 /// // Compare the elements of the two 2D tensors with dimensions [3, 2].
2000 /// // [[false, true], [true, true], [true, true]]
2001 /// let equal = t1.equal(t2);
2002 /// println!("{equal}");
2003 /// }
2004 /// ```
2005 pub fn equal(self, other: Self) -> Tensor<B, D, Bool> {
2006 check!(TensorCheck::binary_ops_ew("Equal", &self, &other));
2007 Tensor::new(K::equal(self.primitive, other.primitive))
2008 }
2009
2010 /// Applies element-wise non-equality comparison.
2011 ///
2012 /// # Returns
2013 /// A boolean tensor that is `true` where input is not equal to `other` and `false` elsewhere.
2014 ///
2015 /// # Panics
2016 ///
2017 /// If the two tensors don't have the same shape.
2018 ///
2019 /// # Example
2020 ///
2021 /// ```rust
2022 /// use burn_tensor::backend::Backend;
2023 /// use burn_tensor::Tensor;
2024 ///
2025 /// fn example<B: Backend>() {
2026 /// let device = Default::default();
2027 /// let t1 = Tensor::<B, 2>::from_data([[2.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
2028 /// let t2 = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
2029 /// // Compare the elements of the two 2D tensors for inequality.
2030 /// // [[true, false], [false, false], [false, false]]
2031 /// let not_equal = t1.not_equal(t2);
2032 /// println!("{not_equal}");
2033 /// }
2034 /// ```
2035 pub fn not_equal(self, other: Self) -> Tensor<B, D, Bool> {
2036 check!(TensorCheck::binary_ops_ew("NotEqual", &self, &other));
2037 Tensor::new(K::not_equal(self.primitive, other.primitive))
2038 }
2039
2040 /// Applies element wise equal comparison and returns a boolean tensor.
2041 ///
2042 /// # Arguments
2043 ///
2044 /// * `other` - The element to compare.
2045 ///
2046 /// # Example
2047 ///
2048 /// ```rust
2049 /// use burn_tensor::backend::Backend;
2050 /// use burn_tensor::{Tensor, Shape};
2051 ///
2052 /// fn example<B: Backend>() {
2053 /// let device = B::Device::default();
2054 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
2055 /// let tensor = tensor.equal_elem(3.0);
2056 /// println!("{tensor}");
2057 /// // [[false, false, true], [false, false, false]]
2058 /// }
2059 /// ```
2060 pub fn equal_elem<E: Element>(self, other: E) -> Tensor<B, D, Bool> {
2061 let other = Scalar::new(other, &self.dtype());
2062 Tensor::new(K::equal_elem(self.primitive, other))
2063 }
2064
2065 /// Applies element wise non-equality comparison and returns a boolean tensor.
2066 ///
2067 /// # Arguments
2068 ///
2069 /// * `other` - The element to compare.
2070 ///
2071 /// # Example
2072 ///
2073 /// ```rust
2074 /// use burn_tensor::backend::Backend;
2075 /// use burn_tensor::{Tensor, Shape};
2076 ///
2077 /// fn example<B: Backend>() {
2078 /// let device = B::Device::default();
2079 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
2080 /// let tensor = tensor.not_equal_elem(3.0);
2081 /// println!("{tensor}");
2082 /// // [[true, true, false], [true, true, true]]
2083 /// }
2084 /// ```
2085 pub fn not_equal_elem<E: Element>(self, other: E) -> Tensor<B, D, Bool> {
2086 let other = Scalar::new(other, &self.dtype());
2087 Tensor::new(K::not_equal_elem(self.primitive, other))
2088 }
2089
2090 /// Concatenates all tensors into a new one along the given dimension.
2091 ///
2092 /// # Panics
2093 ///
2094 /// - If `dim` is higher than the rank.
2095 /// - If `tensors` is an empty vector.
2096 /// - If all tensors don't have the same shape (the dimension `dim` is ignored).
2097 ///
2098 /// # Example
2099 ///
2100 /// ```rust
2101 /// use burn_tensor::backend::Backend;
2102 /// use burn_tensor::Tensor;
2103 ///
2104 /// fn example<B: Backend>() {
2105 /// let device = Default::default();
2106 /// let t1 = Tensor::<B, 2>::from_data([[3.0, 4.9, 2.0, 1.0], [2.0, 1.9, 3.0, 1.0]], &device);
2107 /// let t2 = Tensor::<B, 2>::from_data([[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]], &device);
2108 ///
2109 /// // Concatenate the two tensors with shapes [2, 4] and [2, 3] along the dimension 1.
2110 /// // [[3.0, 4.9, 2.0, 1.0, 4.0, 5.9, 8.0], [2.0, 1.9, 3.0, 1.0, 1.4, 5.8, 6.0]]
2111 /// // The resulting tensor will have shape [2, 7].
2112 /// let concat = Tensor::cat(vec![t1, t2], 1);
2113 /// println!("{concat}");
2114 /// }
2115 /// ```
2116 pub fn cat(tensors: Vec<Self>, dim: usize) -> Self {
2117 check!(TensorCheck::cat(&tensors, dim));
2118
2119 // Filter out tensors with size 0 along the concatenation dimension.
2120 // Empty tensors don't contribute to the output and would cause issues
2121 // in backend implementations (e.g., division by zero in slice_assign).
2122 // Safety: TensorCheck::cat ensures tensors is non-empty
2123 let first_tensor = tensors.first().unwrap();
2124 let device = first_tensor.device();
2125 let mut shape = first_tensor.shape();
2126
2127 let non_empty_primitives: Vec<_> = tensors
2128 .into_iter()
2129 .filter(|t| t.shape()[dim] > 0)
2130 .map(|t| t.primitive)
2131 .collect();
2132
2133 // If all tensors were empty, return an empty tensor with size 0 on concat dim
2134 if non_empty_primitives.is_empty() {
2135 shape[dim] = 0;
2136 return Self::empty(shape, &device);
2137 }
2138
2139 Self::new(K::cat(non_empty_primitives, dim))
2140 }
2141
2142 /// Concatenates all tensors into a new one along a new dimension.
2143 ///
2144 /// # Panics
2145 ///
2146 /// - If all tensors don't have the same shape.
2147 /// - If given dimension is not with range of 0..D2
2148 ///
2149 /// # Example
2150 ///
2151 /// ```rust
2152 /// use burn_tensor::backend::Backend;
2153 /// use burn_tensor::Tensor;
2154 ///
2155 /// fn example<B: Backend>() {
2156 /// let device = Default::default();
2157 /// let t1 = Tensor::<B, 2>::from_data([[3.0, 4.9, 2.0], [2.0, 1.9, 3.0]], &device);
2158 /// let t2 = Tensor::<B, 2>::from_data([[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]], &device);
2159 /// let t3 = Tensor::<B, 2>::from_data([[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]], &device);
2160 ///
2161 /// // Concatenate the three tensors with shape [2, 3] along a new dimension, 0.
2162 /// // [[[3.0, 4.9, 2.0], [2.0, 1.9, 3.0]],
2163 /// // [[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]],
2164 /// // [[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]]]
2165 /// // The resulting tensor will have shape [3, 2, 3].
2166 /// let stacked= Tensor::stack::<3>(vec![t1, t2, t3], 0);
2167 /// println!("{stacked}");
2168 /// }
2169 /// ```
2170 pub fn stack<const D2: usize>(tensors: Vec<Tensor<B, D, K>>, dim: usize) -> Tensor<B, D2, K> {
2171 check!(TensorCheck::stack::<B, D, K, D2>(&tensors, dim));
2172 let tensors = tensors.into_iter().map(|t| t.unsqueeze_dim(dim)).collect();
2173 Tensor::<B, D2, K>::cat(tensors, dim)
2174 }
2175
2176 /// Iterate over slices of tensors alongside a given dimension.
2177 ///
2178 /// # Panics
2179 ///
2180 /// If given dimension is greater than or equal to tensor rank.
2181 ///
2182 /// # Returns
2183 ///
2184 /// A tensor iterator.
2185 ///
2186 /// # Example
2187 ///
2188 /// ```rust
2189 /// use burn_tensor::backend::Backend;
2190 /// use burn_tensor::Tensor;
2191 /// fn example<B: Backend>() {
2192 /// let device = Default::default();
2193 /// let tensor = Tensor::<B,2>::from_data([[3.0, 4.9, 2.0], [2.0, 1.9, 3.0]], &device);
2194 /// // Given a 2D tensor with dimensions [2, 3], iterate over slices of tensors along the dimension 0.
2195 /// let iter = tensor.iter_dim(0);
2196 /// for (i,tensor) in iter.enumerate() {
2197 /// println!("Tensor {}: {}", i, tensor);
2198 /// // Tensor 0: Tensor { data: [[3.0, 4.9, 2.0]], ... }
2199 /// // Tensor 1: Tensor { data: [[2.0, 1.9, 3.0]], ... }
2200 /// }
2201 /// }
2202 /// ```
2203 pub fn iter_dim(self, dim: usize) -> DimIter<B, D, K> {
2204 check!(TensorCheck::dim_ops::<D>("iter_dim", dim));
2205 DimIter::new(self, dim)
2206 }
2207
2208 /// Returns a new tensor with the given dimension narrowed to the given range.
2209 ///
2210 /// # Panics
2211 ///
2212 /// - If the dimension is greater than the number of dimensions of the tensor.
2213 /// - If the given range exceeds the number of elements on the given dimension.
2214 ///
2215 /// # Returns
2216 ///
2217 /// A new tensor with the given dimension narrowed to the given range.
2218 ///
2219 /// # Example
2220 ///
2221 /// ```rust
2222 /// use burn_tensor::backend::Backend;
2223 /// use burn_tensor::Tensor;
2224 ///
2225 /// fn example<B: Backend>() {
2226 /// let device = Default::default();
2227 /// // Create a 2D tensor with dimensions [4, 3]
2228 /// let tensor = Tensor::<B, 2>::from_data(
2229 /// [
2230 /// [3.0, 4.9, 2.0],
2231 /// [2.0, 1.9, 3.0],
2232 /// [6.0, 1.5, 7.0],
2233 /// [3.0, 4.9, 9.0],
2234 /// ],
2235 /// &device,
2236 /// );
2237 /// // Narrow the tensor along the dimension 0, keeping 3 elements starting from index 1.
2238 /// // [[2.0, 1.9, 3.0], [6.0, 1.5, 7.0], [3.0, 4.9, 9.0]]
2239 /// // The resulting tensor will have dimensions [3, 3].
2240 /// let narrowed = tensor.narrow(0, 1, 3);
2241 /// println!("{narrowed}");
2242 /// }
2243 /// ```
2244 pub fn narrow(self, dim: usize, start: usize, length: usize) -> Self {
2245 check!(TensorCheck::dim_ops::<D>("narrow", dim));
2246 check!(TensorCheck::narrow(&self, dim, start, length));
2247 let dims = self.dims();
2248
2249 let ranges: [Range<usize>; D] = dims
2250 .iter()
2251 .enumerate()
2252 .map(|(i, d)| {
2253 if i == dim {
2254 start..(start + length)
2255 } else {
2256 0..*d
2257 }
2258 })
2259 .collect::<Vec<_>>()
2260 .try_into()
2261 .unwrap();
2262
2263 Self::slice(self, ranges)
2264 }
2265
2266 /// Attempts to split the tensor into a specified number of chunks along a given dimension.
2267 /// May return less chunks than requested if the tensor size is not divisible by the number of chunks.
2268 ///
2269 /// When the given dimension is evenly divisible by the number of chunks, the chunks will be of equal size.
2270 /// Otherwise all chunks will be of equal size except for the last one.
2271 ///
2272 /// # Panics
2273 ///
2274 /// If the dimension is greater than the number of dimensions of the tensor.
2275 ///
2276 /// # Returns
2277 /// A vector of tensors.
2278 ///
2279 /// # Example
2280 ///
2281 /// ```rust
2282 /// use burn_tensor::backend::Backend;
2283 /// use burn_tensor::Tensor;
2284 ///
2285 /// fn example<B: Backend>() {
2286 /// let device = Default::default();
2287 /// // Create a 2D tensor with dimensions [4, 3]
2288 /// let tensor = Tensor::<B, 2>::from_data(
2289 /// [
2290 /// [3.0, 4.9, 2.0],
2291 /// [2.0, 1.9, 3.0],
2292 /// [6.0, 1.5, 7.0],
2293 /// [3.0, 4.9, 9.0],
2294 /// ],
2295 /// &device,
2296 /// );
2297 /// // Split the tensor along the dimension 1 into 2 chunks.
2298 /// // The first chuck will have shape [4, 2]:
2299 /// // [[3.0, 4.9], [2.0, 1.9], [6.0, 1.5], [3.0, 4.9]]
2300 /// // The second chunk will have shape [4, 1]:
2301 /// // [[2.0], [3.0], [7.0], [9.0]]
2302 /// let chunks = tensor.chunk(2, 1);
2303 /// println!("{chunks:?}");
2304 /// }
2305 /// ```
2306 pub fn chunk(self, chunks: usize, dim: usize) -> Vec<Self> {
2307 check!(TensorCheck::dim_ops::<D>("chunk", dim));
2308 let size = self.shape()[dim];
2309 if size < chunks {
2310 return (0..size)
2311 .map(|i| Self::narrow(self.clone(), dim, i, 1))
2312 .collect();
2313 }
2314
2315 let mut tensors = Vec::with_capacity(chunks);
2316 let mut sum_chunk_size = 0;
2317 if size.is_multiple_of(chunks) {
2318 let chunk_size = size / chunks;
2319 for _ in 0..chunks {
2320 tensors.push(Self::narrow(self.clone(), dim, sum_chunk_size, chunk_size));
2321 sum_chunk_size += chunk_size;
2322 }
2323 } else {
2324 let chunk_size = (size / chunks) + 1; // assumes not divisible
2325 for _ in 0..chunks - 1 {
2326 tensors.push(Self::narrow(self.clone(), dim, sum_chunk_size, chunk_size));
2327 sum_chunk_size += chunk_size;
2328 }
2329 let remainder = size % chunk_size;
2330 tensors.push(Self::narrow(self.clone(), dim, sum_chunk_size, remainder));
2331 }
2332
2333 tensors
2334 }
2335
2336 /// Splits the tensor into chunks of a specified size along a given dimension.
2337 /// Each chunk is a view of the original tensor.
2338 ///
2339 /// If the tensor size along the given dimension is not divisible by `split_size`,
2340 /// then the last chunk will be smaller.
2341 ///
2342 /// # Panics
2343 ///
2344 /// If the specified dimension to split along is greater than the number of dimensions of the tensor.
2345 ///
2346 /// # Returns
2347 ///
2348 /// A vector of tensors.
2349 ///
2350 /// # Example
2351 /// ```rust
2352 /// use burn_tensor::backend::Backend;
2353 /// use burn_tensor::Tensor;
2354 ///
2355 /// fn example<B: Backend>() {
2356 /// let device = Default::default();
2357 /// // Create a 1D tensor with 5 elements
2358 /// let tensor = Tensor::<B, 1>::from_data([0.0, 1.0, 2.0, 3.0, 4.0], &device);
2359 /// // Split the tensor into chunks of size 2 along dimension 0
2360 /// let chunks = tensor.split(2, 0);
2361 /// // The result is a vector of tensors:
2362 /// // [Tensor([0.0, 1.0]), Tensor([2.0, 3.0]), Tensor([4.0])]
2363 /// println!("{:?}", chunks);
2364 /// }
2365 /// ```
2366 pub fn split(self, split_size: usize, dim: usize) -> Vec<Self> {
2367 check!(TensorCheck::split::<D>(&self.shape(), split_size, dim));
2368 let size = self.shape()[dim];
2369 let mut tensors = Vec::new();
2370
2371 let mut start = 0;
2372 while start < size {
2373 let length = usize::min(split_size, size - start);
2374 tensors.push(Self::narrow(self.clone(), dim, start, length));
2375 start += length;
2376 }
2377
2378 tensors
2379 }
2380
2381 /// Splits the tensor into chunks with the specified sizes along a given dimension.
2382 /// Each chunk is a view of the original tensor.
2383 ///
2384 /// The sizes of the chunks are specified in the `split_sizes` vector. The sum of the sizes
2385 /// in `split_sizes` must equal the size of the tensor along the specified dimension.
2386 ///
2387 /// # Panics
2388 ///
2389 /// If the specified dimension to split along is greater than the number of dimensions of the tensor or
2390 /// if the sum of `dim_sizes` does not equal the size of the tensor along `dim`.
2391 ///
2392 /// # Returns
2393 ///
2394 /// A vector of tensors.
2395 ///
2396 /// # Example
2397 /// ```rust
2398 /// use burn_tensor::backend::Backend;
2399 /// use burn_tensor::Tensor;
2400 ///
2401 /// fn example<B: Backend>() {
2402 /// let device = Default::default();
2403 /// // Create a 1D tensor with 5 elements
2404 /// let tensor = Tensor::<B, 1>::from_data([0.0, 1.0, 2.0, 3.0, 4.0], &device);
2405 /// // Split the tensor into chunks with sizes [2, 3] along dimension 0
2406 /// let chunks = tensor.split_with_sizes(vec![2, 3], 0);
2407 /// // The result is a vector of tensors:
2408 /// // [Tensor([0.0, 1.0]), Tensor([2.0, 3.0, 4.0])]
2409 /// println!("{:?}", chunks);
2410 /// }
2411 /// ```
2412 pub fn split_with_sizes(self, split_sizes: Vec<usize>, dim: usize) -> Vec<Self> {
2413 check!(TensorCheck::split_with_sizes::<D>(
2414 &self.shape(),
2415 &split_sizes,
2416 dim
2417 ));
2418 let mut tensors = Vec::new();
2419
2420 let mut start = 0;
2421 for length in split_sizes {
2422 if length == 0 {
2423 continue;
2424 }
2425 tensors.push(Self::narrow(self.clone(), dim, start, length));
2426 start += length;
2427 }
2428
2429 tensors
2430 }
2431
2432 /// Tests if any element in the `tensor` evaluates to True.
2433 ///
2434 /// # Arguments
2435 ///
2436 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2437 ///
2438 /// # Returns
2439 ///
2440 /// A boolean tensor `Tensor<B, 1, Bool>` containing a single element, True if any element in the input tensor
2441 /// evaluates to True, False otherwise.
2442 ///
2443 /// # Example
2444 ///
2445 /// ```rust
2446 /// use burn_tensor::backend::Backend;
2447 /// use burn_tensor::{Tensor, Bool};
2448 ///
2449 /// fn example<B: Backend>() {
2450 /// let device = Default::default();
2451 /// let tensor = Tensor::<B,2, Bool>::from_data([[true,false,true],[false,true,false]], &device);
2452 /// let tensor_two = Tensor::<B,2, Bool>::from_data([[false,false,false],[false,false,false]], &device);
2453 ///
2454 /// // Given a 2D tensor with dimensions [2, 3], test if any element in the tensor evaluates to True.
2455 /// let any_tensor = tensor.any();
2456 /// println!("{}", any_tensor);
2457 /// // Tensor { data: [true], ... }
2458 ///
2459 /// // Given a 2D tensor with dimensions [2, 3], test if any element in the tensor evaluates to True.
2460 /// let any_tensor_two = tensor_two.any();
2461 /// println!("{}", any_tensor_two);
2462 /// // Tensor { data: [false], ... }
2463 /// }
2464 /// ```
2465 pub fn any(self) -> Tensor<B, 1, Bool> {
2466 Tensor::new(K::any(self.primitive))
2467 }
2468
2469 /// Tests if any element in the `tensor` evaluates to True along a given dimension `dim`.
2470 ///
2471 /// # Arguments
2472 ///
2473 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2474 /// * `dim` - The axis along which to test.
2475 ///
2476 /// # Returns
2477 ///
2478 /// A boolean tensor `Tensor<B, D, Bool>` with the same shape as input `tensor`, except in the `dim` axis
2479 /// where the size is 1. The elem in the `dim` axis is True if any element along this dim in the input
2480 /// evaluates to True, False otherwise.
2481 ///
2482 /// # Example
2483 ///
2484 /// ```rust
2485 /// use burn_tensor::backend::Backend;
2486 /// use burn_tensor::{Tensor, Bool};
2487 ///
2488 /// fn example<B: Backend>() {
2489 /// let device = Default::default();
2490 /// let tensor =
2491 /// Tensor::<B, 2, Bool>::from_data([[true, false, false], [false, true, false]], &device);
2492 /// // Check if any element in the tensor evaluates to True along the dimension 1.
2493 /// // [[true], [true]],
2494 /// let any_dim = tensor.clone().any_dim(1);
2495 /// println!("{any_dim}");
2496 /// }
2497 /// ```
2498 pub fn any_dim(self, dim: usize) -> Tensor<B, D, Bool> {
2499 Tensor::new(K::any_dim(self.primitive, dim))
2500 }
2501
2502 /// Tests if all elements in the `tensor` evaluate to True.
2503 ///
2504 /// # Arguments
2505 ///
2506 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2507 ///
2508 /// # Returns
2509 ///
2510 /// A boolean tensor `Tensor<B, 1, Bool>` with a single element, True if all elements in the input tensor
2511 /// evaluate to True, False otherwise.
2512 ///
2513 /// # Example
2514 ///
2515 /// ```rust
2516 /// use burn_tensor::backend::Backend;
2517 /// use burn_tensor::{Tensor, Bool};
2518 ///
2519 /// fn example<B: Backend>() {
2520 /// let device = Default::default();
2521 /// let tensor =
2522 /// Tensor::<B, 2, Bool>::from_data([[true, false, true], [true, true, true]], &device);
2523 /// // Check if all elements in the tensor evaluate to True (which is not the case).
2524 /// // [false]
2525 /// let all = tensor.all();
2526 /// println!("{all}");
2527 /// }
2528 /// ```
2529 pub fn all(self) -> Tensor<B, 1, Bool> {
2530 Tensor::new(K::all(self.primitive))
2531 }
2532
2533 /// Tests if all elements in the `tensor` evaluate to True along a given dimension `dim`.
2534 ///
2535 /// # Arguments
2536 ///
2537 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2538 /// * `dim` - The axis along which to test.
2539 ///
2540 /// # Returns
2541 ///
2542 /// A boolean tensor `Tensor<B, D, Bool>` with the same shape as input `tensor`, except in the `dim` axis
2543 /// where the size is 1. The elem in the `dim` axis is True if all elements along this dim in the input
2544 /// evaluates to True, False otherwise.
2545 ///
2546 /// # Example
2547 ///
2548 /// ```rust
2549 /// use burn_tensor::backend::Backend;
2550 /// use burn_tensor::{Tensor, Bool};
2551 ///
2552 /// fn example<B: Backend>() {
2553 /// let device = Default::default();
2554 /// let tensor =
2555 /// Tensor::<B, 2, Bool>::from_data([[true, true, false], [true, true, true]], &device);
2556 /// // Check if all elements in the tensor evaluate to True along the dimension 1.
2557 /// // [[true, true, false]]
2558 /// let all_dim = tensor.clone().all_dim(0);
2559 /// println!("{all_dim}");
2560 /// }
2561 /// ```
2562 pub fn all_dim(self, dim: usize) -> Tensor<B, D, Bool> {
2563 Tensor::new(K::all_dim(self.primitive, dim))
2564 }
2565
2566 /// Convert the tensor into a scalar.
2567 ///
2568 /// # Panics
2569 ///
2570 /// - If the tensor doesn't have one element.
2571 /// - If the backend fails to read the tensor data synchronously.
2572 ///
2573 /// # Returns
2574 ///
2575 /// The scalar value of the tensor.
2576 ///
2577 /// # Example
2578 ///
2579 /// ```rust
2580 /// use burn_tensor::backend::Backend;
2581 /// use burn_tensor::Tensor;
2582 ///
2583 /// fn example<B: Backend>() {
2584 /// let device = Default::default();
2585 /// let tensor = Tensor::<B, 2>::from_data([[3.0]], &device);
2586 /// // Convert the tensor with a single element into a scalar.
2587 /// let scalar = tensor.into_scalar();
2588 /// println!("{scalar}");
2589 /// }
2590 /// ```
2591 pub fn into_scalar(self) -> K::Elem {
2592 crate::try_read_sync(self.into_scalar_async())
2593 .expect(
2594 "Failed to read tensor data synchronously. This can happen on platforms
2595 that don't support blocking futures like WASM. Try into_scalar_async instead.",
2596 )
2597 .expect("Error while reading data: use `try_into_scalar` instead to catch the error at runtime")
2598 }
2599
2600 /// Convert the tensor into a scalar and returns any error that might have occurred since the
2601 /// last time the device was synchronized.
2602 ///
2603 /// # Panics
2604 ///
2605 /// - If the tensor doesn't have one element.
2606 /// - If the backend fails to read the tensor data synchronously.
2607 ///
2608 /// # Returns
2609 ///
2610 /// The scalar value of the tensor.
2611 pub fn try_into_scalar(self) -> Result<K::Elem, ExecutionError> {
2612 crate::try_read_sync(self.into_scalar_async()).expect(
2613 "Failed to read tensor data synchronously. This can happen on platforms
2614 that don't support blocking futures like WASM. Try into_scalar_async instead.",
2615 )
2616 }
2617
2618 /// Convert the tensor into a scalar.
2619 ///
2620 /// # Panics
2621 ///
2622 /// If the tensor doesn't have one element.
2623 pub async fn into_scalar_async(self) -> Result<K::Elem, ExecutionError> {
2624 check!(TensorCheck::into_scalar::<D>(&self.shape()));
2625
2626 Ok(self.into_data_async().await?.iter().next().unwrap())
2627 }
2628
2629 /// Broadcast the tensor to the given shape.
2630 ///
2631 /// Only singleton dimensions can be expanded to a larger size. Other dimensions must have the same size
2632 /// (which can be inferred with `-1`).
2633 ///
2634 /// # Arguments
2635 ///
2636 /// * `shape` - The shape to broadcast the tensor to.
2637 /// Can contain -1 for dimensions that should be inferred.
2638 /// The number of elements in the shape must be greater or equal as
2639 /// the number of dimensions of the tensor.
2640 ///
2641 /// # Panics
2642 ///
2643 /// If the tensor cannot be broadcasted to the given shape.
2644 ///
2645 /// # Returns
2646 ///
2647 /// A new tensor with the given shape.
2648 ///
2649 /// # Example
2650 ///
2651 /// ```rust
2652 /// use burn_tensor::backend::Backend;
2653 /// use burn_tensor::Tensor;
2654 ///
2655 /// fn example<B: Backend>() {
2656 /// let device = Default::default();
2657 /// // Create a 2D tensor with dimensions [3, 1]
2658 /// let tensor = Tensor::<B, 2>::from_data([[1.], [2.], [3.]], &device);
2659 /// // Expand the tensor to a new shape [3, 4]
2660 /// // [[1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0]]
2661 /// let expanded = tensor.expand([3, 4]);
2662 /// println!("{}", expanded);
2663 /// }
2664 /// ```
2665 pub fn expand<const D2: usize, S: BroadcastArgs<D, D2>>(self, shape: S) -> Tensor<B, D2, K> {
2666 let shape = shape.into_shape(&self.shape());
2667 check!(TensorCheck::expand::<D, D2>(
2668 "expand",
2669 &self.shape(),
2670 &shape,
2671 ));
2672
2673 Tensor::<B, D2, K>::new(K::expand(self.primitive, shape))
2674 }
2675
2676 /// Unfold windows along a dimension.
2677 ///
2678 /// Returns a view of the tensor with all complete windows of size `size` in dimension `dim`;
2679 /// where windows are advanced by `step` at each index.
2680 ///
2681 /// The number of windows is `max(0, (shape[dim] - size).ceil_div(step))`.
2682 ///
2683 /// The new view will have the unfolded dimension replaced by two dimensions;
2684 /// one in the position of the original dimension, with size equal to the number of windows,
2685 /// and one appended to the right-most position, with size equal to `size`.
2686 ///
2687 /// # Warning
2688 ///
2689 /// For the `ndarray` backend; this is not a view but a copy
2690 /// with duplicated data.
2691 ///
2692 /// # Arguments
2693 ///
2694 /// * `dim` - the dimension to unfold.
2695 /// * `size` - the size of each unfolded window.
2696 /// * `step` - the step between each window.
2697 ///
2698 /// # Returns
2699 ///
2700 /// A tensor view with the shape ``[pre=..., windows, post=..., size]``.
2701 pub fn unfold<const D2: usize, I: AsIndex>(
2702 self,
2703 dim: I,
2704 size: usize,
2705 step: usize,
2706 ) -> Tensor<B, D2, K> {
2707 let dim = dim.expect_dim_index(D);
2708 check!(TensorCheck::unfold::<D, D2>(
2709 "unfold",
2710 &self.shape(),
2711 dim,
2712 size,
2713 step,
2714 ));
2715 Tensor::<B, D2, K>::new(K::unfold(self.primitive, dim, size, step))
2716 }
2717}
2718
2719/// Iterator given by (Tensor::iter_dim).
2720pub struct DimIter<B, const D: usize, K>
2721where
2722 B: Backend,
2723 K: BasicOps<B>,
2724{
2725 start: usize,
2726 end: usize,
2727 dim: usize,
2728 ranges: [Range<usize>; D],
2729 tensor: Tensor<B, D, K>,
2730}
2731
2732impl<B: Backend, const D: usize, K: BasicOps<B>> Iterator for DimIter<B, D, K> {
2733 type Item = Tensor<B, D, K>;
2734
2735 fn next(&mut self) -> Option<Self::Item> {
2736 if self.start >= self.end {
2737 return None;
2738 }
2739
2740 let mut ranges = self.ranges.clone();
2741 ranges[self.dim] = self.start..(self.start + 1);
2742
2743 let slice = self.tensor.clone().slice(ranges);
2744 self.start += 1;
2745
2746 Some(slice)
2747 }
2748}
2749
2750impl<B: Backend, const D: usize, K: BasicOps<B>> DoubleEndedIterator for DimIter<B, D, K> {
2751 fn next_back(&mut self) -> Option<Self::Item> {
2752 if self.start >= self.end {
2753 return None;
2754 }
2755
2756 let mut ranges = self.ranges.clone();
2757 ranges[self.dim] = (self.end - 1)..self.end;
2758
2759 let slice = self.tensor.clone().slice(ranges);
2760 self.end = self.end.saturating_sub(1);
2761
2762 Some(slice)
2763 }
2764}
2765
2766impl<B: Backend, const D: usize, K: BasicOps<B>> DimIter<B, D, K> {
2767 fn new(tensor: Tensor<B, D, K>, dim: usize) -> Self {
2768 let dims = tensor.dims();
2769 let ranges = dims
2770 .iter()
2771 .map(|&dim| 0..dim)
2772 .collect::<Vec<Range<usize>>>();
2773 let ranges: [Range<usize>; D] = ranges.try_into().unwrap();
2774 Self {
2775 end: dims[dim],
2776 ranges,
2777 start: 0,
2778 dim,
2779 tensor,
2780 }
2781 }
2782}
2783
2784impl<B, const D: usize, K> Tensor<B, D, K>
2785where
2786 B: Backend,
2787 K: BasicOps<B>,
2788 <K as BasicOps<B>>::Elem: Debug,
2789{
2790 #[inline]
2791 fn push_newline_indent(acc: &mut String, indent: usize) {
2792 acc.push('\n');
2793 for _ in 0..indent {
2794 acc.push(' ');
2795 }
2796 }
2797 fn fmt_inner_tensor(
2798 &self,
2799 acc: &mut String,
2800 depth: usize,
2801 multi_index: &mut [usize],
2802 range: (usize, usize),
2803 precision: Option<usize>,
2804 ) {
2805 let (start, end) = range;
2806 for i in start..end {
2807 if i > 0 {
2808 acc.push_str(", ");
2809 }
2810 multi_index[depth] = i;
2811 let range: [Range<usize>; D] =
2812 core::array::from_fn(|i| multi_index[i]..multi_index[i] + 1);
2813
2814 let data = burn_std::reader::try_read_sync(self.clone().slice(range).into_data_async());
2815
2816 if let Some(Ok(data)) = data {
2817 let elem = data.iter::<<K as BasicOps<B>>::Elem>().next().unwrap();
2818 match (precision, K::name()) {
2819 (Some(p), "Float") => acc.push_str(&format!("{elem:.p$}")),
2820 (_, "Bool") => acc.push_str(&format!("{}", elem.to_bool())),
2821 _ => acc.push_str(&format!("{elem:?}")),
2822 }
2823 } else {
2824 acc.push_str("<Tensor data not available>");
2825 }
2826 }
2827 }
2828
2829 fn fmt_outer_tensor(
2830 &self,
2831 acc: &mut String,
2832 depth: usize,
2833 multi_index: &mut [usize],
2834 print_options: &PrintOptions,
2835 summarize: bool,
2836 range: (usize, usize),
2837 ) {
2838 let (start, end) = range;
2839 for i in start..end {
2840 if i > start {
2841 acc.push(',');
2842 Self::push_newline_indent(acc, depth + 1);
2843 }
2844 acc.push('[');
2845 multi_index[depth] = i;
2846 self.display_recursive(acc, depth + 1, multi_index, print_options, summarize);
2847 acc.push(']');
2848 }
2849 }
2850
2851 /// Recursively formats the tensor data for display and appends it to the provided accumulator string.
2852 ///
2853 /// This function is designed to work with tensors of any dimensionality.
2854 /// It traverses the tensor dimensions recursively, converting the elements
2855 /// to strings and appending them to the accumulator string with the
2856 /// appropriate formatting.
2857 ///
2858 /// # Arguments
2859 ///
2860 /// * `acc` - A mutable reference to a `String` used as an accumulator for the formatted output.
2861 /// * `depth` - The current depth of the tensor dimensions being processed.
2862 /// * `multi_index` - A mutable slice of `usize` representing the current indices in each dimension.
2863 fn display_recursive(
2864 &self,
2865 acc: &mut String,
2866 depth: usize,
2867 multi_index: &mut [usize],
2868 print_options: &PrintOptions,
2869 summarize: bool,
2870 ) {
2871 let edge_items = print_options.edge_items;
2872
2873 if depth == 0 {
2874 acc.push('[');
2875 }
2876
2877 if depth == self.dims().len() - 1 {
2878 // if we are at the innermost dimension, just push its elements into the accumulator
2879 if summarize && self.dims()[depth] > 2 * edge_items {
2880 // print the starting `edge_items` elements
2881 self.fmt_inner_tensor(
2882 acc,
2883 depth,
2884 multi_index,
2885 (0, edge_items),
2886 print_options.precision,
2887 );
2888 acc.push_str(", ...");
2889 // print the last `edge_items` elements
2890 self.fmt_inner_tensor(
2891 acc,
2892 depth,
2893 multi_index,
2894 (self.dims()[depth] - edge_items, self.dims()[depth]),
2895 print_options.precision,
2896 );
2897 } else {
2898 // print all the elements
2899 self.fmt_inner_tensor(
2900 acc,
2901 depth,
2902 multi_index,
2903 (0, self.dims()[depth]),
2904 print_options.precision,
2905 );
2906 }
2907 } else {
2908 // otherwise, iterate through the current dimension and recursively display the inner tensors
2909 if summarize && self.dims()[depth] > 2 * edge_items {
2910 self.fmt_outer_tensor(
2911 acc,
2912 depth,
2913 multi_index,
2914 print_options,
2915 summarize,
2916 (0, edge_items),
2917 );
2918
2919 acc.push(',');
2920 Self::push_newline_indent(acc, depth + 1);
2921 acc.push_str("...");
2922 Self::push_newline_indent(acc, depth + 1);
2923
2924 self.fmt_outer_tensor(
2925 acc,
2926 depth,
2927 multi_index,
2928 print_options,
2929 summarize,
2930 (self.dims()[depth] - edge_items, self.dims()[depth]),
2931 );
2932 } else {
2933 self.fmt_outer_tensor(
2934 acc,
2935 depth,
2936 multi_index,
2937 print_options,
2938 summarize,
2939 (0, self.dims()[depth]),
2940 );
2941 }
2942 }
2943
2944 if depth == 0 {
2945 acc.push(']');
2946 }
2947 }
2948}
2949
2950#[derive(Clone, Debug)]
2951/// Options for Tensor pretty printing
2952pub struct PrintOptions {
2953 /// number of elements to start summarizing tensor
2954 pub threshold: usize,
2955
2956 /// number of starting elements and ending elements to display
2957 pub edge_items: usize,
2958
2959 /// Precision for floating point numbers
2960 pub precision: Option<usize>,
2961}
2962
2963static PRINT_OPTS: RwLock<PrintOptions> = RwLock::new(PrintOptions::const_default());
2964
2965impl PrintOptions {
2966 /// Print options with default values
2967 pub const fn const_default() -> Self {
2968 Self {
2969 threshold: 1000,
2970 edge_items: 3,
2971 precision: None,
2972 }
2973 }
2974}
2975
2976impl Default for PrintOptions {
2977 fn default() -> Self {
2978 Self::const_default()
2979 }
2980}
2981
2982/// Set print options
2983pub fn set_print_options(options: PrintOptions) {
2984 let mut print_opts = PRINT_OPTS.write().unwrap();
2985 *print_opts = options;
2986}
2987
2988/// Pretty print tensors
2989impl<B, const D: usize, K> core::fmt::Display for Tensor<B, D, K>
2990where
2991 B: Backend,
2992 B::IntElem: core::fmt::Display,
2993 K: BasicOps<B>,
2994 <K as BasicOps<B>>::Elem: Debug,
2995{
2996 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2997 writeln!(f, "Tensor {{")?;
2998
2999 {
3000 // Do not lock the mutex for the whole function
3001 let mut po = { PRINT_OPTS.read().unwrap().clone() };
3002
3003 // Override the precision if it is set from the formatter
3004 // This will be possible when the tensor is printed using the `{:.*}` syntax
3005 if let Some(precision) = f.precision() {
3006 po.precision = Some(precision);
3007 }
3008
3009 let mut acc = String::new();
3010 let mut multi_index = vec![0; D];
3011 let summarize = self.shape().num_elements() > po.threshold;
3012
3013 self.display_recursive(&mut acc, 0, &mut multi_index, &po, summarize);
3014
3015 writeln!(f, " data:")?;
3016 write!(f, "{acc}")?;
3017 writeln!(f, ",")?;
3018 }
3019
3020 writeln!(f, " shape: {:?},", self.dims())?;
3021 writeln!(f, " device: {:?},", self.device())?;
3022 writeln!(f, " backend: {:?},", B::name(&self.device()))?;
3023 writeln!(f, " kind: {:?},", K::name())?;
3024
3025 let dtype = self.primitive.dtype();
3026
3027 writeln!(f, " dtype: {:?},", dtype.name())?;
3028 write!(f, "}}")
3029 }
3030}
3031
3032/// Trait used for movedim arguments
3033pub trait MovedimArgs {
3034 /// Converts into a set of dimensions `Vec<usize>` for the `tensor.movedim()` function
3035 fn into_dim_vec<const D: usize>(self) -> Vec<usize>;
3036}
3037
3038impl MovedimArgs for Vec<i32> {
3039 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3040 let set = self
3041 .iter()
3042 .map(|&dim| {
3043 if dim < 0 {
3044 (D as i32 + dim) as usize
3045 } else {
3046 dim as usize
3047 }
3048 })
3049 .collect::<Vec<usize>>();
3050 check!(TensorCheck::movedim_args_vec::<D>(&set));
3051
3052 set
3053 }
3054}
3055
3056impl MovedimArgs for Vec<usize> {
3057 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3058 check!(TensorCheck::movedim_args_vec::<D>(&self));
3059 self
3060 }
3061}
3062
3063impl MovedimArgs for usize {
3064 #[allow(clippy::vec_init_then_push)]
3065 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3066 check!(TensorCheck::movedim_args_usize::<D>(self));
3067
3068 let mut set = Vec::with_capacity(1);
3069 set.push(self);
3070
3071 set
3072 }
3073}
3074
3075impl MovedimArgs for i32 {
3076 #[allow(clippy::vec_init_then_push)]
3077 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3078 check!(TensorCheck::movedim_args_i32::<D>(self));
3079
3080 let dim = if self < 0 {
3081 (D as i32 + self) as usize
3082 } else {
3083 self as usize
3084 };
3085
3086 let mut set = Vec::with_capacity(1);
3087 set.push(dim);
3088
3089 set
3090 }
3091}
3092
3093/// Trait used for reshape arguments.
3094pub trait ReshapeArgs<const D2: usize>: Debug {
3095 /// Converts to a shape.
3096 fn into_shape<const D: usize>(self, source: Shape) -> Shape;
3097}
3098
3099impl<const D2: usize, I: AsIndex> ReshapeArgs<D2> for [I; D2] {
3100 fn into_shape<const D: usize>(self, source: Shape) -> Shape {
3101 unwrap_shape_reshape(source.reshape(self))
3102 }
3103}
3104
3105impl<const D2: usize> ReshapeArgs<D2> for Shape {
3106 fn into_shape<const D: usize>(self, source: Shape) -> Shape {
3107 unwrap_shape_reshape(source.reshape(self))
3108 }
3109}
3110
3111/// Trait used for broadcast arguments.
3112pub trait BroadcastArgs<const D1: usize, const D2: usize> {
3113 /// Converts to a shape.
3114 fn into_shape(self, shape: &Shape) -> Shape;
3115}
3116
3117impl<const D1: usize, const D2: usize> BroadcastArgs<D1, D2> for Shape {
3118 fn into_shape(self, _shape: &Shape) -> Shape {
3119 self
3120 }
3121}
3122
3123impl<const D1: usize, const D2: usize, E: AsIndex> BroadcastArgs<D1, D2> for [E; D2] {
3124 // Passing -1 as the size for a dimension means not changing the size of that dimension.
3125 fn into_shape(self, shape: &Shape) -> Shape {
3126 if self.len() < shape.num_dims() {
3127 panic!("Broadcast arguments must be greater than the number of dimensions");
3128 }
3129
3130 // Zip the two shapes in reverse order and replace -1 with the actual dimension value.
3131 let new_shape: Vec<_> = self
3132 .iter()
3133 .rev()
3134 .map(|x| {
3135 let primitive = x.as_index();
3136 if primitive < -1 || primitive == 0 {
3137 panic!("Broadcast arguments must be positive or -1");
3138 }
3139 primitive
3140 })
3141 .zip(shape.iter().rev().chain(repeat(&0)).take(self.len())) // Pad the original shape with 0s
3142 .map(|(x, &y)| if x == -1 { y } else { x as usize })
3143 .collect::<Vec<_>>()
3144 .into_iter()
3145 .rev()
3146 .collect();
3147
3148 if new_shape.contains(&0) {
3149 panic!("Cannot substitute -1 for a non-existing dimension");
3150 }
3151
3152 let new_shape: [usize; D2] = new_shape.try_into().unwrap();
3153
3154 Shape::from(new_shape)
3155 }
3156}
3157
3158impl<B, const D: usize, K> Serialize for Tensor<B, D, K>
3159where
3160 B: Backend,
3161 K: BasicOps<B>,
3162 K::Elem: Debug + Copy + Serialize,
3163{
3164 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3165 let data = self.to_data();
3166 data.serialize(serializer)
3167 }
3168}
3169
3170impl<'de, B, const D: usize, K> Deserialize<'de> for Tensor<B, D, K>
3171where
3172 B: Backend,
3173 K: BasicOps<B>,
3174 K::Elem: Debug + Copy + Deserialize<'de>,
3175{
3176 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
3177 let tensor = Tensor::from_data(
3178 TensorData::deserialize(deserializer)?,
3179 &<B::Device as Default>::default(),
3180 );
3181 Ok(tensor)
3182 }
3183}
3184
3185#[cfg(test)]
3186mod tests {
3187 use burn_std::SliceOps;
3188
3189 use crate::{Shape, s};
3190
3191 #[test]
3192 fn slice_range_single_dim_leading() {
3193 let shape = Shape::new([8, 4]);
3194
3195 // Half-open range
3196 let slices = shape.clone().into_slices([0..5]);
3197 assert_eq!(slices[0].to_range(8), 0..5);
3198 let slices = shape.clone().into_slices([-3..-1]);
3199 assert_eq!(slices[0].to_range(8), 5..7);
3200
3201 // Inclusive range
3202 let slices = shape.clone().into_slices([0..=4]);
3203 assert_eq!(slices[0].to_range(8), 0..5);
3204 let slices = shape.clone().into_slices([-2..=-1]);
3205 assert_eq!(slices[0].to_range(8), 6..8);
3206
3207 // Unbounded start
3208 let slices = shape.clone().into_slices([..3]);
3209 assert_eq!(slices[0].to_range(8), 0..3);
3210 let slices = shape.clone().into_slices([..-5]);
3211 assert_eq!(slices[0].to_range(8), 0..3);
3212
3213 // Unbounded end
3214 let slices = shape.clone().into_slices([5..]);
3215 assert_eq!(slices[0].to_range(8), 5..8);
3216 let slices = shape.clone().into_slices([-3..]);
3217 assert_eq!(slices[0].to_range(8), 5..8);
3218
3219 // Full range
3220 let slices = shape.into_slices([..]);
3221 assert_eq!(slices[0].to_range(8), 0..8);
3222 }
3223
3224 #[test]
3225 fn test_negative_slice_indices() {
3226 use crate::Slice;
3227
3228 // Test negative indices conversion
3229 let slice: Slice = (-3..-1).into();
3230 assert_eq!(slice.start, -3);
3231 assert_eq!(slice.end, Some(-1));
3232
3233 // Test to_range conversion with size 8
3234 let range = slice.to_range(8);
3235 assert_eq!(range, 5..7);
3236
3237 // Test with shape slice
3238 let shape = Shape::new([8, 4]);
3239 let result = shape.clone().into_slices([-3..-1]);
3240 assert_eq!(result[0].to_range(8), 5..7);
3241
3242 // Test more negative index cases
3243 let slice2: Slice = (-5..).into();
3244 assert_eq!(slice2.to_range(10), 5..10);
3245
3246 let slice3: Slice = (..-2).into();
3247 assert_eq!(slice3.to_range(10), 0..8);
3248
3249 // Test with s! macro - single dimension returns Slice directly
3250 let slice4 = s![-3..-1];
3251 assert_eq!(slice4.start, -3);
3252 assert_eq!(slice4.end, Some(-1));
3253 }
3254
3255 #[test]
3256 fn slice_range_multi_dim() {
3257 let shape = Shape::new([8, 4]);
3258
3259 // Multiple ways to provide ranges
3260 let slices = shape.clone().into_slices([0..5, 0..4]);
3261 assert_eq!(slices[0].to_range(8), 0..5);
3262 assert_eq!(slices[1].to_range(4), 0..4);
3263
3264 let slices = shape.clone().into_slices([0.., 0..]);
3265 assert_eq!(slices[0].to_range(8), 0..8);
3266 assert_eq!(slices[1].to_range(4), 0..4);
3267
3268 let slices = shape.clone().into_slices([0..=7, 0..=3]);
3269 assert_eq!(slices[0].to_range(8), 0..8);
3270 assert_eq!(slices[1].to_range(4), 0..4);
3271
3272 let slices = shape.clone().into_slices([0..5, 0..3]);
3273 assert_eq!(slices[0].to_range(8), 0..5);
3274 assert_eq!(slices[1].to_range(4), 0..3);
3275
3276 let slices = shape.into_slices([0.., 0..]);
3277 assert_eq!(slices[0].to_range(8), 0..8);
3278 assert_eq!(slices[1].to_range(4), 0..4);
3279 }
3280
3281 #[test]
3282 fn slice_range_multi_dim_index() {
3283 let shape = Shape::new([8, 4]);
3284
3285 // Indices (single integer) should also convert to correct range
3286 let slices = shape.clone().into_slices([0, 2]);
3287 assert_eq!(slices[0].to_range(8), 0..1);
3288 assert_eq!(slices[1].to_range(4), 2..3);
3289
3290 let slices = shape.into_slices([-1, -1]);
3291 assert_eq!(slices[0].to_range(8), 7..8);
3292 assert_eq!(slices[1].to_range(4), 3..4);
3293 }
3294
3295 #[test]
3296 fn slice_range_multi_dim_heterogeneous() {
3297 // Slice macro `s![]` can be used to provide different range types
3298 let shape = Shape::new([8, 4, 2]);
3299 let slice = s![0..5, .., -1];
3300 let slices = shape.into_slices(slice);
3301 assert_eq!(slices[0].to_range(8), 0..5);
3302 assert_eq!(slices[1].to_range(4), 0..4);
3303 assert_eq!(slices[2].to_range(2), 1..2);
3304
3305 let shape = Shape::new([8, 4, 2, 3]);
3306 let slice = s![..=4, 0..=3, .., -2..];
3307 let slices = shape.into_slices(slice);
3308 assert_eq!(slices[0].to_range(8), 0..5);
3309 assert_eq!(slices[1].to_range(4), 0..4);
3310 assert_eq!(slices[2].to_range(2), 0..2);
3311 assert_eq!(slices[3].to_range(3), 1..3);
3312
3313 let shape = Shape::new([3, 4]);
3314 let slice = s![1..-1, ..];
3315 let slices = shape.into_slices(slice);
3316 assert_eq!(slices[0].to_range(3), 1..2);
3317 assert_eq!(slices[1].to_range(4), 0..4);
3318 }
3319}