torch.RangeSpec
export type RangeSpec =
| readonly [number, number] // [start, end]
| readonly [number, number, number];Values
readonly [number, number]readonly [number, number, number]
Range specification for tensor slicing in the .at() method.
Specifies a slice of elements along a single dimension using start, end, and optional step.
Follows Python's slicing semantics but in tuple form instead of start:end:step.
Format:
[start, end]: Slice from start (inclusive) to end (exclusive) with step=1[start, end, step]: Slice with custom step size
Semantics:
- start: First index to include (0-based)
- end: First index to exclude (exclusive bound)
- step: Stride between elements (default 1)
- Negative indices allowed (count from end)
- Empty ranges allowed (returns 0-length slice)
Equivalent to Python:
[start, end]→x[start:end][start, end, step]→x[start:end:step]
Use Cases:
- Subarray extraction:
[0, 5]takes first 5 elements - Strided access:
[0, 10, 2]takes every other element - Negative indexing:
[-5, null]takes last 5 elements - Reversing:
[null, null, -1]reverses the dimension
Examples
const x = torch.arange(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// Two-element range [start, end]
x.at([2, 5]); // [2, 3, 4] - step defaults to 1
// Three-element range [start, end, step]
x.at([0, 10, 2]); // [0, 2, 4, 6, 8] - every other element
x.at([1, 9, 2]); // [1, 3, 5, 7] - start at 1, every other
// Negative indices (count from end)
x.at([-5, 10]); // [5, 6, 7, 8, 9] - last 5 elements
x.at([-3, null]); // [7, 8, 9] - from -3 to end
// Reversal and negative step
x.at([9, -1, -1]); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] - reversed
x.at([5, 0, -1]); // [5, 4, 3, 2, 1] - reversed portion
// Empty ranges
x.at([5, 2]); // [] - empty (start >= end with positive step)
// In multi-dimensional indexing
const matrix = torch.randn([10, 20]);
matrix.at([
[0, 5], // First dimension: rows 0-4
[5, 15, 2] // Second dimension: cols 5,7,9,11,13 (every other)
]);