torch.Tensor.Tensor.contiguous
Returns a contiguous tensor (guarantees memory layout is row-major without strides).
In torch.js, tensors are assumed to be contiguous by default, so this typically returns self. Useful for compatibility with code expecting contiguous tensors or as a safety check before operations that require contiguous memory layout.
Common use cases:
- Ensuring tensor is contiguous before passing to external functions
- PyTorch compatibility
- Performance-critical operations
- Custom indexing operations
- Always returns contiguous: torch.js assumes all tensors are contiguous
- No-op by default: Usually returns self unless layout was modified
- GPU/CPU agnostic: Works on both devices
Returns
Tensor<S, D, Dev>– A contiguous tensor (self if already contiguous)Examples
const x = torch.randn(3, 4, 5);
const contiguous = x.contiguous(); // Returns self (already contiguous)
// After permutation, ensure contiguous for external function
const permuted = x.permute([2, 0, 1]);
const safe = permuted.contiguous(); // Safe to pass to C++ functions
// Custom indexing operations
const data = permuted.contiguous(); // Ensure layout before manual indexingSee Also
- PyTorch tensor.contiguous()
- permute - Can affect memory layout
- transpose - Can affect memory layout
- is_contiguous - Check if tensor is contiguous