zyx 0.17.0

Zyx machine learning library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
// Copyright (C) 2025 zk4x
// SPDX-License-Identifier: LGPL-3.0-only WITH Classpath-exception-2.0

use crate::{
    RT, Tensor, ZyxError,
    dtype::DType,
    shape::{Dim, into_axis},
    tensor::Axis,
};
use std::ops::{Mul, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo};

/// Panics on indexing, with a helpful message directing to `.slice(...)`.
impl<I> std::ops::Index<I> for Tensor {
    type Output = Tensor;

    fn index(&self, _index: I) -> &Self::Output {
        panic!(
            "Tensor does not support indexing with `[]` because rust only allows indexing on referece types. \
             Use `.slice(...)` instead, which supports ranges, integers, and tuples. \
             Example: tensor.slice((0..3, -1))"
        );
    }
}

impl Tensor {
    /// Slice the tensor using integers, ranges, or tuples of each.
    /// Negative indices wrap to the end; omitted dimensions are preserved.
    /// Returns a new view tensor of the selected region.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zyx::{Tensor, DType};
    /// let x = Tensor::randn([3, 4, 5], DType::F32)?;
    /// let a = x.slice(0)?;
    /// let b = x.slice((.., .., -1))?;
    /// # Ok::<(), zyx::ZyxError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a shape error if an index is out of bounds, a range is empty,
    /// or the index count exceeds the tensor rank.
    pub fn slice(&self, index: impl IntoIndex) -> Result<Tensor, ZyxError> {
        let shape = self.resolve_shape();
        let rank = shape.len();

        let mut squeeze_axes: Vec<Axis> = Vec::new();
        let index = index.into_index();
        let padding_len = index.len();

        if rank < padding_len {
            return Err(ZyxError::shape_error(format!("Slice with {padding_len} indices, but tensor has rank {rank}").into()));
        }

        //let padding = std::iter::repeat_n((0, 0), rank - padding_len);
        //print!("shape={shape:?}");

        let padding = index
            .zip(shape)
            .enumerate()
            .map(|(axis, (dim_index, dim_size))| {
                let dim_size = dim_size as i64;
                match dim_index {
                    DimIndex::Range { start, end } => {
                        let s = if start < 0 { (start + dim_size).max(0) } else { start };
                        let s = s.min(dim_size);
                        let e = if end > dim_size {
                            dim_size
                        } else if end < 0 {
                            (end + dim_size).max(0)
                        } else {
                            end
                        };
                        let e = e.min(dim_size).max(0);
                        if e < s {
                            return Err(ZyxError::shape_error(
                                format!("Slice range end {e} is less than start {s} for dimension {axis}").into(),
                            ));
                        }
                        Ok((-s, -(dim_size - e)))
                    }
                    DimIndex::Index(i) => {
                        squeeze_axes.push(axis as i32);
                        let i = if i < 0 { i + dim_size } else { i };
                        if i < 0 || i >= dim_size {
                            return Err(ZyxError::shape_error(
                                format!("Index {i} out of bounds for dimension {axis} of size {dim_size}").into(),
                            ));
                        }
                        Ok((-i, -(dim_size - i - 1)))
                    }
                    DimIndex::RangeFull => Ok((0i64, 0i64)),
                    DimIndex::RangeFrom { start } => {
                        let s = if start < 0 { (start + dim_size).max(0) } else { start };
                        let s = s.min(dim_size);
                        Ok((-s, 0i64))
                    }
                    DimIndex::RangeTo { end } => {
                        let e = if end > dim_size {
                            dim_size
                        } else if end < 0 {
                            (end + dim_size).max(0)
                        } else {
                            end
                        };
                        let e = e.min(dim_size).max(0);
                        Ok((0i64, -(dim_size - e)))
                    }
                }
            })
            .collect::<Result<Vec<_>, _>>()?;

        //let padding_vec: Vec<(i32, i32)> = padding.into_iter().collect();
        //println!("padding={padding_vec:?}");

        let mut result = self.pad_zeros(padding)?;
        result = result.squeeze(squeeze_axes);

        Ok(result)
    }

