Learn PyTorch

Pythonic deep learning with dynamic graphs, autograd and GPU tensors

35 lessons · 7 hours · 4 levels · covers PyTorch 2.9

PyTorch is the most widely used deep learning framework in research and increasingly in production. It gives you GPU-accelerated tensors, automatic differentiation over ordinary Python code, and building blocks for neural networks, data loading and distributed training. Learning it lets you read and write most modern ML code, from small classifiers to large transformers.

Before you start

PyTorch builds on these; the tree links to the exact lessons you need.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics12 lessons · 2 hours in total
2. PracticalUse it productively at work, with the usual idioms22 lessons · 4 hours in total
3. AdvancedThe less common features, performance and trade-offs29 lessons · 5 hours in total
4. ExpertInternals and the edge cases experts know35 lessons · 7 hours in total

The PyTorch tree

PyTorchTensors: the core data typeTensors: the coredata typeCreating tensorsCreating tensorsDtypes and devicesDtypes and devicesIndexing and reshapingIndexing andreshapingTensor math and broadcastingTensor math andbroadcastingNumPy interopNumPy interopAutograd: automatic gradientsAutograd: automaticgradientsnn.Module: defining modelsnn.Module: definingmodelsCommon layers and activationsCommon layers andactivationsLoss functionsLoss functionsOptimizersOptimizersThe training loopThe training loopDataset and DataLoaderDataset andDataLoaderTraining on a GPUTraining on a GPUtrain/eval modes and no_gradtrain/eval modes andno_gradSaving and loading checkpointsSaving and loadingcheckpointsConvolutional networksConvolutionalnetworksEmbeddings and recurrent layersEmbeddings andrecurrent layersLearning-rate schedulesLearning-rateschedulesGradient clipping and accumulationGradient clipping andaccumulationTransfer learning and fine-tuningTransfer learning andfine-tuningReproducibility and seedingReproducibility andseedingThe ndarrayThe ndarrayListsListsShape and reshapeShape and reshapeVectorized arithmeticVectorized arithmeticClasses and instancesClasses andinstancesfor and while loopsfor and while loopsIterators and generatorsIterators andgeneratorsDictionariesDictionariesFunctions as objects, lambdas and closuresFunctions as objects,lambdas and closur…
Essentials and Practical shown (22 of 35 lessons); the full list is below. Click a lesson to read it.

All 35 lessons, in order

Tensors

  1. Tensors: the core data type · Essentials · 8 min

    A tensor is an n-dimensional array with a dtype and a device, much like a NumPy array that can also live on a GPU.

  2. Creating tensors · Essentials · 7 min

    Build tensors with zeros, ones, arange, linspace, full, eye and the random factories, and seed them for repeatability.

  3. Dtypes and devices · Essentials · 9 min

    Choose numeric precision with dtype, move tensors between CPU and GPU with .to(), and know the type-promotion rules.

  4. Indexing and reshaping · Essentials · 10 min

    Slice, mask, reshape, permute, squeeze and combine tensors to get data into the shape a layer expects.

  5. Tensor math and broadcasting · Essentials · 10 min

    Element-wise ops, matrix multiplication with @, reductions along a dim, broadcasting and in-place ops with a trailing underscore.

  6. NumPy interop · Essentials · 6 min

    Convert between tensors and NumPy arrays, knowing when memory is shared and when it is copied.

  7. Storage, strides and views · Expert · 14 min

    How a tensor maps to memory: storage, offset and strides, why views are free, when contiguous() copies, and channels_last.

Autograd

  1. Autograd: automatic gradients · Essentials · 12 min

    Mark tensors with requires_grad, call backward() on a scalar loss, and read gradients from .grad.

  2. train/eval modes and no_grad · Practical · 9 min

    Know what model.eval() changes, when to use torch.no_grad or torch.inference_mode, and what detach() does.

  3. Custom autograd Functions · Advanced · 14 min

    Define your own forward and backward with torch.autograd.Function, save tensors on ctx, and verify with gradcheck.

  4. How autograd works · Expert · 16 min

    The graph of grad_fn nodes, leaf tensors, saved tensors and version counters, and higher-order gradients with create_graph.

