torch.NarrowShape
export type NarrowShape<
S extends Shape,
Dim extends number,
Length extends number,
Start extends number = 0, // Default start to 0 for backwards compat
> =
// Fall back to dynamic for non-literal shapes
number extends S['length']
? DynamicShape
: number extends Length
? DynamicShape
: number extends Start
? DynamicShape
: number extends Dim
? DynamicShape
: // Get the dimension size
GetDimSize<S, Dim> extends infer DimSize extends number
? // Check: start < dimSize
LessThan<Start, DimSize> extends true
? // Check: start + length <= dimSize
Add<Start, Length> extends infer End extends number
? LessOrEqual<End, DimSize> extends true
? ReplaceDim<S, Dim, Length> // Valid! Return narrowed shape
: narrow_error_length_exceeds_bounds<Start, Length, DimSize, Dim>
: DynamicShape // Add overflow, fall back to dynamic
: narrow_error_start_out_of_bounds<Start, DimSize, Dim>
: DynamicShape;Sextends ShapeDimextends numberLengthextends numberStartextends numberCompute output shape of narrow operation with compile-time bounds checking. narrow(dim, start, length) keeps the dimension but with reduced size.
Validates:
- start >= 0 (implicit, as start is a positive literal)
- start < dimSize
- start + length <= dimSize
Examples
// Valid narrow
type R1 = NarrowShape<readonly [2, 5, 4], 1, 0, 2>; // readonly [2, 2, 4]
// Error: start out of bounds
type R2 = NarrowShape<readonly [2, 5, 4], 1, 10, 2>;
// narrow_error_start_out_of_bounds<10, 5, 1>
// Error: length exceeds bounds
type R3 = NarrowShape<readonly [2, 5, 4], 1, 3, 5>;
// narrow_error_length_exceeds_bounds<3, 5, 5, 1>