PyTorch

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

PyTorch is a Python deep-learning framework built around tensors, automatic differentiation and a define-by-run style: the code you write is the computation that runs. This sub-section of the ML (Machine Learning) section documents it page by page, from installation and tensors to compiling, exporting and distributing models. The general pages of the section explain the ideas; these pages show how PyTorch implements them.

Version baseline

Item Value checked on 2026-10-30

PyTorch

2.15.0, released on 2026-10-28. All pages target this release.

Python

Examples were run on Python 3.13 with PyTorch 2.15 on 2026-10-31, on a CPU-only machine (macOS arm64, where Apple MPS is the accelerator). Distributed examples ran as CPU processes under torchrun with the Gloo back end. Examples that need a CUDA GPU, FFmpeg or a mobile toolchain say so on their page and were not executed. PyTorch 2.15 no longer ships Python 3.10 wheels.

torchvision

0.29.2, the release that matches PyTorch 2.15; see torchvision.

Installation

pip is the supported route; conda is no longer an official channel. See Installation & Versions.

Reading path

flowchart TD A[Installation, tensors, devices] --> B[Autograd and grad modes] B --> C[nn.Module and layers] C --> D[Losses, optimizers, schedulers] D --> E[Datasets, DataLoader, training loop] E --> F[Saving, transfer learning, worked examples] F --> G[Mixed precision, memory, profiling] G --> H[torch.compile] H --> I[torch.export, AOTInductor, ONNX, ExecuTorch] G --> J[DDP, FSDP2, DTensor, distributed checkpoint] F --> K[torchvision, ecosystem]

Library status

The PyTorch ecosystem changed a lot between older books and 2.15. This table summarises the status of the pieces most often met in older material; the details are on Legacy APIs & Migration and Ecosystem.

Component Status What to use instead

TorchServe

Archived

Serve exported models with a general-purpose server, or ONNX Runtime; see Deploying & Serving ML Models.

torchtext

Archived

Hugging Face tokenizers and datasets, or your own data pipeline.

TorchScript

Deprecated

torch.export, AOTInductor and the ONNX exporter; see torch.export.

torchaudio

Maintenance

Audio decoding and encoding moved to TorchCodec; see torchaudio (Maintenance) & TorchCodec.

ExecuTorch

Part of PyTorch Core

The route to phones and embedded boards; see ExecuTorch for Mobile & Edge.

conda channel

Deprecated

Install with pip; see Installation & Versions.

Concept-to-page map

Getting started and tensors

Page What it covers

Installation & Versions

Installing PyTorch 2.15 with pip for CPU, CUDA, ROCm and XPU, supported Python versions and the end of the conda channel.

Tensors: Creation, Attributes & Dtypes

Creating tensors, shape, dtype, device, layout, strides and type promotion.

Indexing, Views & Broadcasting

Indexing, slicing, views, reshape, contiguity, in-place semantics and broadcasting.

Sparse, Nested & Complex Tensors

Sparse, nested (jagged) and complex tensors.

NumPy & DLPack Interop

Moving data between tensors and NumPy arrays or other libraries with DLPack, and which conversions share memory.

Devices & Accelerators: CUDA, ROCm, MPS, XPU, CPU

Selecting and using CUDA, ROCm, MPS, XPU and CPU devices with device-agnostic code.

Autograd

Page What it covers

Autograd Fundamentals

How autograd records a graph and computes gradients, with accumulation, detach, in-place pitfalls and hooks.

no_grad, inference_mode & Grad Modes

Switching gradient recording on and off with no_grad, enable_grad and inference_mode.

Custom autograd Functions

Extending autograd with torch.autograd.Function, double backward, forward-mode and gradcheck.

Higher-Order Gradients & torch.func

Second and higher derivatives, forward-mode AD and the composable torch.func transforms.

Building models

Page What it covers

nn.Module: Parameters, Buffers, state_dict, Hooks, Containers & Init

Parameters, buffers, state_dict, hooks, containers and initialisation of nn.Module.

torch.nn.functional

When to use torch.nn.functional instead of modules, and the pitfalls of stateless functions.

Linear, Convolution & Pooling Layers

Linear, convolution, transposed convolution and pooling layers with output-size formulas.

RNN, LSTM & GRU

nn.RNN, nn.LSTM and nn.GRU: shapes, batch_first, bidirectional and stacked layers.

Embeddings, Normalization, Dropout & Activations

Embedding, normalisation, dropout and activation layers.

Attention, SDPA, FlexAttention & Transformers

scaled_dot_product_attention, backend selection, MultiheadAttention, nn.Transformer and FlexAttention.

Training

Page What it covers

Loss Functions

Which losses expect logits or probabilities, target shapes, reductions, class weights and label smoothing.

Optimizers

The torch.optim algorithms, parameter groups, weight decay and fused implementations.