    /// Same as [`Tensor::slice`], but the indices are applied from the last
    /// dimensions instead of the first.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zyx::{Tensor, DType};
    /// let x = Tensor::randn([3, 4, 5], DType::F32)?;
    /// let y = x.rslice((.., .., -1))?;
    /// # Ok::<(), zyx::ZyxError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a shape error if the index is invalid for the tensor shape.
    #[allow(clippy::missing_panics_doc)]
    pub fn rslice(&self, index: impl IntoIndex) -> Result<Tensor, ZyxError> {
        let shape = self.resolve_shape();
        let rank = shape.len();
        //print!("shape={shape:?}");

        let mut squeeze_axes: Vec<Axis> = Vec::new();
        let index = index.into_index();
        let padding_len = index.len();

        if padding_len > rank {
            return Err(ZyxError::shape_error(format!("Index length {padding_len} > rank {rank}").into()));
        }

        let padding = index
            .zip(shape.into_iter().rev())
            .enumerate()
            .map(|(axis, (dim_index, dim_size))| {
                let dim_size = dim_size as i64;
                match dim_index {
                    DimIndex::Range { start, end } => {
                        let s = if start < 0 { (start + dim_size).max(0) } else { start };
                        let s = s.min(dim_size);
                        let e = if end > dim_size {
                            dim_size
                        } else if end < 0 {
                            (end + dim_size).max(0)
                        } else {
                            end
                        };
                        let e = e.min(dim_size).max(0);
                        if e < s {
                            return Err(ZyxError::shape_error(
                                format!("Slice range end {e} is less than start {s} for dimension {axis}").into(),
                            ));
                        }
                        Ok((-s, -(dim_size - e)))
                    }
                    DimIndex::Index(i) => {
                        squeeze_axes.push(axis as i32);
                        let i = if i < 0 { i + dim_size } else { i };
                        if i < 0 || i >= dim_size {
                            return Err(ZyxError::shape_error(
                                format!("Index {i} out of bounds for dimension {axis} of size {dim_size}").into(),
                            ));
                        }
                        Ok((-i, -(dim_size - i - 1)))
                    }
                    DimIndex::RangeFull => Ok((0i64, 0i64)),
                    DimIndex::RangeFrom { start } => {
                        let s = if start < 0 { (start + dim_size).max(0) } else { start };
                        let s = s.min(dim_size);
                        Ok((-s, 0i64))
                    }
                    DimIndex::RangeTo { end } => {
                        let e = if end > dim_size {
                            dim_size
                        } else if end < 0 {
                            (end + dim_size).max(0)
                        } else {
                            end
                        };
                        let e = e.min(dim_size).max(0);
                        Ok((0i64, -(dim_size - e)))
                    }
                }
            })
            .collect::<Result<Vec<_>, _>>()?;

        let padding = padding.into_iter().chain(std::iter::repeat_n((0i64, 0i64), rank - padding_len));

        let mut padding_vec: Vec<(i64, i64)> = padding.into_iter().collect();
        padding_vec.reverse();
        //println!("padding={padding_vec:?}");

        let mut result = self.pad_zeros(padding_vec)?;
        result = result.squeeze(squeeze_axes);

        Ok(result)
    }

    /// Returns a 1-D tensor of the diagonal elements of the last two
    /// dimensions (e.g. `[i, i]` of a 2-D `[n, n]` matrix).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zyx::Tensor;
    /// let arr = Tensor::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape([3, 3])?;
    /// assert_eq!(arr.diagonal(), [1, 5, 9]);
    /// # Ok::<(), zyx::ZyxError>(())
    /// ```
    #[allow(clippy::missing_panics_doc)]
    #[must_use]
    pub fn diagonal(&self) -> Tensor {
        let n = *self.resolve_shape().last().expect("Shape in invalid state. Internal bug.");
        self.flatten(..)
            .unwrap()
            .rpad_zeros([(0i64, i64::try_from(n).unwrap())])
            .unwrap()
            .reshape([n, n + 1])
            .unwrap()
            .slice((.., 0))
            .unwrap()
            .flatten(..)
            .unwrap()
    }

