How can I compute the tensor in Pytorch efficiently?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Efficient tensor computation in PyTorch means using GPU acceleration, avoiding unnecessary copies, leveraging vectorized operations over Python loops, and managing memory carefully. The biggest performance wins come from moving tensors to GPU with .to(device), replacing explicit loops with broadcasting and torch.einsum, using in-place operations where safe, and enabling mixed-precision training. Understanding these patterns is essential for training large models in reasonable time.
Move Tensors to GPU
GPU computation is 10-100x faster than CPU for large tensor operations due to massive parallelism.
Vectorized Operations Over Loops
Vectorized operations dispatch to optimized C++/CUDA kernels. Python loops add interpreter overhead per element.
Broadcasting
Broadcasting automatically expands tensors to compatible shapes without copying data:
torch.einsum for Complex Operations
einsum generates optimized BLAS/CUDA calls and avoids intermediate tensors.
In-Place Operations
In-place operations (trailing _) save memory by not allocating a new tensor. However, they can break autograd if the tensor is needed for gradient computation. Use them primarily in inference or for tensors not requiring gradients.
Mixed Precision Training
Mixed precision uses float16 for forward/backward passes and float32 for weight updates. This roughly doubles training speed on modern GPUs.
Efficient Data Loading
pin_memory=True + non_blocking=True enables asynchronous CPU-to-GPU transfers, overlapping data loading with computation.
Avoid Unnecessary Gradient Tracking
Efficient Matrix Operations
Memory Management
torch.compile (PyTorch 2.0+)
torch.compile fuses operations, optimizes memory access patterns, and generates optimized CUDA kernels automatically.
Common Pitfalls
- CPU-GPU data transfer in loops: Moving small tensors between CPU and GPU in a loop kills performance. Batch operations on GPU and transfer only results back to CPU.
- Using Python lists instead of tensors:
[tensor1, tensor2, ...]followed bytorch.stack()is slower than pre-allocating a tensor and filling it. Usetorch.zeros(n, ...)and index assignment. .item()in training loops:loss.item()synchronizes CPU and GPU. Call it every N steps for logging, not every step.- Forgetting
model.eval()during inference: Withouteval(), batch norm and dropout still run in training mode, giving wrong results and wasting computation. - Using
torch.tensor()inside a loop: Each call creates a new tensor with gradient tracking overhead. Pre-allocate outside the loop.
Summary
- Move tensors to GPU with
.to(device)for 10-100x speedup on large operations - Use vectorized operations and broadcasting instead of Python loops
- Use
torch.einsumfor readable, efficient multi-dimensional operations - Enable mixed precision (
autocast+GradScaler) for 2x training speed - Set
pin_memory=Trueandnum_workers > 0in DataLoader for faster data loading - Use
torch.no_grad()during inference andtorch.compile()(PyTorch 2.0+) for automatic optimization
Related reading
- How can I convert a trained Tensorflow model to Keras?
- How can I copy a variable in tensorflow
- How can I download and skip VGG weights that have no counterpart with my CNN in Keras?
- How can I enrich a Convolutional Neural Network with meta information?
- How can I concatenate pytorch tensors or lists in a distributed multi-node setup?
- How can I load a partial pretrained pytorch model?
- How can I convert TFRecords into numpy arrays?
- How can I deal with a randomization issue in Echo State Networks?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.