PyTorch
Overview
PyTorch is a Python-first deep learning framework offering GPU-accelerated tensors and a tape-based automatic differentiation system (autograd) with dynamic computation graphs. It is the dominant framework for ML research and is widely deployed in production via TorchScript, torch.compile, and ExecuTorch. Read this when defining models, writing custom training loops, managing devices, or building data pipelines.
Official sources
Install / setup
# CPU-only (pip). For CUDA/ROCm builds, use the selector to get the right index URL.
pip install torch torchvision torchaudio
Command from the official install selector: https://pytorch.org/get-started/locally/
Core concepts
- Tensor — n-dimensional array with a dtype and
.device; supports GPU acceleration and NumPy-like ops.
- autograd — tensors with
requires_grad=True record ops on a dynamic graph; .backward() computes gradients.
- torch.nn.Module — base class for models/layers; holds parameters and defines
forward().
- Optimizer + loss —
torch.optim (SGD, Adam) updates parameters from gradients; losses live in torch.nn.
- Dataset / DataLoader — abstractions for sampling, batching, shuffling, and parallel data loading.
- Device model — explicitly move tensors/modules with
.to(device) (cuda, mps, cpu).
- torch.compile — JIT graph capture + kernel fusion for speedups without changing model code.
Best practices
Common pitfalls
- "Expected all tensors on same device" → move both model and inputs with
.to(device).
- Accumulating graphs/memory by appending live tensors to a list → call
.item() or .detach() for logging.
- Forgetting
model.train() after model.eval() → batchnorm/dropout behave wrong in the next epoch.
Examples
import torch
from torch import nn
device = "cuda" if torch.cuda.is_available() else "cpu"
model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()
x, y = torch.randn(32, 784, device=device), torch.randint(0, 10, (32,), device=device)
for _ in range(3):
opt.zero_grad()
loss = loss_fn(model(x), y)
loss.backward()
opt.step()
Further reading
Related skills
- ../tensorflow — alternative deep learning framework
- ../keras — high-level API that can run on a PyTorch backend (Keras 3)
- ../numpy — array library PyTorch tensors convert to/from
1---2name: pytorch3description: PyTorch is an open-source deep learning framework with Pythonic tensors, dynamic (define-by-run) autograd, and strong GPU/CUDA acceleration, widely used for research and production. Consult this when building neural networks with torch.nn, writing training loops with autograd and optimizers, moving tensors between CPU/GPU/MPS devices, loading data with Dataset/DataLoader, compiling with torch.compile, doing distributed/DDP training, or saving/loading state_dict checkpoints, and when debugging device mismatches, gradient/requires_grad issues, or CUDA installs.4domain: stack5category: aiml6tags: [pytorch, deep-learning, machine-learning, autograd, neural-networks, gpu, python]7official_sources:8 - https://docs.pytorch.org/docs/stable/index.html9 - https://github.com/pytorch/pytorch10 - https://pytorch.org/get-started/locally/11verified: 2026-06-1712metadata:13 source: https://skillmd.com/skills/gabriel7silva/pytorch14---1516# PyTorch1718## Overview19PyTorch is a Python-first deep learning framework offering GPU-accelerated tensors and a tape-based automatic differentiation system (autograd) with dynamic computation graphs. It is the dominant framework for ML research and is widely deployed in production via TorchScript, `torch.compile`, and ExecuTorch. Read this when defining models, writing custom training loops, managing devices, or building data pipelines.2021## Official sources22- Docs: https://docs.pytorch.org/docs/stable/index.html23- Repo: https://github.com/pytorch/pytorch24- Install: https://pytorch.org/get-started/locally/2526## Install / setup27```bash28# CPU-only (pip). For CUDA/ROCm builds, use the selector to get the right index URL.29pip install torch torchvision torchaudio30```31Command from the official install selector: https://pytorch.org/get-started/locally/3233## Core concepts34- **Tensor** — n-dimensional array with a dtype and `.device`; supports GPU acceleration and NumPy-like ops.35- **autograd** — tensors with `requires_grad=True` record ops on a dynamic graph; `.backward()` computes gradients.36- **torch.nn.Module** — base class for models/layers; holds parameters and defines `forward()`.37- **Optimizer + loss** — `torch.optim` (SGD, Adam) updates parameters from gradients; losses live in `torch.nn`.38- **Dataset / DataLoader** — abstractions for sampling, batching, shuffling, and parallel data loading.39- **Device model** — explicitly move tensors/modules with `.to(device)` (`cuda`, `mps`, `cpu`).40- **torch.compile** — JIT graph capture + kernel fusion for speedups without changing model code.4142## Best practices43- Zero gradients each step (`optimizer.zero_grad()`) before `loss.backward()` (https://docs.pytorch.org/tutorials/beginner/basics/optimization_tutorial.html).44- Save the `state_dict`, not the whole pickled model, for portable checkpoints (https://docs.pytorch.org/tutorials/beginner/saving_loading_models.html).45- Wrap eval/inference in `with torch.no_grad():` and call `model.eval()` to disable dropout/batchnorm updates (https://docs.pytorch.org/docs/stable/notes/autograd.html).46- Use `DataLoader(num_workers=...)` and `pin_memory=True` to overlap loading with compute (https://docs.pytorch.org/docs/stable/data.html).4748## Common pitfalls49- "Expected all tensors on same device" → move both model and inputs with `.to(device)`.50- Accumulating graphs/memory by appending live tensors to a list → call `.item()` or `.detach()` for logging.51- Forgetting `model.train()` after `model.eval()` → batchnorm/dropout behave wrong in the next epoch.5253## Examples54```python55import torch56from torch import nn5758device = "cuda" if torch.cuda.is_available() else "cpu"59model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)60opt = torch.optim.Adam(model.parameters(), lr=1e-3)61loss_fn = nn.CrossEntropyLoss()6263x, y = torch.randn(32, 784, device=device), torch.randint(0, 10, (32,), device=device)64for _ in range(3):65 opt.zero_grad()66 loss = loss_fn(model(x), y)67 loss.backward()68 opt.step()69```7071## Further reading72- https://docs.pytorch.org/tutorials/ — official tutorials and recipes73- https://docs.pytorch.org/docs/stable/notes/autograd.html — autograd mechanics74- https://pytorch.org/get-started/locally/ — install selector for CPU/CUDA/ROCm7576## Related skills77- ../tensorflow — alternative deep learning framework78- ../keras — high-level API that can run on a PyTorch backend (Keras 3)79- ../numpy — array library PyTorch tensors convert to/from