    /// Extract a contiguous window along `axis`: from index `start` for
    /// `length` elements, padding the omitted region with zeros. `start` and
    /// `length` must be I64 (IDX_T) tensors or integers.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zyx::Tensor;
    /// let x = Tensor::from([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
    /// assert_eq!(x.narrow(0, 0i64, 2i64)?, [[1, 2, 3], [4, 5, 6]]);
    /// assert_eq!(x.narrow(1, 1i64, 2i64)?, [[2, 3], [5, 6], [8, 9]]);
    /// # Ok::<(), zyx::ZyxError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a shape error if `start`/`length` are not I64, if `start + length`
    /// exceeds the dim size, or if the bounds cannot be resolved.
    #[allow(clippy::missing_panics_doc)]
    pub fn narrow(&self, axis: Axis, start: impl Into<Tensor>, length: impl Into<Tensor>) -> Result<Tensor, ZyxError> {
        let rank = self.rank() as usize;
        let axis = into_axis(axis, rank)?;
        let start = start.into();
        let length = length.into();
        // Shape inputs must be IDX_T (I64). Other dtypes would get silently
        // cast inside the kernel IR, hiding the caller mistake until it
        // surfaces far away from the cause (e.g. in gws resolution).
        for (what, tid_dtype) in [("start", start.dtype()), ("length", length.dtype())] {
            if tid_dtype != DType::I64 {
                return Err(ZyxError::shape_error(
                    format!("narrow: {what} must be I64 (IDX_T), got {tid_dtype:?} — cast the tensor to I64 at creation").into(),
                ));
            }
        }
        let mut rt = RT.lock();
        // Bounds check when every value resolves now (constants and bound
        // variables). Unresolvable symbolics skip this and defer to realize
        // time, where values bind and ranges validate before launch.
        let dim = rt.shape(self.id).get(axis as usize).copied().and_then(|d| rt.resolve_symbolic(d));
        let st = rt.resolve_symbolic(start.id);
        let ln = rt.resolve_symbolic(length.id);
        if let (Some(dim), Some(st), Some(ln)) = (dim, st, ln) {
            match (dim.as_dim(), st.as_dim(), ln.as_dim()) {
                (Some(dim), Some(st), Some(ln)) => {
                    if st.checked_add(ln).is_none_or(|end| end > dim) {
                        return Err(ZyxError::shape_error(
                            format!("narrow: out of bounds: start {st} + length {ln} exceeds dim {dim} on axis {axis}").into(),
                        ));
                    }
                }
                _ => {
                    return Err(ZyxError::shape_error(
                        format!("narrow: negative bound: dim {dim:?}, start {st:?}, length {ln:?} on axis {axis}").into(),
                    ));
                }
            }
        }
        let id = rt.narrow(self.id, axis, start.id, length.id);
        Ok(Tensor { id })
    }

    /// Gather elements along `axis` using integer `indices`. Negative indices
    /// wrap to the end; out-of-bounds indices read 0. The result has the
    /// shape of `indices`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zyx::Tensor;
    /// let x = Tensor::from(vec![1.0f32; 4]);
    /// let y = x.gather(0, Tensor::from(vec![2i32, 0, 3, 1]))?;
    /// # Ok::<(), zyx::ZyxError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a shape error if the ranks differ or a non-gather dim of `self`
    /// is smaller than the corresponding dim of `indices`.
    pub fn gather(&self, axis: Axis, indices: impl Into<Tensor>) -> Result<Tensor, ZyxError> {
        let indices = indices.into();

        let shape = self.resolve_shape();
        let index_shape = indices.resolve_shape();
        let dim = into_axis(axis, shape.len())?;

        if shape.len() != index_shape.len() {
            return Err(ZyxError::shape_error(
                format!("self.rank({}) != indices.rank({})", shape.len(), index_shape.len()).into(),
            ));
        }

        for (d, (&s, &i)) in shape.iter().zip(index_shape.iter()).enumerate() {
            if d != dim && s < i {
                return Err(ZyxError::shape_error(
                    format!("Shape mismatch at dimension {d}: self.shape[{d}] = {s} < indices.shape[{d}] = {i}").into(),
                ));
            }
        }

        let dim_size = shape[dim];

        let is_negative = indices.cmplt(0)?.cast(indices.dtype());
        let indices = indices + is_negative * dim_size;

        // Prepare one-hot along dim
        let one_hot = indices.unsqueeze(-1)?.one_hot_along_dim(dim_size, -1)?;

        // Prepare negative padding for shrink
        let mut padding = Vec::new();
        for d in (0..index_shape.len()).rev() {
            if d == dim {
                padding.push((0i64, 0i64));
            } else {
                padding.push((0i64, -(shape[d] as i64 - index_shape[d] as i64)));
            }
        }

        let x = self.rpad_zeros(padding)?.unsqueeze(-1)?.transpose(-1, dim as i32)?;
        let result = one_hot.mul(&x).sum_dtype([-1], self.dtype())?;

        Ok(result)
    }

