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::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.dims));
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.dims));
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.dims));
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.dims));
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 .dims
760 .iter()
761 .filter_map(|&dim| if dim == 1 { None } else { Some(dim) })
762 .collect::<Vec<_>>();
763 check!(TensorCheck::squeeze_dims_len::<D2>(new_dims.len()));
764
765 Tensor::new(K::reshape(self.primitive, new_dims.into()))
766 }
767
768 /// Squeeze the tensor along the given dimension, removing the specified dimension
769 /// of size one, and effectively reducing the rank of the tensor by one.
770 ///
771 /// # Arguments
772 ///
773 /// - `dim`: The dimension to be squeezed.
774 ///
775 /// # Type Parameters
776 ///
777 /// - `D2`: The resulting number of dimensions in the squeezed tensor.
778 ///
779 /// # Panics
780 ///
781 /// If the size in the squeezed dimension is not 1.
782 ///
783 /// # Returns
784 ///
785 /// A new `Tensor<B, D2, K>` instance with the specified dimension removed.
786 ///
787 /// # Example
788 ///
789 /// ```rust
790 ///
791 /// use burn_tensor::backend::Backend;
792 /// use burn_tensor::{Tensor, Shape};
793 ///
794 /// fn example<B: Backend>() {
795 /// let device = Default::default();
796 /// // Create a 3D tensor with dimensions [3, 1, 3]
797 /// let tensor = Tensor::<B, 3>::from_data(
798 /// [[[3.0, 4.9, 2.0]], [[2.0, 1.9, 3.0]], [[4.0, 5.9, 8.0]]],
799 /// &device,
800 /// );
801 ///
802 /// // Squeeze the dimension 1.
803 /// // The resulting tensor will have dimensions [3, 3].
804 /// let squeezed = tensor.squeeze_dim::<2>(1);
805 /// println!("{squeezed}");
806 /// }
807 /// ```
808 pub fn squeeze_dim<const D2: usize>(self, dim: usize) -> Tensor<B, D2, K> {
809 check!(TensorCheck::squeeze::<D2>(dim, &self.shape().dims));
810
811 let current_dims = self.shape().dims;
812 let mut new_dims: [usize; D2] = [0; D2];
813
814 new_dims[..dim].copy_from_slice(¤t_dims[..dim]);
815 new_dims[dim..].copy_from_slice(¤t_dims[dim + 1..]);
816
817 check!(TensorCheck::squeeze_dims_len::<D2>(new_dims.len()));
818 Tensor::new(K::reshape(self.primitive, new_dims.into()))
819 }
820
821 /// Removes specified dimensions of size 1 from a tensor's shape. This function takes a tensor and
822 /// an array of dimensions (`dims`) to be squeezed. If `dims` is provided, only the dimensions
823 /// specified in this array will be removed. Each dimension in `dims` should correspond to a size of 1
824 /// in the tensor; otherwise, the dimension will not be squeezed. If `dims` is empty, all single-dimensional entries
825 /// in the tensor will be removed. If entries in `dims` are negative, then dimensions will be counted
826 /// from the back.
827 ///
828 /// # Arguments
829 ///
830 /// - `dims`: The dimension(s) to be squeezed.
831 ///
832 /// # Type Parameters
833 ///
834 /// - `D2`: The resulting number of dimensions in the squeezed tensor.
835 ///
836 /// # Returns
837 ///
838 /// A new `Tensor<B, D2, K>` instance with the specified dimensions removed.
839 ///
840 /// # Example
841 ///
842 /// ```rust
843 ///
844 /// use burn_tensor::backend::Backend;
845 /// use burn_tensor::{Tensor, Shape};
846 ///
847 /// fn example<B: Backend>() {
848 /// let device = Default::default();
849 /// // Create a 4D tensor with dimensions [2, 1, 4, 1]
850 /// let tensor = Tensor::<B, 4>::ones(Shape::new([2, 1, 4, 1]), &device);
851 ///
852 /// // Squeeze the dimensions 1 and 3.
853 /// // The resulting tensor will have dimensions [2, 4].
854 /// let squeezed: Tensor<B, 2> = tensor.squeeze_dims(&[1, 3]);
855 /// println!("{squeezed}");
856 /// }
857 /// ```
858 pub fn squeeze_dims<const D2: usize>(self, dims: &[isize]) -> Tensor<B, D2, K> {
859 let current_dims = self.shape().dims;
860 let mut dim_indices: Vec<usize>;
861
862 // Check if dims is empty, if yes then assign dim_indices all single-dimensional entries
863 if dims.is_empty() {
864 dim_indices = current_dims
865 .iter()
866 .enumerate()
867 .filter_map(|(index, &dim)| if dim == 1 { Some(index) } else { None })
868 .collect();
869 } else {
870 // If negative dims, count from the back
871 dim_indices = dims
872 .iter()
873 .map(|&d| {
874 if d < 0 {
875 (current_dims.len() as isize + d) as usize
876 } else {
877 d as usize
878 }
879 })
880 .collect();
881 }
882
883 // Sort indices and remove duplicates
884 dim_indices.sort_unstable();
885 dim_indices.dedup();
886
887 // Make sure squeeze_dims doesn't result in a tensor with < 1 dimensions
888 check!(TensorCheck::squeeze_dims_input::<D2>(
889 &dim_indices,
890 ¤t_dims
891 ));
892
893 // Calculate new dimensions
894 let mut new_dims = Vec::new();
895 for (index, &dim_size) in current_dims.iter().enumerate() {
896 // Exclude the dimension if it's explicitly marked for squeezing
897 if dim_indices.contains(&index) {
898 check!(TensorCheck::squeeze::<D2>(index, ¤t_dims));
899 continue;
900 }
901 new_dims.push(dim_size);
902 }
903
904 // Check that after squeezing, we still respect the D2 size
905 check!(TensorCheck::squeeze_dims_len::<D2>(new_dims.len()));
906
907 Tensor::new(K::reshape(self.primitive, new_dims.into()))
908 }
909
910 /// Unsqueeze the current tensor. Create new leading dimensions to fit the given size.
911 ///
912 /// # Type Parameters
913 ///
914 /// - `D2`: The resulting number of dimensions in the unsqueezed tensor.
915 ///
916 /// # Panics
917 ///
918 /// If the output size `D2` is smaller than the current number of dimensions.
919 ///
920 /// # Returns
921 ///
922 /// A new `Tensor<B, D2, K>` instance with the specified dimensions added.
923 ///
924 /// # Example
925 ///
926 /// ```rust
927 /// use burn_tensor::backend::Backend;
928 /// use burn_tensor::{Tensor, Shape};
929 ///
930 /// fn example<B: Backend>() {
931 /// let device = Default::default();
932 /// // Create a 2D tensor with dimensions [3, 3]
933 /// let tensor = Tensor::<B, 2>::ones(Shape::new([3, 3]), &device);
934 /// // Unsqueeze the tensor up to 4 dimensions.
935 /// // The resulting tensor will have dimensions [1, 1, 3, 3].
936 /// let unsqueezed = tensor.unsqueeze::<4>();
937 /// println!("{unsqueezed}");
938 /// }
939 /// ```
940 pub fn unsqueeze<const D2: usize>(self) -> Tensor<B, D2, K> {
941 check!(TensorCheck::unsqueeze::<D, D2>());
942
943 let mut dims = [1; D2];
944 let num_ones = D2 - D;
945 let shape = self.shape();
946
947 dims[num_ones..(D + num_ones)].copy_from_slice(&shape[..D]);
948
949 let shape = Shape::new(dims);
950 self.reshape(shape)
951 }
952
953 /// Creates a new tensor with a dimension of size one inserted at the specified position.
954 ///
955 /// # Example
956 ///
957 /// ```rust
958 /// use burn_tensor::backend::Backend;
959 /// use burn_tensor::{Tensor, Shape};
960 ///
961 /// fn example<B: Backend>() {
962 /// let device = Default::default();
963 /// // Create a 2D tensor with dimensions [3, 3]
964 /// let tensor = Tensor::<B, 2>::ones(Shape::new([3, 3]), &device);
965 /// // Unsqueeze the dimension 1.
966 /// // The resulting tensor will have dimensions [3, 1, 3].
967 /// let unsqueezed: Tensor<B, 3> = tensor.unsqueeze_dim(1);
968 /// println!("{unsqueezed}");
969 /// }
970 /// ```
971 pub fn unsqueeze_dim<const D2: usize>(self, dim: usize) -> Tensor<B, D2, K> {
972 check!(TensorCheck::unsqueeze_dim::<D, D2>(dim));
973
974 let mut dims = [1; D2];
975 let shape = self.shape();
976
977 dims[0..dim].copy_from_slice(&shape[0..dim]);
978
979 if dim < D {
980 dims[dim] = 1;
981 dims[(dim + 1)..].copy_from_slice(&shape[dim..]);
982 } else {
983 dims[dim] = 1;
984 }
985
986 let shape = Shape::new(dims);
987 self.reshape(shape)
988 }
989
990 /// Creates a new tensor with added dimensions of size one inserted at the specified indices.
991 /// The indices can be negative, in which case they are counted from the last to the first dimension.
992 /// the axes can contain duplicates, in which case the number of dimensions inserted at the index
993 /// is the number of duplicates.
994 /// # Example
995 ///
996 /// ```rust
997 /// use burn_tensor::backend::Backend;
998 /// use burn_tensor::{Tensor, Shape};
999 ///
1000 /// fn example<B: Backend>() {
1001 /// let device = Default::default();
1002 /// // Create a 3D tensor with dimensions [3, 4, 5]
1003 /// let tensor = Tensor::<B, 3>::ones(Shape::new([3, 4, 5]), &device);
1004 /// // Unsqueeze the leading dimension (0) once and the trailing dimension (-1) twice.
1005 /// // The resulting tensor will have dimensions [1, 3, 4, 5, 1, 1].
1006 /// let unsqueezed: Tensor<B, 6> = tensor.unsqueeze_dims(&[0, -1, -1]);
1007 /// println!("{unsqueezed}");
1008 /// }
1009 /// ```
1010 pub fn unsqueeze_dims<const D2: usize>(self, axes: &[impl AsIndex]) -> Tensor<B, D2, K> {
1011 let mut new_dims = [1; D2];
1012 let old_dims = self.shape().dims;
1013 //for checking if the dimension is in the acceptable range
1014
1015 //part 1: convert the negative indices to positive
1016 let mut neg_offset = D2;
1017 let mut dim_indices = axes
1018 .iter()
1019 .map(|d| {
1020 let d = d.as_index();
1021 // check if the dimension is in the acceptable range
1022 check!(TensorCheck::unsqueeze_dims::<{ D2 }>(d));
1023 (if d < 0 {
1024 neg_offset -= 1; // handle multiple negative indices (decrease dim value in reverse)
1025 d + neg_offset as isize + 1
1026 } else {
1027 d
1028 }) as usize
1029 })
1030 .collect::<Vec<usize>>();
1031
1032 //sort the indices
1033 dim_indices.sort_unstable();
1034
1035 //Now use this to copy the chunks of the dims
1036 let mut prev_idx: usize = 0;
1037 let mut current_left_b: usize = 0;
1038 let mut current_right_b: usize = 0;
1039 let mut offset: usize = 0;
1040 dim_indices.iter().for_each(|d| {
1041 //check if there is space for at least one dimension
1042 if prev_idx < *d {
1043 current_right_b = *d - offset;
1044 //copy the chunks of the dims
1045 if current_right_b < D {
1046 new_dims[prev_idx..*d]
1047 .copy_from_slice(&old_dims[current_left_b..current_right_b]);
1048 } else {
1049 new_dims[prev_idx..*d].copy_from_slice(&old_dims[current_left_b..]);
1050 }
1051 prev_idx = *d + 1;
1052 //offset is equal to the number of extracted elements from the original shape
1053 offset += current_right_b - current_left_b;
1054 current_left_b = current_right_b;
1055 } else {
1056 //it's sorted so the only reason this would happen
1057 //is if multiple indices are the same
1058 prev_idx += 1;
1059 }
1060 });
1061 //copy over anything past the index of the last new dimension
1062 if current_left_b < D {
1063 new_dims[prev_idx..].copy_from_slice(&old_dims[current_left_b..]);
1064 }
1065
1066 //lastly, create the shape and reshape
1067 let shape = Shape::new(new_dims);
1068 self.reshape(shape)
1069 }
1070
1071 /// Roll operation along a specific dimension; wrapping around the elements.
1072 ///
1073 /// ## Parameters
1074 ///
1075 /// - `shift`: The roll extent; supports negative values and wraps around.
1076 /// - `dim`: The dimension to roll; supports negative indexing.
1077 ///
1078 /// ## Returns
1079 ///
1080 /// A new tensor with the specified dimension rolled by the given shift amount.
1081 pub fn roll_dim<Shift, Dim>(self, shift: Shift, dim: Dim) -> Self
1082 where
1083 Shift: AsIndex,
1084 Dim: AsIndex,
1085 {
1086 let dim = dim.expect_dim_index(D);
1087 let size = self.shape().dims[dim];
1088 if size == 0 {
1089 // If the dimension is empty, return the tensor as is.
1090 return self;
1091 }
1092
1093 let shift = wrap_index(shift, size);
1094 if shift == 0 {
1095 // If the shift is zero, return the tensor as is.
1096 return self;
1097 }
1098
1099 self.unchecked_roll_dim(shift, dim)
1100 }
1101
1102 /// Internal implementation of `roll_dim` that does not canonicalize dimensions or shifts.
1103 ///
1104 /// ## Parameters
1105 ///
1106 /// - `shift`: The number of positions to shift; must be (0 < shift < size).
1107 /// - `dim`: The dimension to roll; must be a valid index for the tensor's shape.
1108 ///
1109 /// ## Returns
1110 ///
1111 /// A new tensor with the specified dimension rolled by the given shift amount.
1112 #[inline(always)]
1113 fn unchecked_roll_dim(self, shift: usize, dim: usize) -> Self {
1114 #[cfg(debug_assertions)]
1115 {
1116 let size = self.shape().dims[dim];
1117 assert!(
1118 0 < shift && shift < size,
1119 "Expected: 0 < shift < size: found shift={shift}, size={size}",
1120 );
1121 assert!(
1122 dim < self.shape().num_dims(),
1123 "Expected: dim < num_dims: found dim={dim}, num_dims={size}",
1124 );
1125 }
1126
1127 Tensor::cat(
1128 vec![
1129 self.clone().slice_dim(dim, shift..),
1130 self.slice_dim(dim, ..shift),
1131 ],
1132 dim,
1133 )
1134 }
1135
1136 /// Roll operation.
1137 ///
1138 /// Note: unlike ``pytorch``, `dims` and `shifts` must have the same length.
1139 ///
1140 /// A given `dim` may be rolled multiple times, and the shifts will be applied sequentially.
1141 ///
1142 /// ## Parameters
1143 ///
1144 /// - `shifts`: A slice of shifts corresponding to each dimension;
1145 /// supports negative values and wraps around.
1146 /// - `dims`: A slice of dimensions to roll; supports negative indexing.
1147 ///
1148 /// ## Returns
1149 ///
1150 /// A new tensor with the specified dimensions rolled by the given shifts.
1151 pub fn roll<Shift, Dim>(self, shifts: &[Shift], dims: &[Dim]) -> Self
1152 where
1153 Shift: AsIndex,
1154 Dim: AsIndex,
1155 {
1156 assert_eq!(
1157 dims.len(),
1158 shifts.len(),
1159 "Dimensions and shifts must align; found dims={dims:#?}, shifts={shifts:#?}",
1160 );
1161
1162 // This is a fair amount of complexity, which could be replaced
1163 // by a simple canonicalization of `dims` and wrapping of `shifts`.
1164 // The work is done here to ensure that any roll operation
1165 // which could be a no-op is a no-op; simplifying the accounting
1166 // needed by backend-specific implementations of the inner roll op.
1167
1168 let item_count = dims.len();
1169
1170 let shape = self.shape().dims;
1171
1172 // Accumulate the effective shifts for each dimension.
1173 let mut accumulated_shifts: Vec<isize> = vec![0; shape.len()];
1174 for i in 0..item_count {
1175 let dim = dims[i].expect_dim_index(D);
1176 accumulated_shifts[dim] += shifts[i].as_index();
1177 }
1178
1179 // Do this after we've checked the validity of `dims` and `shifts`.
1180 if self.shape().num_elements() == 0 {
1181 // If the tensor is empty, return it as is.
1182 return self;
1183 }
1184
1185 // Wrap the accumulated shifts, and filter out empty dimensions.
1186 let mut effective_dims: Vec<usize> = Vec::with_capacity(item_count);
1187 let mut effective_shifts: Vec<usize> = Vec::with_capacity(item_count);
1188 for dim in 0..shape.len() {
1189 // `wrap_index` should inline, and has a fast-exit path for zero shifts.
1190 let shift = wrap_index(accumulated_shifts[dim], shape[dim]);
1191 if shift == 0 {
1192 continue;
1193 }
1194
1195 effective_dims.push(dim);
1196 effective_shifts.push(shift);
1197 }
1198
1199 // If no shifts are needed, return the original tensor.
1200 if effective_shifts.is_empty() {
1201 return self;
1202 }
1203
1204 // At this point:
1205 // - `dims` contains the effective dimensions to roll, in index order,
1206 // - `shifts` contains the effective usize shifts for each dimension.
1207 // - Every shift is non-zero, and less than the size of the corresponding dimension.
1208 self.unchecked_roll(&effective_shifts, &effective_dims)
1209 }
1210
1211 /// `roll` internal implementation.
1212 ///
1213 /// ## Parameters
1214 ///
1215 /// - `shifts`: A slice of shifts corresponding to each dimension;
1216 /// must be non-empty, the same length as `dims`, and all ``1..<size>``.
1217 /// - `dims`: A slice of dimensions to roll; must be non-empty;
1218 /// the same length as `shifts`, and must not contain repeats.
1219 ///
1220 /// ## Panics
1221 ///
1222 /// Panics if the shifts and dimensions do not align, or if dimensions contain repeats.
1223 ///
1224 /// ## Returns
1225 ///
1226 /// A new tensor with the specified dimensions rolled by the given shifts.
1227 #[inline(always)]
1228 fn unchecked_roll(self, shifts: &[usize], dims: &[usize]) -> Self {
1229 #[cfg(debug_assertions)]
1230 {
1231 assert!(!shifts.is_empty());
1232 assert_eq!(
1233 shifts.len(),
1234 dims.len(),
1235 "Shifts and dimensions must align; found {} shifts and {} dims",
1236 shifts.len(),
1237 dims.len()
1238 );
1239
1240 let mut unique_dims = dims.to_vec();
1241 unique_dims.dedup();
1242
1243 assert_eq!(
1244 unique_dims.len(),
1245 dims.len(),
1246 "Dimensions must not contain repeats; found {} unique dims and {} total dims",
1247 unique_dims.len(),
1248 dims.len()
1249 )
1250 }
1251
1252 let x = self.unchecked_roll_dim(shifts[0], dims[0]);
1253
1254 if dims.len() == 1 {
1255 x
1256 } else {
1257 x.unchecked_roll(&shifts[1..], &dims[1..])
1258 }
1259 }
1260
1261 /// Returns a tensor containing the elements selected from the given slices.
1262 ///
1263 /// This method provides flexible tensor slicing with support for various range types,
1264 /// negative indices, and stepped slicing. The method accepts both single slices and
1265 /// arrays of slices, with the [`s!`] macro providing convenient syntax for complex patterns.
1266 ///
1267 /// # Arguments
1268 ///
1269 /// * `slices` - Can be:
1270 /// - A single range for 1D slicing (e.g., `0..5`, `..`, `2..`)
1271 /// - An array of ranges (e.g., `[0..2, 1..4]`)
1272 /// - The [`s!`] macro output for advanced slicing with steps
1273 /// - a `&Vec<Slice>` or `&[Slice]`
1274 ///
1275 /// # Behavior
1276 ///
1277 /// - Supports partial and full slicing in any number of dimensions
1278 /// - Handles negative indices by wrapping from the end (-1 is the last element)
1279 /// - Automatically clamps ranges that exceed tensor dimensions
1280 /// - Supports stepped slicing for selecting every nth element
1281 /// - Negative steps reverse the selection order
1282 ///
1283 /// # Panics
1284 ///
1285 /// - If the number of slices exceeds the tensor's dimensions
1286 /// - If a range is descending (e.g., 2..1) or empty (e.g., 1..1) without negative step
1287 /// - If a step is zero
1288 ///
1289 /// # Examples
1290 ///
1291 /// ```rust
1292 /// use burn_tensor::backend::Backend;
1293 /// use burn_tensor::{Tensor, Shape, s};
1294 ///
1295 /// fn example<B: Backend>() {
1296 /// let device = B::Device::default();
1297 ///
1298 /// // Single dimension slicing - no brackets needed!
1299 /// let tensor = Tensor::<B, 1, burn_tensor::Int>::arange(0..10, &device);
1300 /// let slice = tensor.clone().slice(2..8); // Simple range
1301 /// assert_eq!(slice.into_data().to_vec::<i32>().unwrap(), vec![2, 3, 4, 5, 6, 7]);
1302 ///
1303 /// // Using s! macro for single dimension with step
1304 /// let slice = tensor.clone().slice(s![0..10;2]); // Every 2nd element
1305 /// assert_eq!(slice.into_data().to_vec::<i32>().unwrap(), vec![0, 2, 4, 6, 8]);
1306 ///
1307 /// // Reverse a dimension with negative step
1308 /// let slice = tensor.slice(s![..;-1]); // Reverse entire tensor
1309 /// assert_eq!(slice.into_data().to_vec::<i32>().unwrap(), vec![9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
1310 ///
1311 /// // Multi-dimensional slicing
1312 /// let tensor = Tensor::<B, 2>::ones(Shape::new([4, 6]), &device);
1313 ///
1314 /// // Array syntax for simple ranges
1315 /// let slice = tensor.clone().slice([1..3, 2..5]);
1316 /// assert_eq!(slice.dims(), [2, 3]);
1317 ///
1318 /// // Advanced multi-dimensional with s! macro
1319 /// let slice = tensor.clone().slice(s![0..4;2, ..;-1]); // Every 2nd row, reverse columns
1320 /// assert_eq!(slice.dims(), [2, 6]);
1321 ///
1322 /// // Complex 3D example with mixed slice types
1323 /// let tensor = Tensor::<B, 3>::ones(Shape::new([4, 6, 8]), &device);
1324 /// let slice = tensor.slice(s![1..3, ..;2, -3..]); // Rows 1-2, every 2nd col, last 3 depth
1325 /// assert_eq!(slice.dims(), [2, 3, 3]);
1326 ///
1327 /// // Using negative indices
1328 /// let tensor = Tensor::<B, 2>::ones(Shape::new([4, 6]), &device);
1329 /// let slice = tensor.slice(s![-2.., ..-1]); // Last 2 rows, all but last column
1330 /// assert_eq!(slice.dims(), [2, 5]);
1331 /// }
1332 /// ```
1333 ///
1334 /// # See Also
1335 ///
1336 /// - [`s!`] - The recommended macro for creating complex slice specifications
1337 /// - [`slice_assign`](Self::slice_assign) - Assign values to a slice
1338 /// - [`slice_fill`](Self::slice_fill) - Fill a slice with a constant value
1339 /// - [`slice_dim`](Self::slice_dim) - Slice a single dimension
1340 ///
1341 /// [`s!`]: crate::s!
1342 pub fn slice<S>(self, slices: S) -> Self
1343 where
1344 S: SliceArg,
1345 {
1346 let shape = self.shape();
1347 let slices = slices.into_slices(&shape);
1348
1349 // Validate slices
1350 check!(TensorCheck::slice::<D>(&shape, &slices));
1351
1352 // Calculate output shape and check for empty slices
1353 let mut output_dims = shape.dims.clone();
1354 for (dim, slice) in slices.iter().enumerate() {
1355 output_dims[dim] = slice.output_size(shape.dims[dim]);
1356 }
1357
1358 // Return empty tensor if any dimension is 0 (empty slice)
1359 if output_dims.contains(&0) {
1360 return Self::empty(output_dims, &self.device());
1361 }
1362 Self::new(K::slice(self.primitive, &slices))
1363 }
1364
1365 /// Assigns values to a slice of the tensor and returns the updated tensor.
1366 ///
1367 /// This method supports advanced slicing with steps, including negative steps for reverse
1368 /// assignment. Like `slice`, it accepts both single slices and arrays, with the [`s!`] macro
1369 /// providing powerful syntax for complex patterns.
1370 ///
1371 /// # Arguments
1372 ///
1373 /// * `slices` - Slice specification (same format as `slice` method)
1374 /// * `values` - Tensor with values to assign (must match slice dimensions)
1375 ///
1376 /// # Panics
1377 ///
1378 /// - If slices exceed tensor dimensions
1379 /// - If values dimensions don't match the selected slice shape
1380 /// - If a step is zero
1381 ///
1382 /// # Examples
1383 ///
1384 /// ```rust
1385 /// use burn_tensor::backend::Backend;
1386 /// use burn_tensor::{Tensor, s};
1387 ///
1388 /// fn example<B: Backend>() {
1389 /// let device = B::Device::default();
1390 ///
1391 /// // Simple assignment to a sub-region
1392 /// let mut tensor = Tensor::<B, 2>::zeros([4, 6], &device);
1393 /// let values = Tensor::<B, 2>::ones([2, 3], &device);
1394 /// tensor = tensor.slice_assign([1..3, 2..5], values);
1395 /// // Now tensor[1..3, 2..5] contains ones
1396 ///
1397 /// // Single dimension assignment with step
1398 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1399 /// let values = Tensor::<B, 1>::ones([5], &device);
1400 /// tensor = tensor.slice_assign(s![0..10;2], values);
1401 /// // Now every 2nd element is 1: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
1402 ///
1403 /// // Reverse assignment with negative step
1404 /// let mut tensor = Tensor::<B, 1>::from_data([0.0, 1.0, 2.0, 3.0, 4.0], &device);
1405 /// let values = Tensor::<B, 1>::from_data([10.0, 11.0, 12.0, 13.0, 14.0], &device);
1406 /// tensor = tensor.slice_assign(s![..;-1], values);
1407 /// // Assigns in reverse: [14, 13, 12, 11, 10]
1408 ///
1409 /// // Complex multi-dimensional assignment
1410 /// let mut tensor = Tensor::<B, 3>::zeros([4, 6, 8], &device);
1411 /// let values = Tensor::<B, 3>::ones([2, 3, 3], &device);
1412 /// tensor = tensor.slice_assign(s![0..4;2, ..;2, -3..], values);
1413 /// // Assigns to every 2nd row, every 2nd column, last 3 in depth
1414 ///
1415 /// // Mixed syntax example
1416 /// let mut tensor = Tensor::<B, 2>::zeros([8, 8], &device);
1417 /// let pattern = Tensor::<B, 2>::ones([4, 4], &device);
1418 /// tensor = tensor.slice_assign(s![..;2, ..;2], pattern);
1419 /// // Creates a checkerboard pattern with ones
1420 /// }
1421 /// ```
1422 ///
1423 /// # See Also
1424 ///
1425 /// - [`s!`] - The recommended macro for creating complex slice specifications
1426 /// - [`slice`](Self::slice) - Extract a slice from a tensor
1427 /// - [`slice_fill`](Self::slice_fill) - Fill a slice with a constant value
1428 ///
1429 /// [`s!`]: crate::s!
1430 pub fn slice_assign<S>(self, slices: S, values: Self) -> Self
1431 where
1432 S: SliceArg,
1433 {
1434 let shape = self.shape();
1435 let slices = slices.into_slices(&shape);
1436
1437 // Check if any slice produces 0 elements (empty assignment).
1438 // Empty assignments are no-ops and would cause issues in backend implementations.
1439 let is_empty_assignment = slices
1440 .iter()
1441 .enumerate()
1442 .any(|(i, slice)| slice.output_size(shape.dims[i]) == 0);
1443
1444 if is_empty_assignment {
1445 return self;
1446 }
1447
1448 check!(TensorCheck::slice_assign::<D>(
1449 &shape,
1450 &values.shape(),
1451 &slices
1452 ));
1453
1454 Self::new(K::slice_assign(self.primitive, &slices, values.primitive))
1455 }
1456
1457 /// Fills a slice of the tensor with a constant value and returns the updated tensor.
1458 ///
1459 /// Like other slice methods, accepts both single slices and arrays. However, this method
1460 /// currently **does not support stepped slicing** - use [`slice_assign`](Self::slice_assign)
1461 /// with a constant tensor for stepped patterns.
1462 ///
1463 /// # Arguments
1464 ///
1465 /// * `slices` - Slice specification (same format as `slice` method, but no steps)
1466 /// * `value` - The value to fill the slice with
1467 ///
1468 /// # Panics
1469 ///
1470 /// - If slices exceed tensor dimensions
1471 /// - If any slice has a step != 1 (not yet supported)
1472 ///
1473 /// # Examples
1474 ///
1475 /// ```rust
1476 /// use burn_tensor::backend::Backend;
1477 /// use burn_tensor::{Tensor, s};
1478 ///
1479 /// fn example<B: Backend>() {
1480 /// let device = B::Device::default();
1481 ///
1482 /// // Simple fill for a single dimension
1483 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1484 /// tensor = tensor.slice_fill(2..5, 1.0);
1485 /// // Now tensor is [0, 0, 1, 1, 1, 0, 0, 0, 0, 0]
1486 ///
1487 /// // Multi-dimensional fill
1488 /// let mut tensor = Tensor::<B, 2>::zeros([4, 6], &device);
1489 /// tensor = tensor.slice_fill([1..3, 2..5], -1.0);
1490 /// // Fills the rectangle at rows 1-2, columns 2-4 with -1
1491 ///
1492 /// // Using negative indices
1493 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1494 /// tensor = tensor.slice_fill(-3.., 2.0);
1495 /// // Fills the last 3 elements with 2.0
1496 ///
1497 /// // Complex multi-dimensional example
1498 /// let mut tensor = Tensor::<B, 3>::ones([4, 6, 8], &device);
1499 /// tensor = tensor.slice_fill(s![1..3, .., -2..], 0.0);
1500 /// // Sets rows 1-2, all columns, last 2 in depth to 0
1501 ///
1502 /// // Stepped slicing is supported
1503 /// let mut tensor = Tensor::<B, 1>::zeros([10], &device);
1504 /// tensor = tensor.slice_fill(s![0..10;2], 1.0);
1505 /// // Now every 2nd element is 1: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
1506 /// }
1507 /// ```
1508 ///
1509 /// # See Also
1510 ///
1511 /// - [`s!`] - The macro for creating slice specifications with steps
1512 /// - [`slice`](Self::slice) - Extract a slice from a tensor
1513 /// - [`slice_assign`](Self::slice_assign) - Assign tensor values to a slice
1514 ///
1515 /// [`s!`]: crate::s!
1516 pub fn slice_fill<S, E: ElementConversion>(self, slices: S, value: E) -> Self
1517 where
1518 S: SliceArg,
1519 {
1520 let shape = self.shape();
1521 let slices = slices.into_slices(&shape);
1522
1523 check!(TensorCheck::slice::<D>(&shape, &slices));
1524
1525 let slice_shape = shape.slice(&slices).unwrap();
1526 let value = Tensor::<B, 1, K>::from_data_dtype(
1527 [value.elem::<K::Elem>()],
1528 &self.device(),
1529 self.dtype(),
1530 );
1531 let value = value.expand(slice_shape);
1532 self.slice_assign(&slices, value)
1533 }
1534
1535 /// Returns a new tensor with the specified dimension sliced.
1536 ///
1537 /// # Arguments
1538 ///
1539 /// * `dim`: The dimension to slice.
1540 /// * `slice`: The slice specification for the dimension. Can be a range (e.g., `2..5`),
1541 /// slice with step (via `s!` macro, e.g., `s![0..10;2]`), or any type that implements `Into<Slice>`.
1542 ///
1543 /// # Returns
1544 ///
1545 /// A new tensor with the specified dimension sliced.
1546 ///
1547 /// # Panics
1548 ///
1549 /// If the slice is out of bounds for the specified dimension.
1550 ///
1551 /// # Examples
1552 ///
1553 /// ```rust
1554 /// # use burn_tensor::{Tensor, s};
1555 /// # use burn_tensor::backend::Backend;
1556 /// #
1557 /// # fn example<B: Backend>() {
1558 /// # let device = B::Device::default();
1559 /// let tensor = Tensor::<B, 3>::zeros([3, 4, 5], &device);
1560 ///
1561 /// // Simple range slicing
1562 /// let sliced = tensor.clone().slice_dim(1, 1..3);
1563 /// assert_eq!(sliced.shape().dims, [3, 2, 5]);
1564 ///
1565 /// // Slicing with step - take every 2nd element
1566 /// let sliced = tensor.clone().slice_dim(2, s![0..5;2]);
1567 /// assert_eq!(sliced.shape().dims, [3, 4, 3]); // Takes indices 0, 2, 4
1568 ///
1569 /// // Reverse slicing with negative step
1570 /// let sliced = tensor.clone().slice_dim(1, s![..;-1]);
1571 /// assert_eq!(sliced.shape().dims, [3, 4, 5]); // Reverses dimension 1
1572 ///
1573 /// // Select from index 2 with step 3
1574 /// let sliced = tensor.clone().slice_dim(0, s![2..;3]);
1575 /// assert_eq!(sliced.shape().dims, [1, 4, 5]); // Takes only index 2
1576 ///
1577 /// // Select single index (reduces dimension to size 1)
1578 /// let sliced = tensor.slice_dim(0, 1);
1579 /// assert_eq!(sliced.shape().dims, [1, 4, 5]);
1580 /// # }
1581 /// ```
1582 ///
1583 /// # See Also
1584 ///
1585 /// - [`slice`](Self::slice) - Slice multiple dimensions simultaneously
1586 /// - [`s!`] - The macro for creating complex slice specifications
1587 ///
1588 /// [`s!`]: crate::s!
1589 pub fn slice_dim<S>(self, dim: usize, slice: S) -> Self
1590 where
1591 S: Into<Slice>,
1592 {
1593 check!(TensorCheck::check_dim::<D>(dim));
1594 let slice: Slice = slice.into();
1595
1596 let mut slices = vec![Slice::full(); D];
1597 slices[dim] = slice;
1598
1599 self.slice(&slices)
1600 }
1601
1602 /// Returns the device of the current tensor.
1603 pub fn device(&self) -> B::Device {
1604 K::device(&self.primitive)
1605 }
1606
1607 /// Move the tensor to the given device.
1608 pub fn to_device(self, device: &B::Device) -> Self {
1609 Self::new(K::to_device(self.primitive, device))
1610 }
1611
1612 /// Select tensor elements along the given dimension corresponding to the given indices.
1613 ///
1614 /// # Arguments
1615 ///
1616 /// * `dim` - The dimension to select from. Supports negative indexing.
1617 /// * `indices` - The indices of the elements to select.
1618 ///
1619 /// # Example
1620 ///
1621 /// ```rust
1622 /// use burn_tensor::backend::Backend;
1623 /// use burn_tensor::{Tensor, Int};
1624 ///
1625 /// fn example<B: Backend>() {
1626 /// let device = B::Device::default();
1627 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [4.0, 5.0, 6.0]], &device);
1628 /// let indices = Tensor::<B, 1, Int>::from_data([0], &device);
1629 /// let tensor = tensor.select(0, indices);
1630 /// println!("{tensor}");
1631 /// // [[1.0, -2.0, 3.0]]
1632 /// }
1633 /// ```
1634 pub fn select(self, dim: impl AsIndex, indices: Tensor<B, 1, Int>) -> Self {
1635 let dim = dim.expect_dim_index(D);
1636 check!(TensorCheck::select::<D>(dim));
1637 Self::new(K::select(self.primitive, dim, indices.primitive))
1638 }
1639
1640 /// Assign the selected elements along the given dimension corresponding to the given indices
1641 /// from the value tensor to the original tensor using sum reduction.
1642 ///
1643 /// # Note
1644 /// For booleans, the sum operator is logical or.
1645 ///
1646 /// # Arguments
1647 ///
1648 /// * `dim` - The dimension along which to select. Supports negative indexing.
1649 /// * `indices` - The indices to select from the tensor.
1650 /// * `values` - The values to assign to the selected indices.
1651 /// * `update` - The operation used to update the existing values at the indexed positions (e.g., add).
1652 ///
1653 /// # Example
1654 ///
1655 /// Example using a 3D tensor:
1656 ///
1657 /// `input[indices[i], j, k] += values[i, j, k]; // dim = 0`
1658 /// `input[i, indices[j], k] += values[i, j, k]; // dim = 1`
1659 /// `input[i, j, indices[k]] += values[i, j, k]; // dim = 2`
1660 /// `input[i, j, indices[k]] += values[i, j, k]; // dim = -1 (same as dim = 2)`
1661 ///
1662 /// # Warning
1663 ///
1664 /// Not all backends have runtime bound checks for the indices, so make sure they are valid.
1665 /// Otherwise, out of bounds indices could lead to unexpected results instead of panicking.
1666 pub fn select_assign(
1667 self,
1668 dim: impl AsIndex,
1669 indices: Tensor<B, 1, Int>,
1670 values: Tensor<B, D, K>,
1671 update: IndexingUpdateOp,
1672 ) -> Self {
1673 let dim = dim.expect_dim_index(D);
1674 check!(TensorCheck::select_assign::<D>(
1675 dim,
1676 &indices.shape(),
1677 &values.shape()
1678 ));
1679
1680 Self::new(K::select_assign(
1681 self.primitive,
1682 dim,
1683 indices.primitive,
1684 values.primitive,
1685 update,
1686 ))
1687 }
1688
1689 /// Update the given tensor with the value tensor where the mask is true.
1690 ///
1691 /// This is similar to [mask_fill](Tensor::mask_fill), however the value is a tensor instead of
1692 /// a scalar.
1693 ///
1694 /// # Example
1695 ///
1696 /// ```rust
1697 /// use burn_tensor::backend::Backend;
1698 /// use burn_tensor::{Tensor, Shape, Bool};
1699 ///
1700 /// fn example<B: Backend>() {
1701 /// let device = B::Device::default();
1702 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
1703 /// let mask = Tensor::<B, 2, Bool>::from_data([[true, false, true], [false, true, false]], &device);
1704 /// let value = Tensor::<B, 2>::from_data([[2.0, 3.0, 4.0], [1.0, 2.0, 3.0]], &device);
1705 /// let tensor = tensor.mask_where(mask, value);
1706 /// println!("{tensor}");
1707 /// // [[2.0, -2.0, 4.0], [5.0, 2.0, 6.0]]
1708 /// }
1709 /// ```
1710 pub fn mask_where(self, mask: Tensor<B, D, Bool>, value: Self) -> Self {
1711 Self::new(K::mask_where(
1712 self.primitive,
1713 mask.primitive,
1714 value.primitive,
1715 ))
1716 }
1717
1718 /// Update the given tensor with the value where the mask is true.
1719 ///
1720 /// This is similar to [mask_where](Tensor::mask_where), however the value is a scalar instead of
1721 /// a tensor.
1722 ///
1723 /// # Example
1724 ///
1725 /// ```rust
1726 /// use burn_tensor::backend::Backend;
1727 /// use burn_tensor::{Tensor, Shape, Bool};
1728 ///
1729 /// fn example<B: Backend>() {
1730 /// let device = B::Device::default();
1731 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
1732 /// let mask = Tensor::<B, 2, Bool>::from_data([[true, false, true], [false, true, false]], &device);
1733 /// let tensor = tensor.mask_fill(mask, 3.0);
1734 /// println!("{tensor}");
1735 /// // [[3.0, -2.0, 3.0], [5.0, 3.0, 6.0]]
1736 /// }
1737 /// ```
1738 pub fn mask_fill<E: ElementConversion>(self, mask: Tensor<B, D, Bool>, value: E) -> Self {
1739 let value = Scalar::new(value, &self.dtype());
1740 Self::new(K::mask_fill(self.primitive, mask.primitive, value))
1741 }
1742
1743 /// Gather tensor elements corresponding to the given indices from the specified dim.
1744 ///
1745 /// Example using a 3D tensor:
1746 ///
1747 /// `output[i, j, k] = input[indices[i, j, k], j, k]; // dim = 0`
1748 /// `output[i, j, k] = input[i, indices[i, j, k], k]; // dim = 1`
1749 /// `output[i, j, k] = input[i, j, indices[i, j, k]]; // dim = 2`
1750 ///
1751 /// # Notes
1752 ///
1753 /// The index tensor should have the same shape as the original tensor except for the dim
1754 /// specified.
1755 ///
1756 /// # Warning
1757 /// Not all backends have runtime bound checks for the indices, so make sure the they are valid.
1758 /// Otherwise, out of bounds indices could lead to unexpected results instead of panicking.
1759 pub fn gather(self, dim: usize, indices: Tensor<B, D, Int>) -> Self {
1760 check!(TensorCheck::gather::<D>(
1761 dim,
1762 &self.shape(),
1763 &indices.shape()
1764 ));
1765
1766 Self::new(K::gather(dim, self.primitive, indices.primitive))
1767 }
1768
1769 /// Assign the gathered elements corresponding to the given indices along the specified dimension
1770 /// from the value tensor to the original tensor using sum reduction.
1771 ///
1772 /// Example using a 3D tensor:
1773 ///
1774 /// `input[indices[i, j, k], j, k] += values[i, j, k]; // dim = 0`
1775 /// `input[i, indices[i, j, k], k] += values[i, j, k]; // dim = 1`
1776 /// `input[i, j, indices[i, j, k]] += values[i, j, k]; // dim = 2`
1777 ///
1778 /// # Arguments
1779 /// * `dim` - The axis along which to scatter elements.
1780 /// * `indices` - The indices of the elements to scatter.
1781 /// * `values` - The values to scatter into the tensor.
1782 /// * `update` - The operation used to update the existing values at the indexed positions (e.g., add).
1783 ///
1784 /// # Notes
1785 ///
1786 /// The index tensor should have the same shape as the original tensor except for the specified
1787 /// dimension. The value and index tensors should have the same shape.
1788 ///
1789 /// Other references to the input tensor will not be modified by this operation.
1790 ///
1791 /// # Warning
1792 /// Not all backends have runtime bound checks for the indices, so make sure the they are valid.
1793 /// Otherwise, out of bounds indices could lead to unexpected results instead of panicking.
1794 pub fn scatter(
1795 self,
1796 dim: usize,
1797 indices: Tensor<B, D, Int>,
1798 values: Self,
1799 update: IndexingUpdateOp,
1800 ) -> Self {
1801 check!(TensorCheck::scatter::<D>(
1802 dim,
1803 &self.shape(),
1804 &indices.shape(),
1805 &values.shape()
1806 ));
1807
1808 Self::new(K::scatter(
1809 dim,
1810 self.primitive,
1811 indices.primitive,
1812 values.primitive,
1813 update,
1814 ))
1815 }
1816
1817 /// Converts the data of the current tensor.
1818 ///
1819 /// # Note
1820 ///
1821 /// For better performance, prefer using a [Transaction](crate::Transaction) when reading multiple
1822 /// tensors at once. This may improve laziness, especially if executed on a different
1823 /// thread in native environments.
1824 pub fn into_data(self) -> TensorData {
1825 self.try_into_data().expect(
1826 "Error while reading data: use `try_into_data` instead to catch the error at runtime",
1827 )
1828 }
1829
1830 /// Converts the data of the current tensor and returns any error that might have occurred since the
1831 /// last time the device was synchronized.
1832 ///
1833 /// # Note
1834 ///
1835 /// For better performance, prefer using a [Transaction](crate::Transaction) when reading multiple
1836 /// tensors at once. This may improve laziness, especially if executed on a different
1837 /// thread in native environments.
1838 pub fn try_into_data(self) -> Result<TensorData, ExecutionError> {
1839 crate::try_read_sync(self.into_data_async()).expect(
1840 "Failed to read tensor data synchronously.
1841 This can happen on platforms that don't support blocking futures like WASM.
1842 If possible, try using into_data_async instead.",
1843 )
1844 }
1845
1846 /// Converts the data of the current tensor.
1847 ///
1848 /// # Note
1849 ///
1850 /// For better performance, prefer using a [Transaction](crate::Transaction) when reading multiple
1851 /// tensors at once. This may improve laziness, especially if executed on a different
1852 /// thread in native environments.
1853 pub fn to_data(&self) -> TensorData {
1854 self.clone().into_data()
1855 }
1856
1857 /// Returns the data of the current tensor.
1858 pub async fn into_data_async(self) -> Result<TensorData, ExecutionError> {
1859 K::into_data_async(self.primitive).await
1860 }
1861
1862 /// Returns the data of the current tensor.
1863 pub async fn to_data_async(&self) -> Result<TensorData, ExecutionError> {
1864 self.clone().into_data_async().await
1865 }
1866
1867 /// Create a tensor from the given data on the given device.
1868 pub fn from_data<T>(data: T, device: &B::Device) -> Self
1869 where
1870 T: Into<TensorData>,
1871 {
1872 let data = data.into();
1873 check!(TensorCheck::creation_ops::<D>(
1874 "From Data",
1875 data.shape.as_slice()
1876 ));
1877 Self::new(K::from_data(data, device))
1878 }
1879
1880 /// Create a tensor from the given data on the given device enforcing the given data type.
1881 pub fn from_data_dtype<T>(data: T, device: &B::Device, dtype: DType) -> Self
1882 where
1883 T: Into<TensorData>,
1884 {
1885 let data = data.into();
1886 check!(TensorCheck::creation_ops::<D>(
1887 "From Data",
1888 data.shape.as_slice()
1889 ));
1890 Self::new(K::from_data_dtype(data, device, dtype))
1891 }
1892
1893 /// Repeat the tensor along the given dimension.
1894 ///
1895 /// The output tensor has the same shape, except along the given dimension.
1896 ///
1897 /// # Arguments
1898 /// - `dim`: The dimension to repeat.
1899 /// - `times`: The number of times to repeat the tensor along the given dimension in the new tensor.
1900 ///
1901 /// # Returns
1902 ///
1903 /// A new tensor with the given dimension repeated `times` times.
1904 ///
1905 /// # Example
1906 ///
1907 /// ```rust
1908 /// use burn_tensor::backend::Backend;
1909 /// use burn_tensor::Tensor;
1910 ///
1911 /// fn example<B: Backend>() {
1912 /// let device = Default::default();
1913 /// // Create a 2D tensor with dimensions [3, 2]
1914 /// let tensor = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
1915 ///
1916 /// // Repeat the tensor along the dimension 0 twice.
1917 /// // [[3.0, 4.9], [2.0, 1.9], [4.0, 5.9], [3.0, 4.9], [2.0, 1.9], [4.0, 5.9]]
1918 /// // The resulting tensor will have dimensions [6, 2].
1919 /// let repeated = tensor.repeat_dim(0, 2);
1920 /// println!("{repeated}");
1921 /// }
1922 /// ```
1923 pub fn repeat_dim(self, dim: usize, times: usize) -> Self {
1924 if times > 0 {
1925 Self::new(K::repeat_dim(self.primitive, dim, times))
1926 } else {
1927 let shape = self.shape().repeat(dim, times).unwrap();
1928 Self::empty(shape, &self.device())
1929 }
1930 }
1931
1932 /// Repeat the tensor along the given dimensions.
1933 /// # Arguments
1934 /// - `sizes`: Borrowed slice of the number of times to repeat each dimension.
1935 ///
1936 /// # Returns
1937 ///
1938 /// A new tensor with the given dimensions repeated `times` times.
1939 ///
1940 /// # Panics
1941 ///
1942 /// If `sizes` contains more elements than the number of dimensions.
1943 ///
1944 /// # Example
1945 ///
1946 /// ```rust
1947 ///
1948 /// use burn_tensor::backend::Backend;
1949 /// use burn_tensor::Tensor;
1950 ///
1951 /// fn example<B: Backend>() {
1952 /// let device = Default::default();
1953 /// // Create a 2D tensor with dimensions [3, 2]
1954 /// let tensor = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
1955 ///
1956 /// // Repeat the tensor along the dimension 0 twice and the dimension 0 once.
1957 /// // [[3.0, 4.9], [2.0, 1.9], [4.0, 5.9], [3.0, 4.9], [2.0, 1.9], [4.0, 5.9]]
1958 /// // The resulting tensor will have dimensions [6, 2].
1959 /// let repeated = tensor.repeat(&[2, 1]);
1960 /// }
1961 /// ```
1962 pub fn repeat(self, sizes: &[usize]) -> Self {
1963 if sizes.contains(&0) {
1964 let mut shape = self.shape();
1965 for (dim, ×) in sizes.iter().enumerate() {
1966 shape = shape.repeat(dim, times).unwrap();
1967 }
1968
1969 return Self::empty(shape, &self.device());
1970 }
1971
1972 let mut tensor = self;
1973 for (dim, ×) in sizes.iter().enumerate() {
1974 if times > 1 {
1975 tensor = tensor.repeat_dim(dim, times);
1976 }
1977 }
1978 tensor
1979 }
1980
1981 /// Applies element-wise equal comparison.
1982 ///
1983 /// # Returns
1984 /// A boolean tensor that is `true` where input is equal to `other` and `false` elsewhere.
1985 ///
1986 /// # Panics
1987 ///
1988 /// If the two tensors don't have the same shape.
1989 ///
1990 /// # Example
1991 ///
1992 /// ```rust
1993 /// use burn_tensor::backend::Backend;
1994 /// use burn_tensor::Tensor;
1995 ///
1996 /// fn example<B: Backend>() {
1997 /// let device = Default::default();
1998 /// let t1 = Tensor::<B, 2>::from_data([[2.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
1999 /// let t2 = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
2000 /// // Compare the elements of the two 2D tensors with dimensions [3, 2].
2001 /// // [[false, true], [true, true], [true, true]]
2002 /// let equal = t1.equal(t2);
2003 /// println!("{equal}");
2004 /// }
2005 /// ```
2006 pub fn equal(self, other: Self) -> Tensor<B, D, Bool> {
2007 check!(TensorCheck::binary_ops_ew("Equal", &self, &other));
2008 Tensor::new(K::equal(self.primitive, other.primitive))
2009 }
2010
2011 /// Applies element-wise non-equality comparison.
2012 ///
2013 /// # Returns
2014 /// A boolean tensor that is `true` where input is not equal to `other` and `false` elsewhere.
2015 ///
2016 /// # Panics
2017 ///
2018 /// If the two tensors don't have the same shape.
2019 ///
2020 /// # Example
2021 ///
2022 /// ```rust
2023 /// use burn_tensor::backend::Backend;
2024 /// use burn_tensor::Tensor;
2025 ///
2026 /// fn example<B: Backend>() {
2027 /// let device = Default::default();
2028 /// let t1 = Tensor::<B, 2>::from_data([[2.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
2029 /// let t2 = Tensor::<B, 2>::from_data([[3.0, 4.9], [2.0, 1.9], [4.0, 5.9]], &device);
2030 /// // Compare the elements of the two 2D tensors for inequality.
2031 /// // [[true, false], [false, false], [false, false]]
2032 /// let not_equal = t1.not_equal(t2);
2033 /// println!("{not_equal}");
2034 /// }
2035 /// ```
2036 pub fn not_equal(self, other: Self) -> Tensor<B, D, Bool> {
2037 check!(TensorCheck::binary_ops_ew("NotEqual", &self, &other));
2038 Tensor::new(K::not_equal(self.primitive, other.primitive))
2039 }
2040
2041 /// Applies element wise equal comparison and returns a boolean tensor.
2042 ///
2043 /// # Arguments
2044 ///
2045 /// * `other` - The element to compare.
2046 ///
2047 /// # Example
2048 ///
2049 /// ```rust
2050 /// use burn_tensor::backend::Backend;
2051 /// use burn_tensor::{Tensor, Shape};
2052 ///
2053 /// fn example<B: Backend>() {
2054 /// let device = B::Device::default();
2055 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
2056 /// let tensor = tensor.equal_elem(3.0);
2057 /// println!("{tensor}");
2058 /// // [[false, false, true], [false, false, false]]
2059 /// }
2060 /// ```
2061 pub fn equal_elem<E: Element>(self, other: E) -> Tensor<B, D, Bool> {
2062 let other = Scalar::new(other, &self.dtype());
2063 Tensor::new(K::equal_elem(self.primitive, other))
2064 }
2065
2066 /// Applies element wise non-equality comparison and returns a boolean tensor.
2067 ///
2068 /// # Arguments
2069 ///
2070 /// * `other` - The element to compare.
2071 ///
2072 /// # Example
2073 ///
2074 /// ```rust
2075 /// use burn_tensor::backend::Backend;
2076 /// use burn_tensor::{Tensor, Shape};
2077 ///
2078 /// fn example<B: Backend>() {
2079 /// let device = B::Device::default();
2080 /// let tensor = Tensor::<B, 2>::from_data([[1.0, -2.0, 3.0], [5.0, 9.0, 6.0]], &device);
2081 /// let tensor = tensor.not_equal_elem(3.0);
2082 /// println!("{tensor}");
2083 /// // [[true, true, false], [true, true, true]]
2084 /// }
2085 /// ```
2086 pub fn not_equal_elem<E: Element>(self, other: E) -> Tensor<B, D, Bool> {
2087 let other = Scalar::new(other, &self.dtype());
2088 Tensor::new(K::not_equal_elem(self.primitive, other))
2089 }
2090
2091 /// Concatenates all tensors into a new one along the given dimension.
2092 ///
2093 /// # Panics
2094 ///
2095 /// - If `dim` is higher than the rank.
2096 /// - If `tensors` is an empty vector.
2097 /// - If all tensors don't have the same shape (the dimension `dim` is ignored).
2098 ///
2099 /// # Example
2100 ///
2101 /// ```rust
2102 /// use burn_tensor::backend::Backend;
2103 /// use burn_tensor::Tensor;
2104 ///
2105 /// fn example<B: Backend>() {
2106 /// let device = Default::default();
2107 /// let t1 = Tensor::<B, 2>::from_data([[3.0, 4.9, 2.0, 1.0], [2.0, 1.9, 3.0, 1.0]], &device);
2108 /// let t2 = Tensor::<B, 2>::from_data([[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]], &device);
2109 ///
2110 /// // Concatenate the two tensors with shapes [2, 4] and [2, 3] along the dimension 1.
2111 /// // [[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]]
2112 /// // The resulting tensor will have shape [2, 7].
2113 /// let concat = Tensor::cat(vec![t1, t2], 1);
2114 /// println!("{concat}");
2115 /// }
2116 /// ```
2117 pub fn cat(tensors: Vec<Self>, dim: usize) -> Self {
2118 check!(TensorCheck::cat(&tensors, dim));
2119
2120 // Filter out tensors with size 0 along the concatenation dimension.
2121 // Empty tensors don't contribute to the output and would cause issues
2122 // in backend implementations (e.g., division by zero in slice_assign).
2123 // Safety: TensorCheck::cat ensures tensors is non-empty
2124 let first_tensor = tensors.first().unwrap();
2125 let device = first_tensor.device();
2126 let mut shape = first_tensor.shape();
2127
2128 let non_empty_primitives: Vec<_> = tensors
2129 .into_iter()
2130 .filter(|t| t.shape().dims[dim] > 0)
2131 .map(|t| t.primitive)
2132 .collect();
2133
2134 // If all tensors were empty, return an empty tensor with size 0 on concat dim
2135 if non_empty_primitives.is_empty() {
2136 shape.dims[dim] = 0;
2137 return Self::empty(shape, &device);
2138 }
2139
2140 Self::new(K::cat(non_empty_primitives, dim))
2141 }
2142
2143 /// Concatenates all tensors into a new one along a new dimension.
2144 ///
2145 /// # Panics
2146 ///
2147 /// - If all tensors don't have the same shape.
2148 /// - If given dimension is not with range of 0..D2
2149 ///
2150 /// # Example
2151 ///
2152 /// ```rust
2153 /// use burn_tensor::backend::Backend;
2154 /// use burn_tensor::Tensor;
2155 ///
2156 /// fn example<B: Backend>() {
2157 /// let device = Default::default();
2158 /// let t1 = Tensor::<B, 2>::from_data([[3.0, 4.9, 2.0], [2.0, 1.9, 3.0]], &device);
2159 /// let t2 = Tensor::<B, 2>::from_data([[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]], &device);
2160 /// let t3 = Tensor::<B, 2>::from_data([[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]], &device);
2161 ///
2162 /// // Concatenate the three tensors with shape [2, 3] along a new dimension, 0.
2163 /// // [[[3.0, 4.9, 2.0], [2.0, 1.9, 3.0]],
2164 /// // [[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]],
2165 /// // [[4.0, 5.9, 8.0], [1.4, 5.8, 6.0]]]
2166 /// // The resulting tensor will have shape [3, 2, 3].
2167 /// let stacked= Tensor::stack::<3>(vec![t1, t2, t3], 0);
2168 /// println!("{stacked}");
2169 /// }
2170 /// ```
2171 pub fn stack<const D2: usize>(tensors: Vec<Tensor<B, D, K>>, dim: usize) -> Tensor<B, D2, K> {
2172 check!(TensorCheck::stack::<B, D, K, D2>(&tensors, dim));
2173 let tensors = tensors.into_iter().map(|t| t.unsqueeze_dim(dim)).collect();
2174 Tensor::<B, D2, K>::cat(tensors, dim)
2175 }
2176
2177 /// Iterate over slices of tensors alongside a given dimension.
2178 ///
2179 /// # Panics
2180 ///
2181 /// If given dimension is greater than or equal to tensor rank.
2182 ///
2183 /// # Returns
2184 ///
2185 /// A tensor iterator.
2186 ///
2187 /// # Example
2188 ///
2189 /// ```rust
2190 /// use burn_tensor::backend::Backend;
2191 /// use burn_tensor::Tensor;
2192 /// fn example<B: Backend>() {
2193 /// let device = Default::default();
2194 /// let tensor = Tensor::<B,2>::from_data([[3.0, 4.9, 2.0], [2.0, 1.9, 3.0]], &device);
2195 /// // Given a 2D tensor with dimensions [2, 3], iterate over slices of tensors along the dimension 0.
2196 /// let iter = tensor.iter_dim(0);
2197 /// for (i,tensor) in iter.enumerate() {
2198 /// println!("Tensor {}: {}", i, tensor);
2199 /// // Tensor 0: Tensor { data: [[3.0, 4.9, 2.0]], ... }
2200 /// // Tensor 1: Tensor { data: [[2.0, 1.9, 3.0]], ... }
2201 /// }
2202 /// }
2203 /// ```
2204 pub fn iter_dim(self, dim: usize) -> DimIter<B, D, K> {
2205 check!(TensorCheck::dim_ops::<D>("iter_dim", dim));
2206 DimIter::new(self, dim)
2207 }
2208
2209 /// Returns a new tensor with the given dimension narrowed to the given range.
2210 ///
2211 /// # Panics
2212 ///
2213 /// - If the dimension is greater than the number of dimensions of the tensor.
2214 /// - If the given range exceeds the number of elements on the given dimension.
2215 ///
2216 /// # Returns
2217 ///
2218 /// A new tensor with the given dimension narrowed to the given range.
2219 ///
2220 /// # Example
2221 ///
2222 /// ```rust
2223 /// use burn_tensor::backend::Backend;
2224 /// use burn_tensor::Tensor;
2225 ///
2226 /// fn example<B: Backend>() {
2227 /// let device = Default::default();
2228 /// // Create a 2D tensor with dimensions [4, 3]
2229 /// let tensor = Tensor::<B, 2>::from_data(
2230 /// [
2231 /// [3.0, 4.9, 2.0],
2232 /// [2.0, 1.9, 3.0],
2233 /// [6.0, 1.5, 7.0],
2234 /// [3.0, 4.9, 9.0],
2235 /// ],
2236 /// &device,
2237 /// );
2238 /// // Narrow the tensor along the dimension 0, keeping 3 elements starting from index 1.
2239 /// // [[2.0, 1.9, 3.0], [6.0, 1.5, 7.0], [3.0, 4.9, 9.0]]
2240 /// // The resulting tensor will have dimensions [3, 3].
2241 /// let narrowed = tensor.narrow(0, 1, 3);
2242 /// println!("{narrowed}");
2243 /// }
2244 /// ```
2245 pub fn narrow(self, dim: usize, start: usize, length: usize) -> Self {
2246 check!(TensorCheck::dim_ops::<D>("narrow", dim));
2247 check!(TensorCheck::narrow(&self, dim, start, length));
2248 let dims = self.dims();
2249
2250 let ranges: [Range<usize>; D] = dims
2251 .iter()
2252 .enumerate()
2253 .map(|(i, d)| {
2254 if i == dim {
2255 start..(start + length)
2256 } else {
2257 0..*d
2258 }
2259 })
2260 .collect::<Vec<_>>()
2261 .try_into()
2262 .unwrap();
2263
2264 Self::slice(self, ranges)
2265 }
2266
2267 /// Attempts to split the tensor into a specified number of chunks along a given dimension.
2268 /// May return less chunks than requested if the tensor size is not divisible by the number of chunks.
2269 ///
2270 /// When the given dimension is evenly divisible by the number of chunks, the chunks will be of equal size.
2271 /// Otherwise all chunks will be of equal size except for the last one.
2272 ///
2273 /// # Panics
2274 ///
2275 /// If the dimension is greater than the number of dimensions of the tensor.
2276 ///
2277 /// # Returns
2278 /// A vector of tensors.
2279 ///
2280 /// # Example
2281 ///
2282 /// ```rust
2283 /// use burn_tensor::backend::Backend;
2284 /// use burn_tensor::Tensor;
2285 ///
2286 /// fn example<B: Backend>() {
2287 /// let device = Default::default();
2288 /// // Create a 2D tensor with dimensions [4, 3]
2289 /// let tensor = Tensor::<B, 2>::from_data(
2290 /// [
2291 /// [3.0, 4.9, 2.0],
2292 /// [2.0, 1.9, 3.0],
2293 /// [6.0, 1.5, 7.0],
2294 /// [3.0, 4.9, 9.0],
2295 /// ],
2296 /// &device,
2297 /// );
2298 /// // Split the tensor along the dimension 1 into 2 chunks.
2299 /// // The first chuck will have shape [4, 2]:
2300 /// // [[3.0, 4.9], [2.0, 1.9], [6.0, 1.5], [3.0, 4.9]]
2301 /// // The second chunk will have shape [4, 1]:
2302 /// // [[2.0], [3.0], [7.0], [9.0]]
2303 /// let chunks = tensor.chunk(2, 1);
2304 /// println!("{chunks:?}");
2305 /// }
2306 /// ```
2307 pub fn chunk(self, chunks: usize, dim: usize) -> Vec<Self> {
2308 check!(TensorCheck::dim_ops::<D>("chunk", dim));
2309 let size = self.shape().dims[dim];
2310 if size < chunks {
2311 return (0..size)
2312 .map(|i| Self::narrow(self.clone(), dim, i, 1))
2313 .collect();
2314 }
2315
2316 let mut tensors = Vec::with_capacity(chunks);
2317 let mut sum_chunk_size = 0;
2318 if size.is_multiple_of(chunks) {
2319 let chunk_size = size / chunks;
2320 for _ in 0..chunks {
2321 tensors.push(Self::narrow(self.clone(), dim, sum_chunk_size, chunk_size));
2322 sum_chunk_size += chunk_size;
2323 }
2324 } else {
2325 let chunk_size = (size / chunks) + 1; // assumes not divisible
2326 for _ in 0..chunks - 1 {
2327 tensors.push(Self::narrow(self.clone(), dim, sum_chunk_size, chunk_size));
2328 sum_chunk_size += chunk_size;
2329 }
2330 let remainder = size % chunk_size;
2331 tensors.push(Self::narrow(self.clone(), dim, sum_chunk_size, remainder));
2332 }
2333
2334 tensors
2335 }
2336
2337 /// Splits the tensor into chunks of a specified size along a given dimension.
2338 /// Each chunk is a view of the original tensor.
2339 ///
2340 /// If the tensor size along the given dimension is not divisible by `split_size`,
2341 /// then the last chunk will be smaller.
2342 ///
2343 /// # Panics
2344 ///
2345 /// If the specified dimension to split along is greater than the number of dimensions of the tensor.
2346 ///
2347 /// # Returns
2348 ///
2349 /// A vector of tensors.
2350 ///
2351 /// # Example
2352 /// ```rust
2353 /// use burn_tensor::backend::Backend;
2354 /// use burn_tensor::Tensor;
2355 ///
2356 /// fn example<B: Backend>() {
2357 /// let device = Default::default();
2358 /// // Create a 1D tensor with 5 elements
2359 /// let tensor = Tensor::<B, 1>::from_data([0.0, 1.0, 2.0, 3.0, 4.0], &device);
2360 /// // Split the tensor into chunks of size 2 along dimension 0
2361 /// let chunks = tensor.split(2, 0);
2362 /// // The result is a vector of tensors:
2363 /// // [Tensor([0.0, 1.0]), Tensor([2.0, 3.0]), Tensor([4.0])]
2364 /// println!("{:?}", chunks);
2365 /// }
2366 /// ```
2367 pub fn split(self, split_size: usize, dim: usize) -> Vec<Self> {
2368 check!(TensorCheck::split::<D>(&self.shape(), split_size, dim));
2369 let size = self.shape().dims[dim];
2370 let mut tensors = Vec::new();
2371
2372 let mut start = 0;
2373 while start < size {
2374 let length = usize::min(split_size, size - start);
2375 tensors.push(Self::narrow(self.clone(), dim, start, length));
2376 start += length;
2377 }
2378
2379 tensors
2380 }
2381
2382 /// Splits the tensor into chunks with the specified sizes along a given dimension.
2383 /// Each chunk is a view of the original tensor.
2384 ///
2385 /// The sizes of the chunks are specified in the `split_sizes` vector. The sum of the sizes
2386 /// in `split_sizes` must equal the size of the tensor along the specified dimension.
2387 ///
2388 /// # Panics
2389 ///
2390 /// If the specified dimension to split along is greater than the number of dimensions of the tensor or
2391 /// if the sum of `dim_sizes` does not equal the size of the tensor along `dim`.
2392 ///
2393 /// # Returns
2394 ///
2395 /// A vector of tensors.
2396 ///
2397 /// # Example
2398 /// ```rust
2399 /// use burn_tensor::backend::Backend;
2400 /// use burn_tensor::Tensor;
2401 ///
2402 /// fn example<B: Backend>() {
2403 /// let device = Default::default();
2404 /// // Create a 1D tensor with 5 elements
2405 /// let tensor = Tensor::<B, 1>::from_data([0.0, 1.0, 2.0, 3.0, 4.0], &device);
2406 /// // Split the tensor into chunks with sizes [2, 3] along dimension 0
2407 /// let chunks = tensor.split_with_sizes(vec![2, 3], 0);
2408 /// // The result is a vector of tensors:
2409 /// // [Tensor([0.0, 1.0]), Tensor([2.0, 3.0, 4.0])]
2410 /// println!("{:?}", chunks);
2411 /// }
2412 /// ```
2413 pub fn split_with_sizes(self, split_sizes: Vec<usize>, dim: usize) -> Vec<Self> {
2414 check!(TensorCheck::split_with_sizes::<D>(
2415 &self.shape(),
2416 &split_sizes,
2417 dim
2418 ));
2419 let mut tensors = Vec::new();
2420
2421 let mut start = 0;
2422 for length in split_sizes {
2423 if length == 0 {
2424 continue;
2425 }
2426 tensors.push(Self::narrow(self.clone(), dim, start, length));
2427 start += length;
2428 }
2429
2430 tensors
2431 }
2432
2433 /// Tests if any element in the `tensor` evaluates to True.
2434 ///
2435 /// # Arguments
2436 ///
2437 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2438 ///
2439 /// # Returns
2440 ///
2441 /// A boolean tensor `Tensor<B, 1, Bool>` containing a single element, True if any element in the input tensor
2442 /// evaluates to True, False otherwise.
2443 ///
2444 /// # Example
2445 ///
2446 /// ```rust
2447 /// use burn_tensor::backend::Backend;
2448 /// use burn_tensor::{Tensor, Bool};
2449 ///
2450 /// fn example<B: Backend>() {
2451 /// let device = Default::default();
2452 /// let tensor = Tensor::<B,2, Bool>::from_data([[true,false,true],[false,true,false]], &device);
2453 /// let tensor_two = Tensor::<B,2, Bool>::from_data([[false,false,false],[false,false,false]], &device);
2454 ///
2455 /// // Given a 2D tensor with dimensions [2, 3], test if any element in the tensor evaluates to True.
2456 /// let any_tensor = tensor.any();
2457 /// println!("{}", any_tensor);
2458 /// // Tensor { data: [true], ... }
2459 ///
2460 /// // Given a 2D tensor with dimensions [2, 3], test if any element in the tensor evaluates to True.
2461 /// let any_tensor_two = tensor_two.any();
2462 /// println!("{}", any_tensor_two);
2463 /// // Tensor { data: [false], ... }
2464 /// }
2465 /// ```
2466 pub fn any(self) -> Tensor<B, 1, Bool> {
2467 Tensor::new(K::any(self.primitive))
2468 }
2469
2470 /// Tests if any element in the `tensor` evaluates to True along a given dimension `dim`.
2471 ///
2472 /// # Arguments
2473 ///
2474 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2475 /// * `dim` - The axis along which to test.
2476 ///
2477 /// # Returns
2478 ///
2479 /// A boolean tensor `Tensor<B, D, Bool>` with the same shape as input `tensor`, except in the `dim` axis
2480 /// where the size is 1. The elem in the `dim` axis is True if any element along this dim in the input
2481 /// evaluates to True, False otherwise.
2482 ///
2483 /// # Example
2484 ///
2485 /// ```rust
2486 /// use burn_tensor::backend::Backend;
2487 /// use burn_tensor::{Tensor, Bool};
2488 ///
2489 /// fn example<B: Backend>() {
2490 /// let device = Default::default();
2491 /// let tensor =
2492 /// Tensor::<B, 2, Bool>::from_data([[true, false, false], [false, true, false]], &device);
2493 /// // Check if any element in the tensor evaluates to True along the dimension 1.
2494 /// // [[true], [true]],
2495 /// let any_dim = tensor.clone().any_dim(1);
2496 /// println!("{any_dim}");
2497 /// }
2498 /// ```
2499 pub fn any_dim(self, dim: usize) -> Tensor<B, D, Bool> {
2500 Tensor::new(K::any_dim(self.primitive, dim))
2501 }
2502
2503 /// Tests if all elements in the `tensor` evaluate to True.
2504 ///
2505 /// # Arguments
2506 ///
2507 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2508 ///
2509 /// # Returns
2510 ///
2511 /// A boolean tensor `Tensor<B, 1, Bool>` with a single element, True if all elements in the input tensor
2512 /// evaluate to True, False otherwise.
2513 ///
2514 /// # Example
2515 ///
2516 /// ```rust
2517 /// use burn_tensor::backend::Backend;
2518 /// use burn_tensor::{Tensor, Bool};
2519 ///
2520 /// fn example<B: Backend>() {
2521 /// let device = Default::default();
2522 /// let tensor =
2523 /// Tensor::<B, 2, Bool>::from_data([[true, false, true], [true, true, true]], &device);
2524 /// // Check if all elements in the tensor evaluate to True (which is not the case).
2525 /// // [false]
2526 /// let all = tensor.all();
2527 /// println!("{all}");
2528 /// }
2529 /// ```
2530 pub fn all(self) -> Tensor<B, 1, Bool> {
2531 Tensor::new(K::all(self.primitive))
2532 }
2533
2534 /// Tests if all elements in the `tensor` evaluate to True along a given dimension `dim`.
2535 ///
2536 /// # Arguments
2537 ///
2538 /// * `tensor` - The tensor to test. All input tensor types (Float, Int, Bool) are supported.
2539 /// * `dim` - The axis along which to test.
2540 ///
2541 /// # Returns
2542 ///
2543 /// A boolean tensor `Tensor<B, D, Bool>` with the same shape as input `tensor`, except in the `dim` axis
2544 /// where the size is 1. The elem in the `dim` axis is True if all elements along this dim in the input
2545 /// evaluates to True, False otherwise.
2546 ///
2547 /// # Example
2548 ///
2549 /// ```rust
2550 /// use burn_tensor::backend::Backend;
2551 /// use burn_tensor::{Tensor, Bool};
2552 ///
2553 /// fn example<B: Backend>() {
2554 /// let device = Default::default();
2555 /// let tensor =
2556 /// Tensor::<B, 2, Bool>::from_data([[true, true, false], [true, true, true]], &device);
2557 /// // Check if all elements in the tensor evaluate to True along the dimension 1.
2558 /// // [[true, true, false]]
2559 /// let all_dim = tensor.clone().all_dim(0);
2560 /// println!("{all_dim}");
2561 /// }
2562 /// ```
2563 pub fn all_dim(self, dim: usize) -> Tensor<B, D, Bool> {
2564 Tensor::new(K::all_dim(self.primitive, dim))
2565 }
2566
2567 /// Convert the tensor into a scalar.
2568 ///
2569 /// # Panics
2570 ///
2571 /// - If the tensor doesn't have one element.
2572 /// - If the backend fails to read the tensor data synchronously.
2573 ///
2574 /// # Returns
2575 ///
2576 /// The scalar value of the tensor.
2577 ///
2578 /// # Example
2579 ///
2580 /// ```rust
2581 /// use burn_tensor::backend::Backend;
2582 /// use burn_tensor::Tensor;
2583 ///
2584 /// fn example<B: Backend>() {
2585 /// let device = Default::default();
2586 /// let tensor = Tensor::<B, 2>::from_data([[3.0]], &device);
2587 /// // Convert the tensor with a single element into a scalar.
2588 /// let scalar = tensor.into_scalar();
2589 /// println!("{scalar}");
2590 /// }
2591 /// ```
2592 pub fn into_scalar(self) -> K::Elem {
2593 crate::try_read_sync(self.into_scalar_async())
2594 .expect(
2595 "Failed to read tensor data synchronously. This can happen on platforms
2596 that don't support blocking futures like WASM. Try into_scalar_async instead.",
2597 )
2598 .expect("Error while reading data: use `try_into_scalar` instead to catch the error at runtime")
2599 }
2600
2601 /// Convert the tensor into a scalar and returns any error that might have occurred since the
2602 /// last time the device was synchronized.
2603 ///
2604 /// # Panics
2605 ///
2606 /// - If the tensor doesn't have one element.
2607 /// - If the backend fails to read the tensor data synchronously.
2608 ///
2609 /// # Returns
2610 ///
2611 /// The scalar value of the tensor.
2612 pub fn try_into_scalar(self) -> Result<K::Elem, ExecutionError> {
2613 crate::try_read_sync(self.into_scalar_async()).expect(
2614 "Failed to read tensor data synchronously. This can happen on platforms
2615 that don't support blocking futures like WASM. Try into_scalar_async instead.",
2616 )
2617 }
2618
2619 /// Convert the tensor into a scalar.
2620 ///
2621 /// # Panics
2622 ///
2623 /// If the tensor doesn't have one element.
2624 pub async fn into_scalar_async(self) -> Result<K::Elem, ExecutionError> {
2625 check!(TensorCheck::into_scalar::<D>(&self.shape()));
2626
2627 Ok(self.into_data_async().await?.iter().next().unwrap())
2628 }
2629
2630 /// Broadcast the tensor to the given shape.
2631 ///
2632 /// Only singleton dimensions can be expanded to a larger size. Other dimensions must have the same size
2633 /// (which can be inferred with `-1`).
2634 ///
2635 /// # Arguments
2636 ///
2637 /// * `shape` - The shape to broadcast the tensor to.
2638 /// Can contain -1 for dimensions that should be inferred.
2639 /// The number of elements in the shape must be greater or equal as
2640 /// the number of dimensions of the tensor.
2641 ///
2642 /// # Panics
2643 ///
2644 /// If the tensor cannot be broadcasted to the given shape.
2645 ///
2646 /// # Returns
2647 ///
2648 /// A new tensor with the given shape.
2649 ///
2650 /// # Example
2651 ///
2652 /// ```rust
2653 /// use burn_tensor::backend::Backend;
2654 /// use burn_tensor::Tensor;
2655 ///
2656 /// fn example<B: Backend>() {
2657 /// let device = Default::default();
2658 /// // Create a 2D tensor with dimensions [3, 1]
2659 /// let tensor = Tensor::<B, 2>::from_data([[1.], [2.], [3.]], &device);
2660 /// // Expand the tensor to a new shape [3, 4]
2661 /// // [[1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0]]
2662 /// let expanded = tensor.expand([3, 4]);
2663 /// println!("{}", expanded);
2664 /// }
2665 /// ```
2666 pub fn expand<const D2: usize, S: BroadcastArgs<D, D2>>(self, shape: S) -> Tensor<B, D2, K> {
2667 let shape = shape.into_shape(&self.shape());
2668 check!(TensorCheck::expand::<D, D2>(
2669 "expand",
2670 &self.shape(),
2671 &shape,
2672 ));
2673
2674 Tensor::<B, D2, K>::new(K::expand(self.primitive, shape))
2675 }
2676
2677 /// Unfold windows along a dimension.
2678 ///
2679 /// Returns a view of the tensor with all complete windows of size `size` in dimension `dim`;
2680 /// where windows are advanced by `step` at each index.
2681 ///
2682 /// The number of windows is `max(0, (shape[dim] - size).ceil_div(step))`.
2683 ///
2684 /// The new view will have the unfolded dimension replaced by two dimensions;
2685 /// one in the position of the original dimension, with size equal to the number of windows,
2686 /// and one appended to the right-most position, with size equal to `size`.
2687 ///
2688 /// # Warning
2689 ///
2690 /// For the `ndarray` backend; this is not a view but a copy
2691 /// with duplicated data.
2692 ///
2693 /// # Arguments
2694 ///
2695 /// * `dim` - the dimension to unfold.
2696 /// * `size` - the size of each unfolded window.
2697 /// * `step` - the step between each window.
2698 ///
2699 /// # Returns
2700 ///
2701 /// A tensor view with the shape ``[pre=..., windows, post=..., size]``.
2702 pub fn unfold<const D2: usize, I: AsIndex>(
2703 self,
2704 dim: I,
2705 size: usize,
2706 step: usize,
2707 ) -> Tensor<B, D2, K> {
2708 let dim = dim.expect_dim_index(D);
2709 check!(TensorCheck::unfold::<D, D2>(
2710 "unfold",
2711 &self.shape(),
2712 dim,
2713 size,
2714 step,
2715 ));
2716 Tensor::<B, D2, K>::new(K::unfold(self.primitive, dim, size, step))
2717 }
2718}
2719
2720/// Iterator given by (Tensor::iter_dim).
2721pub struct DimIter<B, const D: usize, K>
2722where
2723 B: Backend,
2724 K: BasicOps<B>,
2725{
2726 start: usize,
2727 end: usize,
2728 dim: usize,
2729 ranges: [Range<usize>; D],
2730 tensor: Tensor<B, D, K>,
2731}
2732
2733impl<B: Backend, const D: usize, K: BasicOps<B>> Iterator for DimIter<B, D, K> {
2734 type Item = Tensor<B, D, K>;
2735
2736 fn next(&mut self) -> Option<Self::Item> {
2737 if self.start >= self.end {
2738 return None;
2739 }
2740
2741 let mut ranges = self.ranges.clone();
2742 ranges[self.dim] = self.start..(self.start + 1);
2743
2744 let slice = self.tensor.clone().slice(ranges);
2745 self.start += 1;
2746
2747 Some(slice)
2748 }
2749}
2750
2751impl<B: Backend, const D: usize, K: BasicOps<B>> DoubleEndedIterator for DimIter<B, D, K> {
2752 fn next_back(&mut self) -> Option<Self::Item> {
2753 if self.start >= self.end {
2754 return None;
2755 }
2756
2757 let mut ranges = self.ranges.clone();
2758 ranges[self.dim] = (self.end - 1)..self.end;
2759
2760 let slice = self.tensor.clone().slice(ranges);
2761 self.end = self.end.saturating_sub(1);
2762
2763 Some(slice)
2764 }
2765}
2766
2767impl<B: Backend, const D: usize, K: BasicOps<B>> DimIter<B, D, K> {
2768 fn new(tensor: Tensor<B, D, K>, dim: usize) -> Self {
2769 let dims = tensor.dims();
2770 let ranges = dims
2771 .iter()
2772 .map(|&dim| 0..dim)
2773 .collect::<Vec<Range<usize>>>();
2774 let ranges: [Range<usize>; D] = ranges.try_into().unwrap();
2775 Self {
2776 end: dims[dim],
2777 ranges,
2778 start: 0,
2779 dim,
2780 tensor,
2781 }
2782 }
2783}
2784
2785impl<B, const D: usize, K> Tensor<B, D, K>
2786where
2787 B: Backend,
2788 K: BasicOps<B>,
2789 <K as BasicOps<B>>::Elem: Debug,
2790{
2791 #[inline]
2792 fn push_newline_indent(acc: &mut String, indent: usize) {
2793 acc.push('\n');
2794 for _ in 0..indent {
2795 acc.push(' ');
2796 }
2797 }
2798 fn fmt_inner_tensor(
2799 &self,
2800 acc: &mut String,
2801 depth: usize,
2802 multi_index: &mut [usize],
2803 range: (usize, usize),
2804 precision: Option<usize>,
2805 ) {
2806 let (start, end) = range;
2807 for i in start..end {
2808 if i > 0 {
2809 acc.push_str(", ");
2810 }
2811 multi_index[depth] = i;
2812 let range: [Range<usize>; D] =
2813 core::array::from_fn(|i| multi_index[i]..multi_index[i] + 1);
2814
2815 let data = burn_std::reader::try_read_sync(self.clone().slice(range).into_data_async());
2816
2817 if let Some(Ok(data)) = data {
2818 let elem = data.iter::<<K as BasicOps<B>>::Elem>().next().unwrap();
2819 match (precision, K::name()) {
2820 (Some(p), "Float") => acc.push_str(&format!("{elem:.p$}")),
2821 (_, "Bool") => acc.push_str(&format!("{}", elem.to_bool())),
2822 _ => acc.push_str(&format!("{elem:?}")),
2823 }
2824 } else {
2825 acc.push_str("<Tensor data not available>");
2826 }
2827 }
2828 }
2829
2830 fn fmt_outer_tensor(
2831 &self,
2832 acc: &mut String,
2833 depth: usize,
2834 multi_index: &mut [usize],
2835 print_options: &PrintOptions,
2836 summarize: bool,
2837 range: (usize, usize),
2838 ) {
2839 let (start, end) = range;
2840 for i in start..end {
2841 if i > start {
2842 acc.push(',');
2843 Self::push_newline_indent(acc, depth + 1);
2844 }
2845 acc.push('[');
2846 multi_index[depth] = i;
2847 self.display_recursive(acc, depth + 1, multi_index, print_options, summarize);
2848 acc.push(']');
2849 }
2850 }
2851
2852 /// Recursively formats the tensor data for display and appends it to the provided accumulator string.
2853 ///
2854 /// This function is designed to work with tensors of any dimensionality.
2855 /// It traverses the tensor dimensions recursively, converting the elements
2856 /// to strings and appending them to the accumulator string with the
2857 /// appropriate formatting.
2858 ///
2859 /// # Arguments
2860 ///
2861 /// * `acc` - A mutable reference to a `String` used as an accumulator for the formatted output.
2862 /// * `depth` - The current depth of the tensor dimensions being processed.
2863 /// * `multi_index` - A mutable slice of `usize` representing the current indices in each dimension.
2864 fn display_recursive(
2865 &self,
2866 acc: &mut String,
2867 depth: usize,
2868 multi_index: &mut [usize],
2869 print_options: &PrintOptions,
2870 summarize: bool,
2871 ) {
2872 let edge_items = print_options.edge_items;
2873
2874 if depth == 0 {
2875 acc.push('[');
2876 }
2877
2878 if depth == self.dims().len() - 1 {
2879 // if we are at the innermost dimension, just push its elements into the accumulator
2880 if summarize && self.dims()[depth] > 2 * edge_items {
2881 // print the starting `edge_items` elements
2882 self.fmt_inner_tensor(
2883 acc,
2884 depth,
2885 multi_index,
2886 (0, edge_items),
2887 print_options.precision,
2888 );
2889 acc.push_str(", ...");
2890 // print the last `edge_items` elements
2891 self.fmt_inner_tensor(
2892 acc,
2893 depth,
2894 multi_index,
2895 (self.dims()[depth] - edge_items, self.dims()[depth]),
2896 print_options.precision,
2897 );
2898 } else {
2899 // print all the elements
2900 self.fmt_inner_tensor(
2901 acc,
2902 depth,
2903 multi_index,
2904 (0, self.dims()[depth]),
2905 print_options.precision,
2906 );
2907 }
2908 } else {
2909 // otherwise, iterate through the current dimension and recursively display the inner tensors
2910 if summarize && self.dims()[depth] > 2 * edge_items {
2911 self.fmt_outer_tensor(
2912 acc,
2913 depth,
2914 multi_index,
2915 print_options,
2916 summarize,
2917 (0, edge_items),
2918 );
2919
2920 acc.push(',');
2921 Self::push_newline_indent(acc, depth + 1);
2922 acc.push_str("...");
2923 Self::push_newline_indent(acc, depth + 1);
2924
2925 self.fmt_outer_tensor(
2926 acc,
2927 depth,
2928 multi_index,
2929 print_options,
2930 summarize,
2931 (self.dims()[depth] - edge_items, self.dims()[depth]),
2932 );
2933 } else {
2934 self.fmt_outer_tensor(
2935 acc,
2936 depth,
2937 multi_index,
2938 print_options,
2939 summarize,
2940 (0, self.dims()[depth]),
2941 );
2942 }
2943 }
2944
2945 if depth == 0 {
2946 acc.push(']');
2947 }
2948 }
2949}
2950
2951#[derive(Clone, Debug)]
2952/// Options for Tensor pretty printing
2953pub struct PrintOptions {
2954 /// number of elements to start summarizing tensor
2955 pub threshold: usize,
2956
2957 /// number of starting elements and ending elements to display
2958 pub edge_items: usize,
2959
2960 /// Precision for floating point numbers
2961 pub precision: Option<usize>,
2962}
2963
2964static PRINT_OPTS: RwLock<PrintOptions> = RwLock::new(PrintOptions::const_default());
2965
2966impl PrintOptions {
2967 /// Print options with default values
2968 pub const fn const_default() -> Self {
2969 Self {
2970 threshold: 1000,
2971 edge_items: 3,
2972 precision: None,
2973 }
2974 }
2975}
2976
2977impl Default for PrintOptions {
2978 fn default() -> Self {
2979 Self::const_default()
2980 }
2981}
2982
2983/// Set print options
2984pub fn set_print_options(options: PrintOptions) {
2985 let mut print_opts = PRINT_OPTS.write().unwrap();
2986 *print_opts = options;
2987}
2988
2989/// Pretty print tensors
2990impl<B, const D: usize, K> core::fmt::Display for Tensor<B, D, K>
2991where
2992 B: Backend,
2993 B::IntElem: core::fmt::Display,
2994 K: BasicOps<B>,
2995 <K as BasicOps<B>>::Elem: Debug,
2996{
2997 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2998 writeln!(f, "Tensor {{")?;
2999
3000 {
3001 // Do not lock the mutex for the whole function
3002 let mut po = { PRINT_OPTS.read().unwrap().clone() };
3003
3004 // Override the precision if it is set from the formatter
3005 // This will be possible when the tensor is printed using the `{:.*}` syntax
3006 if let Some(precision) = f.precision() {
3007 po.precision = Some(precision);
3008 }
3009
3010 let mut acc = String::new();
3011 let mut multi_index = vec![0; D];
3012 let summarize = self.shape().num_elements() > po.threshold;
3013
3014 self.display_recursive(&mut acc, 0, &mut multi_index, &po, summarize);
3015
3016 writeln!(f, " data:")?;
3017 write!(f, "{acc}")?;
3018 writeln!(f, ",")?;
3019 }
3020
3021 writeln!(f, " shape: {:?},", self.dims())?;
3022 writeln!(f, " device: {:?},", self.device())?;
3023 writeln!(f, " backend: {:?},", B::name(&self.device()))?;
3024 writeln!(f, " kind: {:?},", K::name())?;
3025
3026 let dtype = self.primitive.dtype();
3027
3028 writeln!(f, " dtype: {:?},", dtype.name())?;
3029 write!(f, "}}")
3030 }
3031}
3032
3033/// Trait used for movedim arguments
3034pub trait MovedimArgs {
3035 /// Converts into a set of dimensions `Vec<usize>` for the `tensor.movedim()` function
3036 fn into_dim_vec<const D: usize>(self) -> Vec<usize>;
3037}
3038
3039impl MovedimArgs for Vec<i32> {
3040 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3041 let set = self
3042 .iter()
3043 .map(|&dim| {
3044 if dim < 0 {
3045 (D as i32 + dim) as usize
3046 } else {
3047 dim as usize
3048 }
3049 })
3050 .collect::<Vec<usize>>();
3051 check!(TensorCheck::movedim_args_vec::<D>(&set));
3052
3053 set
3054 }
3055}
3056
3057impl MovedimArgs for Vec<usize> {
3058 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3059 check!(TensorCheck::movedim_args_vec::<D>(&self));
3060 self
3061 }
3062}
3063
3064impl MovedimArgs for usize {
3065 #[allow(clippy::vec_init_then_push)]
3066 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3067 check!(TensorCheck::movedim_args_usize::<D>(self));
3068
3069 let mut set = Vec::with_capacity(1);
3070 set.push(self);
3071
3072 set
3073 }
3074}
3075
3076impl MovedimArgs for i32 {
3077 #[allow(clippy::vec_init_then_push)]
3078 fn into_dim_vec<const D: usize>(self) -> Vec<usize> {
3079 check!(TensorCheck::movedim_args_i32::<D>(self));
3080
3081 let dim = if self < 0 {
3082 (D as i32 + self) as usize
3083 } else {
3084 self as usize
3085 };
3086
3087 let mut set = Vec::with_capacity(1);
3088 set.push(dim);
3089
3090 set
3091 }
3092}
3093
3094/// Trait used for reshape arguments.
3095pub trait ReshapeArgs<const D2: usize>: Debug {
3096 /// Converts to a shape.
3097 fn into_shape<const D: usize>(self, source: Shape) -> Shape;
3098}
3099
3100impl<const D2: usize, I: AsIndex> ReshapeArgs<D2> for [I; D2] {
3101 fn into_shape<const D: usize>(self, source: Shape) -> Shape {
3102 unwrap_shape_reshape(source.reshape(self))
3103 }
3104}
3105
3106impl<const D2: usize> ReshapeArgs<D2> for Shape {
3107 fn into_shape<const D: usize>(self, source: Shape) -> Shape {
3108 unwrap_shape_reshape(source.reshape(self))
3109 }
3110}
3111
3112/// Trait used for broadcast arguments.
3113pub trait BroadcastArgs<const D1: usize, const D2: usize> {
3114 /// Converts to a shape.
3115 fn into_shape(self, shape: &Shape) -> Shape;
3116}
3117
3118impl<const D1: usize, const D2: usize> BroadcastArgs<D1, D2> for Shape {
3119 fn into_shape(self, _shape: &Shape) -> Shape {
3120 self
3121 }
3122}
3123
3124impl<const D1: usize, const D2: usize, E: AsIndex> BroadcastArgs<D1, D2> for [E; D2] {
3125 // Passing -1 as the size for a dimension means not changing the size of that dimension.
3126 fn into_shape(self, shape: &Shape) -> Shape {
3127 if self.len() < shape.num_dims() {
3128 panic!("Broadcast arguments must be greater than the number of dimensions");
3129 }
3130
3131 // Zip the two shapes in reverse order and replace -1 with the actual dimension value.
3132 let new_shape: Vec<_> = self
3133 .iter()
3134 .rev()
3135 .map(|x| {
3136 let primitive = x.as_index();
3137 if primitive < -1 || primitive == 0 {
3138 panic!("Broadcast arguments must be positive or -1");
3139 }
3140 primitive
3141 })
3142 .zip(shape.iter().rev().chain(repeat(&0)).take(self.len())) // Pad the original shape with 0s
3143 .map(|(x, &y)| if x == -1 { y } else { x as usize })
3144 .collect::<Vec<_>>()
3145 .into_iter()
3146 .rev()
3147 .collect();
3148
3149 if new_shape.contains(&0) {
3150 panic!("Cannot substitute -1 for a non-existing dimension");
3151 }
3152
3153 let new_shape: [usize; D2] = new_shape.try_into().unwrap();
3154
3155 Shape::from(new_shape)
3156 }
3157}
3158
3159impl<B, const D: usize, K> Serialize for Tensor<B, D, K>
3160where
3161 B: Backend,
3162 K: BasicOps<B>,
3163 K::Elem: Debug + Copy + Serialize,
3164{
3165 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3166 let data = self.to_data();
3167 data.serialize(serializer)
3168 }
3169}
3170
3171impl<'de, B, const D: usize, K> Deserialize<'de> for Tensor<B, D, K>
3172where
3173 B: Backend,
3174 K: BasicOps<B>,
3175 K::Elem: Debug + Copy + Deserialize<'de>,
3176{
3177 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
3178 let tensor = Tensor::from_data(
3179 TensorData::deserialize(deserializer)?,
3180 &<B::Device as Default>::default(),
3181 );
3182 Ok(tensor)
3183 }
3184}
3185
3186#[cfg(test)]
3187mod tests {
3188 use crate::{Shape, s};
3189
3190 #[test]
3191 fn slice_range_single_dim_leading() {
3192 let shape = Shape::new([8, 4]);
3193
3194 // Half-open range
3195 let slices = shape.clone().into_slices([0..5]);
3196 assert_eq!(slices[0].to_range(8), 0..5);
3197 let slices = shape.clone().into_slices([-3..-1]);
3198 assert_eq!(slices[0].to_range(8), 5..7);
3199
3200 // Inclusive range
3201 let slices = shape.clone().into_slices([0..=4]);
3202 assert_eq!(slices[0].to_range(8), 0..5);
3203 let slices = shape.clone().into_slices([-2..=-1]);
3204 assert_eq!(slices[0].to_range(8), 6..8);
3205
3206 // Unbounded start
3207 let slices = shape.clone().into_slices([..3]);
3208 assert_eq!(slices[0].to_range(8), 0..3);
3209 let slices = shape.clone().into_slices([..-5]);
3210 assert_eq!(slices[0].to_range(8), 0..3);
3211
3212 // Unbounded end
3213 let slices = shape.clone().into_slices([5..]);
3214 assert_eq!(slices[0].to_range(8), 5..8);
3215 let slices = shape.clone().into_slices([-3..]);
3216 assert_eq!(slices[0].to_range(8), 5..8);
3217
3218 // Full range
3219 let slices = shape.into_slices([..]);
3220 assert_eq!(slices[0].to_range(8), 0..8);
3221 }
3222
3223 #[test]
3224 fn test_negative_slice_indices() {
3225 use crate::Slice;
3226
3227 // Test negative indices conversion
3228 let slice: Slice = (-3..-1).into();
3229 assert_eq!(slice.start, -3);
3230 assert_eq!(slice.end, Some(-1));
3231
3232 // Test to_range conversion with size 8
3233 let range = slice.to_range(8);
3234 assert_eq!(range, 5..7);
3235
3236 // Test with shape slice
3237 let shape = Shape::new([8, 4]);
3238 let result = shape.clone().into_slices([-3..-1]);
3239 assert_eq!(result[0].to_range(8), 5..7);
3240
3241 // Test more negative index cases
3242 let slice2: Slice = (-5..).into();
3243 assert_eq!(slice2.to_range(10), 5..10);
3244
3245 let slice3: Slice = (..-2).into();
3246 assert_eq!(slice3.to_range(10), 0..8);
3247
3248 // Test with s! macro - single dimension returns Slice directly
3249 let slice4 = s![-3..-1];
3250 assert_eq!(slice4.start, -3);
3251 assert_eq!(slice4.end, Some(-1));
3252 }
3253
3254 #[test]
3255 fn slice_range_multi_dim() {
3256 let shape = Shape::new([8, 4]);
3257
3258 // Multiple ways to provide ranges
3259 let slices = shape.clone().into_slices([0..5, 0..4]);
3260 assert_eq!(slices[0].to_range(8), 0..5);
3261 assert_eq!(slices[1].to_range(4), 0..4);
3262
3263 let slices = shape.clone().into_slices([0.., 0..]);
3264 assert_eq!(slices[0].to_range(8), 0..8);
3265 assert_eq!(slices[1].to_range(4), 0..4);
3266
3267 let slices = shape.clone().into_slices([0..=7, 0..=3]);
3268 assert_eq!(slices[0].to_range(8), 0..8);
3269 assert_eq!(slices[1].to_range(4), 0..4);
3270
3271 let slices = shape.clone().into_slices([0..5, 0..3]);
3272 assert_eq!(slices[0].to_range(8), 0..5);
3273 assert_eq!(slices[1].to_range(4), 0..3);
3274
3275 let slices = shape.into_slices([0.., 0..]);
3276 assert_eq!(slices[0].to_range(8), 0..8);
3277 assert_eq!(slices[1].to_range(4), 0..4);
3278 }
3279
3280 #[test]
3281 fn slice_range_multi_dim_index() {
3282 let shape = Shape::new([8, 4]);
3283
3284 // Indices (single integer) should also convert to correct range
3285 let slices = shape.clone().into_slices([0, 2]);
3286 assert_eq!(slices[0].to_range(8), 0..1);
3287 assert_eq!(slices[1].to_range(4), 2..3);
3288
3289 let slices = shape.into_slices([-1, -1]);
3290 assert_eq!(slices[0].to_range(8), 7..8);
3291 assert_eq!(slices[1].to_range(4), 3..4);
3292 }
3293
3294 #[test]
3295 fn slice_range_multi_dim_heterogeneous() {
3296 // Slice macro `s![]` can be used to provide different range types
3297 let shape = Shape::new([8, 4, 2]);
3298 let slice = s![0..5, .., -1];
3299 let slices = shape.into_slices(slice);
3300 assert_eq!(slices[0].to_range(8), 0..5);
3301 assert_eq!(slices[1].to_range(4), 0..4);
3302 assert_eq!(slices[2].to_range(2), 1..2);
3303
3304 let shape = Shape::new([8, 4, 2, 3]);
3305 let slice = s![..=4, 0..=3, .., -2..];
3306 let slices = shape.into_slices(slice);
3307 assert_eq!(slices[0].to_range(8), 0..5);
3308 assert_eq!(slices[1].to_range(4), 0..4);
3309 assert_eq!(slices[2].to_range(2), 0..2);
3310 assert_eq!(slices[3].to_range(3), 1..3);
3311
3312 let shape = Shape::new([3, 4]);
3313 let slice = s![1..-1, ..];
3314 let slices = shape.into_slices(slice);
3315 assert_eq!(slices[0].to_range(3), 1..2);
3316 assert_eq!(slices[1].to_range(4), 0..4);
3317 }
3318}