Building models

  1. nn.Module: defining models · Essentials · 12 min

    Subclass nn.Module, create layers in __init__, describe the computation in forward, and call the model like a function.

  2. Common layers and activations · Essentials · 12 min

    Linear, Conv2d, pooling, Embedding, normalization, Dropout and activations, and how their input and output shapes relate.

  3. Convolutional networks · Practical · 14 min

    Build an image classifier from conv, activation and pooling blocks, compute feature-map sizes, and use torchvision.

  4. Embeddings and recurrent layers · Practical · 12 min

    Turn token ids into vectors, pad batches of sequences, and run LSTMs with batch_first and packed sequences.

  5. Transfer learning and fine-tuning · Practical · 12 min

    Start from pretrained torchvision weights, freeze the backbone, replace the head, then optionally fine-tune with a small learning rate.

  6. Forward and backward hooks · Advanced · 10 min

    Attach functions to modules and tensors to inspect or modify activations and gradients without changing model code.

  7. Attention and transformer layers · Advanced · 15 min

    Use F.scaled_dot_product_attention for fast fused attention, understand the math behind it, and the built-in transformer layers.

Training & data

  1. Loss functions · Essentials · 10 min

    Use CrossEntropyLoss with raw logits and int64 class labels, BCEWithLogitsLoss for binary or multi-label targets, MSELoss for regression.

  2. Optimizers · Essentials · 10 min

    Use torch.optim (SGD, Adam, AdamW) to update parameters from their gradients with zero_grad, backward, step.

  3. The training loop · Essentials · 15 min

    Put it together: iterate over batches, forward, loss, backward, step, then evaluate under torch.no_grad.

  4. Dataset and DataLoader · Practical · 14 min

    Wrap data in a Dataset with __len__ and __getitem__, then let DataLoader batch, shuffle and load it in parallel.

  5. Saving and loading checkpoints · Practical · 10 min

    Save state_dicts of the model and optimizer with torch.save, and load them safely with torch.load(weights_only=True).

  6. Learning-rate schedules · Practical · 9 min

    Change the learning rate during training with torch.optim.lr_scheduler: step decay, cosine, warmup and OneCycle.

  7. Gradient clipping and accumulation · Practical · 10 min

    Cap the gradient norm to stabilise training, and accumulate gradients over micro-batches to simulate a bigger batch.

  8. Reproducibility and seeding · Practical · 8 min

    Seed every random source, control DataLoader randomness, and opt into deterministic algorithms when you need identical runs.

GPU & performance

  1. Training on a GPU · Practical · 10 min

    Move the model and each batch to the accelerator, write device-agnostic code, and avoid hidden synchronisations.

  2. Automatic mixed precision · Advanced · 12 min

    Run matmuls in bfloat16 or float16 with torch.autocast, scale fp16 losses with GradScaler, and enable TF32.

  3. torch.compile · Advanced · 14 min

    Speed up models with one line: torch.compile captures Python into graphs and generates fused kernels, with caveats about graph breaks and recompiles.

  4. Profiling and benchmarking · Advanced · 12 min

    Find where time goes with torch.profiler, label regions with record_function, and benchmark correctly with torch.utils.benchmark.

  5. GPU memory management · Expert · 16 min

    The caching allocator, allocated versus reserved memory, fragmentation, memory snapshots, and activation checkpointing to trade compute for memory.

Distributed training

  1. DistributedDataParallel · Advanced · 16 min

    Train on several GPUs or machines with DDP: one process per GPU, launched by torchrun, with a DistributedSampler and gradient all-reduce.

  2. Fully sharded data parallel (FSDP) · Expert · 18 min

    Shard parameters, gradients and optimizer state across GPUs with fully_shard (FSDP2) to train models too large for one device.

Extending & deploying

  1. The dispatcher and custom ops · Expert · 18 min

    How torch calls are routed to ATen kernels by dispatch keys, and how to register custom operators with torch.library that work with autograd and torch.compile.

  2. torch.export for deployment · Expert · 15 min

    Capture a model as a whole-graph ExportedProgram with dynamic shapes, save it as .pt2, and feed AOTInductor, ONNX or ExecuTorch.