    /// Add values from `src` into a copy of `self` along `axis` per `indices`;
    /// indices mapping to the same output position are summed. Negative
    /// indices wrap to the end.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zyx::{Tensor, DType};
    /// let x = Tensor::zeros([4], DType::F32);
    /// let y = x.scatter(0, Tensor::from(vec![1i32, 1]), Tensor::from(vec![5.0f32, 2.0]))?;
    /// # Ok::<(), zyx::ZyxError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a shape error if the `indices`/`src` shapes mismatch, or a
    /// non-scatter dim of `self` is smaller than the corresponding dim.
    pub fn scatter(&self, axis: Axis, indices: impl Into<Tensor>, src: impl Into<Tensor>) -> Result<Tensor, ZyxError> {
        let indices = indices.into();
        let src = src.into();
        let shape = self.resolve_shape();
        let index_shape = indices.resolve_shape();
        let dim = into_axis(axis, shape.len())?;
        let dim_size = shape[dim];

        if shape.len() != index_shape.len() {
            return Err(ZyxError::shape_error(
                format!("self.rank({}) != indices.rank({})", shape.len(), index_shape.len()).into(),
            ));
        }

        if index_shape != src.resolve_shape() {
            return Err(ZyxError::shape_error(
                format!("indices shape {:?} != src shape {:?}", index_shape, src.resolve_shape()).into(),
            ));
        }

        for (d, (&s, &i)) in shape.iter().zip(index_shape.iter()).enumerate() {
            if d != dim && s < i {
                return Err(ZyxError::shape_error(
                    format!("Shape mismatch at dimension {d}: self.shape[{d}] = {s} < indices.shape[{d}] = {i}").into(),
                ));
            }
        }

        let is_negative = indices.cmplt(0)?.cast(indices.dtype());
        let indices = indices + is_negative.mul(dim_size as i32);

        let one_hot = indices.unsqueeze(-1)?.one_hot_along_dim(dim_size, -1)?;

        let contrib = one_hot.mul(&src.unsqueeze(-1)?);

        let contrib = contrib.transpose(-1, dim as i32)?;

        let rank = self.rank() as usize;
        let mut padding = Vec::new();
        for d in (0..=rank).rev() {
            if d == dim || d == rank {
                padding.push((0i64, 0i64));
            } else {
                padding.push((0i64, (shape[d] - index_shape[d]) as i64));
            }
        }
        let contrib = contrib.rpad_zeros(padding)?;

        let result = contrib.sum_dtype([-1], self.dtype())? + self;

        Ok(result)
    }

    /// Select rows along `dim` at the rows named by `index` (a 1-D integer
    /// tensor). The result has `self`'s shape with `dim` replaced by the number
    /// of indices.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zyx::Tensor;
    /// let x = Tensor::from(vec![1i32; 6]);
    /// let y = x.index_select(0, Tensor::from(vec![1i32, 3, 5]))?;
    /// # Ok::<(), zyx::ZyxError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a shape error if `dim` is out of range or `index` is not 1-D.
    pub fn index_select(&self, dim: Axis, index: impl Into<Tensor>) -> Result<Tensor, ZyxError> {
        let index = index.into();
        let mut shape = self.resolve_shape();
        let rank = shape.len();
        let dim = into_axis(dim, rank)?;

        shape[dim] = index.resolve_shape()[0];
        let mut view_shape: Vec<Dim> = vec![1; rank];
        view_shape[dim] = index.resolve_shape()[0];
        let index_expanded = index.reshape(view_shape)?.expand(shape)?;

        self.gather(dim as Axis, index_expanded)
    }
}

/// Dim index
#[derive(Clone, Debug)]
pub enum DimIndex {
    /// Single index
    Index(i64),
    /// Range
    Range { start: i64, end: i64 },
    /// Range from
    RangeFrom { start: i64 },
    /// Range to
    RangeTo { end: i64 },
    /// Range full
    RangeFull,
}

