torch.contiguous
function contiguous<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>): Tensor<S, D, Dev>Ensures tensor is contiguous in memory.
Returns a contiguous (C-order) tensor. In torch.js, tensors are always contiguous, so this effectively returns a clone for consistency with PyTorch. Useful for:
- API compatibility: matching PyTorch code exactly
- Memory layout guarantee: ensuring C-contiguous for GPU operations
- Reshape safety: before operations that require contiguity
- Performance: some operations are faster with guaranteed contiguity
- Torch.js note: torch.js always keeps tensors contiguous, so this is mostly for API compatibility
- No-op usually: In most cases, returns input or minimal copy
- Safety: Ensures operations expecting contiguity will work
Parameters
inputTensor<S, D, Dev>- The input tensor
Returns
Tensor<S, D, Dev>– A contiguous tensor (or input if already contiguous)Examples
// Ensure contiguity before operation
const x = torch.randn(3, 4).t(); // Transposed (still contiguous in torch.js)
const contiguous = torch.contiguous(x);
// After non-standard indexing
const indexed = torch.randn(10)[torch.tensor([0, 2, 4, 6, 8])];
const result = torch.contiguous(indexed); // Guarantee contiguitySee Also
- PyTorch torch.contiguous()
- reshape - Reshape operation
- clone - Create independent copy
- view - Create view with different shape