Learning-Rate Schedulers & SWA/EMA

Learning-rate schedulers, warmup, stochastic weight averaging and EMA.

Datasets & DataLoader

Map-style and iterable datasets, samplers, collate functions and DataLoader arguments.

Workers, Pinned Memory & Samplers

Workers, pinned memory, prefetching, worker seeding and resumable loading.

The Training Loop & Evaluation

The canonical training and evaluation loop explained step by step.

Saving & Loading Models (weights_only)

Saving and loading safely: state_dict, the weights_only default and checkpointing patterns.

Transfer Learning & Fine-Tuning

Reusing pre-trained torchvision models: replacing the head, freezing layers and discriminative learning rates.

Reproducibility & Determinism

Seeding and deterministic algorithms for repeatable runs, and what is not guaranteed.

TensorBoard Integration

Logging scalars, images, graphs and embeddings with SummaryWriter.

Performance

Page What it covers

Mixed Precision with torch.amp

Automatic mixed precision with torch.autocast and GradScaler.

GPU Memory & Activation Checkpointing

Where GPU memory goes, the caching allocator and activation checkpointing.

Performance Tuning Guide

A checklist of the official performance recommendations with runnable examples.

Profiling with torch.profiler

Finding the real bottleneck with torch.profiler.

torch.compile

How TorchDynamo, AOTAutograd and Inductor work together, and the options of torch.compile.

Graph Breaks, Recompilation & Dynamic Shapes

Graph breaks, recompilation and dynamic shapes.

Export, extensions and deployment

Page What it covers

torch.export

Ahead-of-time capture into an ExportedProgram with dynamic shapes.

AOTInductor

Compiling an exported model into a self-contained package with AOTInductor.

Exporting to ONNX

Exporting to ONNX with the torch.export based exporter.

Custom Operators, C++/CUDA Extensions & Triton

Custom operators with torch.library, C++ and CUDA extensions, and Triton kernels.

Quantization, Sparsity & Pruning with torchao

Quantisation, sparsity and pruning with torchao.

ExecuTorch for Mobile & Edge

Running models on phones and embedded boards with ExecuTorch.

Distributed training

Page What it covers

Distributed Overview, torchrun & Elastic

The map of distributed training, torchrun, rendezvous and elastic scaling.

DistributedDataParallel

DistributedDataParallel: setup, bucketed all-reduce, no_sync and communication hooks.

FSDP2 (fully_shard)

Training models that do not fit on one GPU with fully_shard.

DTensor, Tensor & Pipeline Parallelism

DeviceMesh, DTensor, tensor parallelism and pipeline parallelism.

Distributed Checkpoint & Flight Recorder

Sharded checkpoints with torch.distributed.checkpoint and the Flight Recorder for hung jobs.

Libraries and ecosystem

Page What it covers

torchvision: Transforms v2, Models & Weights

Transforms v2, models and weights, datasets and feature extraction.

torchaudio (Maintenance) & TorchCodec

What remains in torchaudio in maintenance mode, and decoding with TorchCodec.

Ecosystem: Lightning, Hugging Face, Captum, skorch, Ray & TorchRL

Lightning, Hugging Face, Captum, skorch, Ray Train and TorchRL around PyTorch.

Legacy APIs & Migration

APIs and habits from older books and tutorials that are deprecated, removed or archived.

Worked examples

Page What it covers

Worked Example: CNN Image Classifier

A complete CIFAR-10 image classification project.

Worked Example: Character RNN & seq2seq

A character-level RNN and a sequence-to-sequence model.

Worked Example: Transformer Building Blocks

A small decoder-only transformer built from PyTorch primitives.

The general pages that these pages build on include Backpropagation & Automatic Differentiation, Distributed Training Concepts, Hardware, Memory & Mixed Precision and Choosing a Framework. Return to the ML (Machine Learning) landing page for the whole section.

Bibliography

All official links below were opened on 2026-10-30. Books and general sources for the whole section are listed in the ML bibliography.

Releases and installation

Documentation and tutorials

  • PyTorch documentation (stable, 2.15): serialization, quantization, ONNX, AMP, FSDP, compile, export, func, autograd, data, reproducibility, accelerators, nested and sparse tensors, optim, nn, attention, distributed, DTensor, tensor parallel, pipelining, distributed checkpoint, elastic, profiler, CUDA memory, library, cpp_extension and TensorBoard, plus the torch.export user guide

  • PyTorch tutorials: Learn the Basics, the performance tuning guide, custom operators, torch.compile, DDP, FSDP, tensor parallel, pipelining, Flight Recorder, ONNX export, transfer learning, character-level RNN, sequence-to-sequence, SDPA and transformer building blocks

Libraries

Package metadata

Sources cited by individual pages

The official sources below are cited in the References section of one page each; a source shared by several pages is listed once, under the first page that cites it.