Skip to main content

burn_tensor/tensor/api/
base.rs

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