| name | pytorch |
| description | Comprehensive reference documentation and skill for PyTorch - the GPU-accelerated tensor computation and deep learning framework. Covers tensor operations, automatic differentiation, neural network modules (nn), optimization, distributed training, CUDA support, automatic mixed precision (AMP), torch.compile/Dynamo, TorchScript, FX graph transformation, Inductor backend, ONNX export, quantization, profiling, data loading, probability distributions, FFT, linear algebra, sparse tensors, C++ API (libtorch), operator dispatch, custom operators, and deployment. Based on PyTorch source code analysis.
|
| version | 2.7 |
PyTorch - Tensor Computation & Deep Learning Framework
Overview
PyTorch is a GPU-accelerated tensor computation framework with a tape-based automatic differentiation system and a comprehensive deep learning library. It provides two high-level features:
- Tensor computation with strong GPU acceleration (via CUDA, XPU, MPS backends)
- Deep neural networks built on a tape-based autograd system
Supported Hardware: NVIDIA GPUs (CUDA), Intel GPUs (XPU), Apple Silicon (MPS), AMD GPUs (ROCm), Meta MTIA, CPU
Supported Platforms: Linux, macOS, Windows, Android, iOS
PyTorch Version: 2.7
Key Architecture Concepts
- Tensor: Multi-dimensional matrix containing elements of a single data type
- Autograd: Automatic differentiation engine that powers neural network training
- nn.Module: Base class for all neural network components
- Optimizer: Algorithms for updating model parameters (Adam, SGD, etc.)
- Dispatcher: Routes operator calls to backend-specific implementations
- Dynamo: Just-in-time compiler for PyTorch (
torch.compile)
- Inductor: Triton-based code generation backend for Dynamo
- FX: Python-to-Python program transformation toolkit
- TorchScript: Static typing and compilation for production deployment
- ATen: A Tensor Library - C++ core tensor operations
- c10: Core library providing foundational abstractions
Architecture Overview
┌──────────────────────────────────────────────────────┐
│ Python Frontend │
│ torch.nn │ torch.optim │ torch.autograd │ ... │
├──────────────┼──────────────┼─────────────────────────┤
│ torch._C (Pybind11 Bindings) │
├──────────────┼──────────────┼─────────────────────────┤
│ ATen (A Tensor Library) │
│ native ops │ CPU kernels │ CUDA kernels │ ... │
├──────────────┼──────────────┼─────────────────────────┤
│ c10 (Core Library) │
│ TensorImpl │ Device │ ScalarType │ Storage │
└──────────────────────────────────────────────────────┘
Quick Reference
Tensor Creation
import torch
t = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32, device='cuda')
z = torch.zeros(3, 4)
o = torch.ones(2, 3)
r = torch.randn(5, 5)
u = torch.rand(3, 3)
a = torch.arange(0, 10, 2)
l = torch.linspace(0, 1, 5)
e = torch.empty(2, 3)
f = torch.full((2, 3), 7.0)
i = torch.eye(3)
like = torch.zeros_like(t)
new_t = t.new_zeros(3, 4)
Training Loop
import torch
import torch.nn as nn
import torch.optim as optim
model = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10),
).cuda()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(num_epochs):
for inputs, targets in dataloader:
inputs, targets = inputs.cuda(), targets.cuda()
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
torch.compile
model = torch.compile(model)
output = model(input)
Automatic Mixed Precision
scaler = torch.amp.GradScaler('cuda')
with torch.amp.autocast('cuda'):
output = model(input)
loss = criterion(output, target)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
Distributed Training
import torch.distributed as dist
dist.init_process_group("nccl")
model = nn.parallel.DistributedDataParallel(model, device_ids=[local_rank])
Custom Autograd Function
class MyFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
return input.clamp(min=0)
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
return grad_output * (input > 0).float()
C++ API (LibTorch)
#include <torch/torch.h>
auto tensor = torch::rand({2, 3});
auto result = torch::matmul(tensor, tensor.transpose(0, 1));
Code Examples
Official examples from pytorch/examples (219 files), covering key deep learning patterns:
| Category | Description |
|---|
mnist/ | MNIST classification — basic training loop |
mnist_hogwild/ | Hogwild multi-process training |
mnist_rnn/ | RNN on MNIST |
mnist_forward_forward/ | Forward-Forward algorithm |
imagenet/ | ImageNet training with distributed data parallel |
dcgan/ | DCGAN generative adversarial network |
vae/ | Variational Autoencoder |
word_language_model/ | LSTM/Transformer language modeling |
time_sequence_prediction/ | Sequence prediction with RNN |
regression/ | Polynomial regression |
reinforcement_learning/ | DQN, policy gradient, actor-critic, REINFORCE |
distributed/ | DDP, FSDP, pipeline parallel, RPC, minGPT-ddp |
super_resolution/ | SRCNN super-resolution with AMP |
fast_neural_style/ | Neural style transfer |
language_translation/ | Seq2seq translation with attention |
siamese_network/ | Siamese network for similarity |
gat/ / gcn/ | Graph neural networks (GAT, GCN) |
fx/ | torch.fx graph manipulation examples |
cpp/ | LibTorch C++ API examples |
legacy/ | Legacy examples (AlephBet, SNLI, etc.) |
Reference Chapters
Core
- Overview and Architecture - Design philosophy, system architecture, code layout
- Tensor Fundamentals - Creation, indexing, slicing, reshaping, views
- Tensor Operations - Math, comparison, reduction, BLAS, spectral ops
- Automatic Differentiation - Autograd engine, Function, grad modes, forward-mode AD
- Tensor Types and Device Management - dtypes, devices, layouts, memory formats
Neural Network Modules (torch.nn)
- nn.Module System - Module, Parameter, hooks, serialization, state_dict
- Linear and Convolution Layers - Linear, Conv1d/2d/3d, ConvTranspose, Lazy variants
- Recurrent and Transformer Layers - RNN, LSTM, GRU, Transformer, MultiheadAttention
- Normalization, Pooling, and Activation - BatchNorm, LayerNorm, GroupNorm, MaxPool, ReLU, GELU, etc.
- Loss Functions - CrossEntropy, MSE, L1, NLL, BCE, KLDiv, CosineEmbedding, etc.
- nn.functional - Functional API for all nn operations
- nn.init and Utilities - Weight initialization, RNN utils, clip_grad_norm, data utilities
Optimization
- Optimizers - SGD, Adam, AdamW, RMSprop, Adagrad, LBFGS, etc.
- Learning Rate Schedulers - StepLR, CosineAnnealingLR, OneCycleLR, ReduceLROnPlateau, etc.
Distributed Training
- Distributed Overview - Architecture, backends (NCCL, Gloo, MPI), initialization
- DistributedDataParallel - DDP design, gradient sync, bucketing, comm hooks
- Collective Communications - all_reduce, all_gather, broadcast, reduce_scatter, etc.
- Pipeline Parallelism - PipelineParallel, GPipe, virtual stages
- FSDP - FullyShardedDataParallel, sharding strategies, mixed precision
- RPC Framework - Remote procedure calls, RRef, distributed autograd
GPU and Performance
- CUDA Support - CUDA tensors, memory management, pinned memory, device operations
- Automatic Mixed Precision - autocast, GradScaler, bfloat16, float16
- Memory Management - Memory allocation, caching allocator,OutOfMemoryError handling
- Streams and Events - CUDA streams, events, synchronization, graph capture
Compilation and Export
- torch.compile - Dynamo, graph breaks, backends, config
- TorchScript - Scripting, tracing, optimization, deployment
- FX Graph - Graph representation, Node, symbolic trace, transformation passes
- Inductor Backend - Triton codegen, CPU backend, memory planning, scheduling
- Model Export - torch.export, dynamo export, ExportedProgram
- ONNX Export - ONNX graph conversion, opset versions, custom ops
Data Pipeline
- DataLoader - Batching, shuffling, multiprocessing, prefetching, worker init
- Datasets - Dataset, IterableDataset, TensorDataset, ConcatDataset, random_split
- Transforms - torchvision transforms, custom transforms, functional API
Mathematical Libraries
- Probability Distributions - Normal, Uniform, Bernoulli, Categorical, etc., KL divergence
- FFT Operations - FFT, IFFT, RFFT, IRFFT, FFT2, FFTN, hann/hamming windows
- Linear Algebra - Matrix decompositions (SVD, LU, QR, cholesky), solve, eig, norm
- Sparse Tensors - COO, CSR, CSC formats, sparse operations, semi-structured sparsity
- Special Math Functions - Bessel, gamma, erf, digamma, softmax, log_softmax
- Masked and Nested Tensors - Masked operations, nested/jagged tensors
C++ Backend
- c10 Core Library - Device, ScalarType, TensorImpl, Storage, ArrayRef, DispatchKey
- ATen Operations - Native functions, operator schema, backend implementations
- LibTorch C++ API - C++ frontend, nn::Module, optim::Optimizer, data loaders
- Operator Dispatch - Dispatch keys, dispatch table, fallthrough, functionalization
- Custom Operators - TORCH_LIBRARY, torch.library, custom CUDA kernels
- Code Generation (torchgen) - Operator generation, native_functions.yaml, build system
- Autograd Engine (C++) - Eval queue, graph execution, compiled autograd
Deployment and Optimization
- Quantization - Post-training quantization, quantization-aware training, observer, fake quant
- Advanced Quantization (torch.ao) - torch.ao.ns, GPTQ, quantized operators, custom quant
- Profiling - torch.profiler, TensorBoard, Kineto, memory profiling, flame graphs
- Package and Hub - torch.package, torch.hub, model packaging, dependency management
- Mobile Deployment - Model optimization for mobile, quantization, selective build
- Inference Optimization - Inference mode, graph optimization, kernel fusion, torch._C
Advanced Topics
- functorch (JAX-like transforms) - vmap, grad, jacfwd, jacrev, hessian, functional calls
- Storage and Serialization - Storage types, save/load, safetensors, format details
- Multiprocessing - torch.multiprocessing, shared memory, CUDA IPC
- Backend System - Backend modules (mkl, mkldnn, cudnn, etc.), flags, context managers
- Control Flow and Gradient - torch.cond, torch.while_loop, checkpoint, gradient checkpointing
- Type System and dtypes - All dtypes, type promotion, casting rules, SymInt/SymFloat
- Device Management - Multi-device, device context, XPU, MPS, MTIA backends
- Advanced Features - Named tensors, compiler hints, tracing, debugging utilities