/// Into index
pub trait IntoIndex {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator;
}

impl From<i64> for DimIndex {
    fn from(val: i64) -> DimIndex {
        DimIndex::Index(val)
    }
}

impl From<i32> for DimIndex {
    fn from(val: i32) -> DimIndex {
        DimIndex::Index(i64::from(val))
    }
}

impl From<usize> for DimIndex {
    fn from(val: usize) -> DimIndex {
        DimIndex::Index(val as i64)
    }
}

impl From<u64> for DimIndex {
    fn from(val: u64) -> DimIndex {
        DimIndex::Index(val as i64)
    }
}

impl From<Range<i64>> for DimIndex {
    fn from(val: Range<i64>) -> DimIndex {
        DimIndex::Range { start: val.start, end: val.end }
    }
}

impl From<Range<i32>> for DimIndex {
    fn from(val: Range<i32>) -> DimIndex {
        DimIndex::Range { start: i64::from(val.start), end: i64::from(val.end) }
    }
}

impl From<Range<usize>> for DimIndex {
    fn from(val: Range<usize>) -> DimIndex {
        DimIndex::Range { start: val.start as i64, end: val.end as i64 }
    }
}

impl From<Range<u64>> for DimIndex {
    fn from(val: Range<u64>) -> DimIndex {
        DimIndex::Range { start: val.start as i64, end: val.end as i64 }
    }
}

impl From<RangeInclusive<i64>> for DimIndex {
    fn from(val: RangeInclusive<i64>) -> DimIndex {
        DimIndex::Range { start: *val.start(), end: val.end() + 1 }
    }
}

impl From<RangeInclusive<i32>> for DimIndex {
    fn from(val: RangeInclusive<i32>) -> DimIndex {
        DimIndex::Range { start: i64::from(*val.start()), end: i64::from(*val.end()) + 1 }
    }
}

impl From<RangeInclusive<usize>> for DimIndex {
    fn from(val: RangeInclusive<usize>) -> DimIndex {
        DimIndex::Range { start: *val.start() as i64, end: *val.end() as i64 + 1 }
    }
}

impl From<RangeInclusive<u64>> for DimIndex {
    fn from(val: RangeInclusive<u64>) -> DimIndex {
        DimIndex::Range { start: *val.start() as i64, end: *val.end() as i64 + 1 }
    }
}

impl From<RangeFrom<i64>> for DimIndex {
    fn from(val: RangeFrom<i64>) -> DimIndex {
        DimIndex::RangeFrom { start: val.start }
    }
}

impl From<RangeFrom<i32>> for DimIndex {
    fn from(val: RangeFrom<i32>) -> DimIndex {
        DimIndex::RangeFrom { start: i64::from(val.start) }
    }
}

impl From<RangeFrom<usize>> for DimIndex {
    fn from(val: RangeFrom<usize>) -> DimIndex {
        DimIndex::RangeFrom { start: val.start as i64 }
    }
}

impl From<RangeFrom<u64>> for DimIndex {
    fn from(val: RangeFrom<u64>) -> DimIndex {
        DimIndex::RangeFrom { start: val.start as i64 }
    }
}

impl From<RangeTo<i64>> for DimIndex {
    fn from(val: RangeTo<i64>) -> DimIndex {
        DimIndex::RangeTo { end: val.end }
    }
}

impl From<RangeTo<i32>> for DimIndex {
    fn from(val: RangeTo<i32>) -> DimIndex {
        DimIndex::RangeTo { end: i64::from(val.end) }
    }
}

impl From<RangeTo<usize>> for DimIndex {
    fn from(val: RangeTo<usize>) -> DimIndex {
        DimIndex::RangeTo { end: val.end as i64 }
    }
}

impl From<RangeTo<u64>> for DimIndex {
    fn from(val: RangeTo<u64>) -> DimIndex {
        DimIndex::RangeTo { end: val.end as i64 }
    }
}

impl From<Range<Tensor>> for DimIndex {
    fn from(val: Range<Tensor>) -> DimIndex {
        DimIndex::Range { start: val.start.item::<i64>(), end: val.end.item::<i64>() }
    }
}

impl From<RangeInclusive<Tensor>> for DimIndex {
    fn from(val: RangeInclusive<Tensor>) -> DimIndex {
        DimIndex::Range { start: val.start().item::<i64>(), end: val.end().item::<i64>() + 1 }
    }
}

impl From<RangeFrom<Tensor>> for DimIndex {
    fn from(val: RangeFrom<Tensor>) -> DimIndex {
        DimIndex::RangeFrom { start: val.start.item::<i64>() }
    }
}

impl From<RangeTo<Tensor>> for DimIndex {
    fn from(val: RangeTo<Tensor>) -> DimIndex {
        DimIndex::RangeTo { end: val.end.item::<i64>() }
    }
}

impl From<RangeFull> for DimIndex {
    fn from(_val: RangeFull) -> DimIndex {
        DimIndex::RangeFull
    }
}

impl<I: Into<DimIndex>> IntoIndex for I {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        std::iter::once(self.into())
    }
}

impl<I: Into<DimIndex>, const N: usize> IntoIndex for [I; N] {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        self.into_iter().map(Into::into)
    }
}

impl<I: Into<DimIndex> + Clone> IntoIndex for &[I] {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        self.iter().map(|e| e.clone().into())
    }
}

impl<I: Into<DimIndex>> IntoIndex for Vec<I> {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        self.into_iter().map(Into::into)
    }
}

impl<I0: Into<DimIndex>, I1: Into<DimIndex>> IntoIndex for (I0, I1) {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        [self.0.into(), self.1.into()].into_iter()
    }
}

impl<I0: Into<DimIndex>, I1: Into<DimIndex>, I2: Into<DimIndex>> IntoIndex for (I0, I1, I2) {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        [self.0.into(), self.1.into(), self.2.into()].into_iter()
    }
}

impl<I0: Into<DimIndex>, I1: Into<DimIndex>, I2: Into<DimIndex>, I3: Into<DimIndex>> IntoIndex for (I0, I1, I2, I3) {
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        [self.0.into(), self.1.into(), self.2.into(), self.3.into()].into_iter()
    }
}

impl<I0: Into<DimIndex>, I1: Into<DimIndex>, I2: Into<DimIndex>, I3: Into<DimIndex>, I4: Into<DimIndex>> IntoIndex
    for (I0, I1, I2, I3, I4)
{
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        [self.0.into(), self.1.into(), self.2.into(), self.3.into(), self.4.into()].into_iter()
    }
}

impl<I0: Into<DimIndex>, I1: Into<DimIndex>, I2: Into<DimIndex>, I3: Into<DimIndex>, I4: Into<DimIndex>, I5: Into<DimIndex>>
    IntoIndex for (I0, I1, I2, I3, I4, I5)
{
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        [
            self.0.into(),
            self.1.into(),
            self.2.into(),
            self.3.into(),
            self.4.into(),
            self.5.into(),
        ]
        .into_iter()
    }
}

impl<
    I0: Into<DimIndex>,
    I1: Into<DimIndex>,
    I2: Into<DimIndex>,
    I3: Into<DimIndex>,
    I4: Into<DimIndex>,
    I5: Into<DimIndex>,
    I6: Into<DimIndex>,
> IntoIndex for (I0, I1, I2, I3, I4, I5, I6)
{
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        [
            self.0.into(),
            self.1.into(),
            self.2.into(),
            self.3.into(),
            self.4.into(),
            self.5.into(),
            self.6.into(),
        ]
        .into_iter()
    }
}

impl<
    I0: Into<DimIndex>,
    I1: Into<DimIndex>,
    I2: Into<DimIndex>,
    I3: Into<DimIndex>,
    I4: Into<DimIndex>,
    I5: Into<DimIndex>,
    I6: Into<DimIndex>,
    I7: Into<DimIndex>,
> IntoIndex for (I0, I1, I2, I3, I4, I5, I6, I7)
{
    fn into_index(self) -> impl ExactSizeIterator<Item = DimIndex> + DoubleEndedIterator {
        [
            self.0.into(),
            self.1.into(),
            self.2.into(),
            self.3.into(),
            self.4.into(),
            self.5.into(),
            self.6.into(),
            self.7.into(),
        ]
        .into_iter()
    }
}