Deep Learning & LLM Systems Masterclass PyTorch 2.6+ • ATen C++ • Triton • FSDP2

PyTorch 2.x Engineering: Tensors, Autograd, torch.compile & FSDP2

Over 90% of frontier Large Language Models, diffusion architectures, and autonomous AI agent backbones are trained and fine-tuned in PyTorch. This production masterclass takes you under the hood of PyTorch 2.x—from zero-copy strided UntypedStorage memory views and C++ Reverse-Mode Autograd DAGs to F.scaled_dot_product_attention (FlashAttention-2), torch.compile Triton kernel fusion, mixed-precision bfloat16 training loops, and multi-node FSDP2 (DTensor) sharding.

🔥 Strided Tensor Memory ∇ Reverse-Mode Autograd ⚡ torch.compile + Triton 🧠 FlashAttention-2 SDPA 🌐 FSDP2 & DTensor

01 Evolution of PyTorch & The PyTorch 2.x torch.compile Stack

Eager Ergonomics + Compiled Speed

When Facebook AI Research (FAIR) released PyTorch 0.1 in January 2017 (combining the C/CUDA tensor backends of Lua Torch7 with the define-by-run dynamic autograd philosophy of Chainer), deep learning was dominated by static-graph frameworks (TensorFlow 1.x, Theano, Caffe) that required compiling a rigid symbolic graph before inspecting a single tensor. PyTorch won researchers over with imperative eager execution—every line of Python immediately dispatches an ATen C++/CUDA kernel, allowing standard Python pdb debugging, dynamic control flow, and variable-length structures.

However, pure eager execution pays a heavy memory-bandwidth tax on modern GPUs: executing y = torch.sin(x) + torch.cos(x) eagerly launches three separate CUDA kernels and round-trips intermediate tensors between GPU SRAM and off-chip HBM three times. PyTorch 2.x (torch.compile) solves this without sacrificing Python eager semantics through a 4-stage compiler pipeline:

PYTHON MODEL:  @torch.compile(mode="max-autotune", fullgraph=False)
               def swiglu(x, w_gate, w_up): return F.silu(x @ w_gate) * (x @ w_up)
  │
  ├─▶ STAGE 1: TorchDynamo (Graph Acquisition via PEP 523 Python Frame Evaluation Hook)
  │     • Intercepts CPython frame execution dynamically; traces PyTorch ops into an FX Graph.
  │     • Inserts fast C guards on tensor shapes/strides; cleanly falls back to Python on unsupported graph breaks!
  │
  ├─▶ STAGE 2: AOTAutograd (Ahead-of-Time Forward + Backward Graph Capture)
  │     • Traces BOTH the forward pass AND the C++ Autograd backward pass ahead of time using FakeTensors.
  │     • Chooses optimal min-cut activation checkpoints between forward and backward graphs.
  │
  ├─▶ STAGE 3: PrimTorch (Operator Decomposition & Canonicalization)
  │     • Lowers 2,000+ high-level ATen operators down to ~250 core functional Aten/Prims operators.
  │
  └─▶ STAGE 4: TorchInductor (Hardware Codegen → OpenAI Triton GPU Kernels / C++ OpenMP)
        • Fuses pointwise, reduction, and epilogue ops into a single Triton GPU kernel!
        • Intermediate values stay in 20+ TB/s on-chip GPU SRAM instead of 3 TB/s off-chip HBM (1.5x–2.5x speedup).
Table 1.1 — PyTorch 2.x vs. JAX vs. TensorFlow 2 vs. Apple MLX (2026 Deep Learning Stack Comparison)
Dimension PyTorch 2.x JAX / Flax NNX TensorFlow 2 / Keras 3 Apple MLX
Execution & State Model Imperative OOP (nn.Module holds mutable in-place weights & buffers) Pure functional transforms (grad, jit, vmap, pmap); explicit PRNG keys Eager + @tf.function graph tracing Lazy evaluation + unified CPU/GPU memory (zero host-device copies)
Compiler Backend torch.compile (TorchDynamo → TorchInductor → Triton) @jax.jit → OpenXLA (HLO compiler for GPU & Google TPU) XLA + TFLite / TensorRT mx.compile → Apple Metal GPU shaders
Distributed Sharding DDP, FSDP2 (fully_shard), DTensor, DeviceMesh (TorchTitan) jax.sharding.Mesh + PartitionSpec (GSPMD auto-sharding) tf.distribute.Strategy / DTensor mx.distributed (MPI / Ring over Thunderbolt)
Primary Ecosystem Dominance 90%+ of LLM research, HuggingFace, vLLM, SGLang, DeepSpeed, Llama/Qwen/DeepSeek Google TPU Pods (Gemini, Gemma, AlphaFold), scientific computing Legacy enterprise pipelines, TFLite mobile/embedded edge Local LLM training & inference on M1–M4 Mac Studios/MacBooks

02 Tensor Internals: Strided Memory (UntypedStorage), Views & Broadcasting

C++ ATen TensorImpl

The single most important mental model in PyTorch is that a torch.Tensor (c10::TensorImpl in C++) is not the multidimensional array of numbers itself—it is a lightweight metadata header (shape, stride, storage_offset, dtype, device, requires_grad) pointing to a flat, 1-dimensional contiguous byte buffer called torch.UntypedStorage in CPU RAM or GPU HBM:

Logical 2D Tensor x (shape = [2, 3], stride = [3, 1], offset = 0):
   ┌──────────┬──────────┬──────────┐
   │ x[0,0]=1 │ x[0,1]=2 │ x[0,2]=3 │   Physical Memory Address Formula for x[i, j]:
   ├──────────┼──────────┼──────────┤   address(i, j) = storage_ptr + (storage_offset + i * stride[0] + j * stride[1]) * itemsize
   │ x[1,0]=4 │ x[1,1]=5 │ x[1,2]=6 │
   └──────────┴──────────┴──────────┘
        │
        ▼ Points to 1D Contiguous Physical Storage Buffer (UntypedStorage in GPU HBM / CPU RAM):
   ┌─────┬─────┬─────┬─────┬─────┬─────┐
   │  1  │  2  │  3  │  4  │  5  │  6  │   ◀── Transposing y = x.T DOES NOT MOVE OR COPY A SINGLE BYTE!
   └─────┴─────┴─────┴─────┴─────┴─────┘       It simply creates a new Tensor header with shape=[3, 2] and stride=[1, 3]!
Table 2.1 — Essential PyTorch Tensor Operations, Memory Semantics & Data Types
Category Core Methods & Signatures Allocates New Memory? Production Engineering Rule & Gotchas
Floating-Point Dtypes torch.float32, torch.bfloat16, torch.float16, torch.float8_e4m3fn 4B / 2B / 2B / 1B per elem Always prefer torch.bfloat16 over float16 on Ampere/Hopper/Blackwell GPUs: BF16 has the exact same 8-bit exponent range as FP32 (preventing gradient underflow/overflow without GradScaler!).
Zero-Copy Views t.view(*shape), t.transpose(d0, d1), t.permute(*dims), t.unsqueeze(d), t.squeeze(d), t.expand(*sizes), t[:, :k] NO (O(1) metadata view) Mutating a view in-place (view.add_(1)) mutates the original tensor! expand() broadcasts a size-1 dimension by setting its stride to 0 (zero extra RAM!).
Reshape vs Contiguous t.is_contiguous(), t.contiguous(), t.reshape(*shape), t.flatten(start, end) Only if non-contiguous After transpose() or permute(), strides are non-monotonic (is_contiguous() == False), so t.view() raises RuntimeError. Call t.reshape() or t.contiguous().view().
Explicit Copies & Bridges t.clone(), t.detach(), t.to(device, dtype, non_blocking=True), torch.from_numpy(arr), t.numpy() clone() copies; from_numpy() is zero-copy on CPU! t.clone() allocates fresh storage AND stays attached to Autograd (CloneBackward0). Use t.detach().clone() for an independent copy with no gradient history.
Matrix & Einsum Contractions A @ B (torch.matmul), torch.bmm, torch.einsum("bhqd,bhkd->bhqk", Q, K), F.linear(x, W, b) Yes (Output buffer) torch.einsum expresses multi-head attention, bilinear forms, and tensor traces cleanly without error-prone chains of permute and unsqueeze.

Runnable Lab: Strided Views, Zero-Stride Expand & Contiguity

Runs in Wasm Sandbox

Click Run in Sandbox to see how PyTorch’s C++ TensorImpl computes memory offsets via (offset + Σ idx_d * stride_d), why transpose() breaks contiguity, and how expand() achieves zero-memory broadcasting via stride = 0:

# Pure-Python implementation of PyTorch's C++ Strided TensorImpl & UntypedStorage
class StridedTensorView:
    def __init__(self, storage: list[float], shape: tuple[int, ...], strides: tuple[int, ...], offset: int = 0):
        self.storage = storage
        self.shape = shape
        self.strides = strides
        self.offset = offset

    def __getitem__(self, indices: tuple[int, int]) -> float:
        # Exact C++ ATen address calculation: offset + i*stride[0] + j*stride[1]
        flat_idx = self.offset + sum(i * s for i, s in zip(indices, self.strides))
        return self.storage[flat_idx]

    def transpose_2d(self) -> "StridedTensorView":
        # Zero-copy! Shares the exact same self.storage list, just swaps shape & strides
        return StridedTensorView(self.storage, (self.shape[1], self.shape[0]), (self.strides[1], self.strides[0]), self.offset)

    def is_contiguous(self) -> bool:
        expected_stride = 1
        for dim_size, st in zip(reversed(self.shape), reversed(self.strides)):
            if dim_size > 1 and st != expected_stride:
                return False
            expected_stride *= dim_size
        return True

# 1. Create a 2x3 tensor backed by a 6-element flat storage buffer
raw_storage = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]
x = StridedTensorView(raw_storage, shape=(2, 3), strides=(3, 1))
x_t = x.transpose_2d()

print(f"Original x:   shape={x.shape}, strides={x.strides}, is_contiguous={x.is_contiguous()}")
print(f"Transposed:   shape={x_t.shape}, strides={x_t.strides}, is_contiguous={x_t.is_contiguous()}")
print(f"Zero-copy verify: x[1, 2]={x[(1, 2)]} == x_t[2, 1]={x_t[(2, 1)]} (same storage id={id(x.storage) == id(x_t.storage)})")

# 2. Zero-Stride Broadcasting (How tensor.expand(4, 3) broadcasts a (1, 3) row vector in 0 extra bytes!)
row_storage = [1.5, 2.5, 3.5]
expanded = StridedTensorView(row_storage, shape=(4, 3), strides=(0, 1))
print("Zero-stride broadcast expanded[3, 1]:", expanded[(3, 1)], "(Reads storage[0*3 + 1*1] = 2.5!)")

Production PyTorch 2.x Tensor & Einsum Idioms

PyTorch 2.6+ GPU Idioms

Essential idioms for device-agnostic allocation, Multi-Head Attention view + transpose head splitting, torch.einsum, and in-place masking:

import torch

# 1. Hardware-Agnostic Device & Precision Selection (CUDA -> Apple MPS -> CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
dtype = torch.bfloat16 if (device.type == "cuda" and torch.cuda.is_bf16_supported()) else torch.float32

# 2. Allocate directly on target device (NEVER do torch.randn(...).cuda(), which allocates CPU RAM first!)
B, T, D = 4, 1024, 512
n_heads, d_head = 8, 64
x = torch.randn(B, T, D, device=device, dtype=dtype)

# 3. Splitting Hidden Dim D into (n_heads, d_head) via Zero-Copy View + Transpose
# [B, T, D] -> view [B, T, H, d_h] -> transpose(1, 2) -> [B, H, T, d_h]
q = x.view(B, T, n_heads, d_head).transpose(1, 2)
assert not q.is_contiguous()  # Transpose changed strides from (524288, 512, 64, 1) to (524288, 64, 512, 1)

# 4. Batched Attention Scores via torch.einsum vs Matmul
k = torch.randn(B, n_heads, T, d_head, device=device, dtype=dtype)
scores = torch.einsum("bhqd,bhkd->bhqk", q, k) / (d_head ** 0.5)

# 5. Causal Lower-Triangular Masking with masked_fill_
causal_mask = torch.triu(torch.ones(T, T, device=device, dtype=torch.bool), diagonal=1)
scores.masked_fill_(causal_mask, float("-inf"))

# 6. Merging Heads Back to [B, T, D] Requires .contiguous() (or .reshape())!
merged = q.transpose(1, 2).contiguous().view(B, T, D)

03 The Autograd Engine: Dynamic DAGs (grad_fn), Jacobians & Memory Traps

Reverse-Mode Automatic Differentiation

Whenever you perform an operation on a tensor with requires_grad=True, PyTorch’s C++ Dispatcher routes the call through the Autograd Engine. It allocates a Node (such as AddBackward0, MmBackward0, or SiluBackward0), attaches it to the output tensor’s .grad_fn pointer, and saves any forward activations needed for the chain-rule Vector-Jacobian Product (vᵀ · J). When loss.backward() is called:

  1. Topological Sort: The C++ Engine::execute computes dependency refcounts across all reachable grad_fn nodes from loss back to user-created Leaf Tensors (tensor.is_leaf == True, such as model nn.Parameter weights).
  2. Vector-Jacobian Propagation & Buffer Release: As each node’s backward function executes, it frees its saved forward activations immediately (which is why calling loss.backward() a second time raises RuntimeError unless retain_graph=True was passed).
  3. Gradient Accumulation into AccumulateGrad Sinks: At leaf parameters, gradients are added in-place (param.grad += new_grad). If you forget to call optimizer.zero_grad(set_to_none=True), gradients from previous batches corrupt the current step!

Runnable Lab: PyTorch Reverse-Mode Autograd DAG Engine

Runs in Wasm Sandbox

Run this self-contained Tensor Autograd engine in the browser sandbox to trace grad_fn nodes, topological sorting, and gradient accumulation traps:

import math

class MiniTensor:
    """Minimal Reverse-Mode Autograd Scalar/Tensor mirroring torch.Tensor & grad_fn."""
    def __init__(self, data: float, requires_grad: bool = False, _children=(), _grad_fn: str = "Leaf"):
        self.data = float(data)
        self.requires_grad = requires_grad
        self.grad: float | None = 0.0 if requires_grad else None
        self.grad_fn = None if _grad_fn == "Leaf" else _grad_fn
        self.is_leaf = (_grad_fn == "Leaf")
        self._prev = set(_children)
        self._backward = lambda: None

    def __mul__(self, other: "MiniTensor") -> "MiniTensor":
        out = MiniTensor(self.data * other.data, self.requires_grad or other.requires_grad, (self, other), "MulBackward0")
        def _bw():
            if self.requires_grad:
                self.grad = (self.grad or 0.0) + other.data * out.grad
            if other.requires_grad:
                other.grad = (other.grad or 0.0) + self.data * out.grad
        out._backward = _bw
        return out

    def __add__(self, other: "MiniTensor") -> "MiniTensor":
        out = MiniTensor(self.data + other.data, self.requires_grad or other.requires_grad, (self, other), "AddBackward0")
        def _bw():
            if self.requires_grad:
                self.grad = (self.grad or 0.0) + 1.0 * out.grad
            if other.requires_grad:
                other.grad = (other.grad or 0.0) + 1.0 * out.grad
        out._backward = _bw
        return out

    def silu(self) -> "MiniTensor":
        sig = 1.0 / (1.0 + math.exp(-self.data))
        out = MiniTensor(self.data * sig, self.requires_grad, (self,), "SiluBackward0")
        def _bw():
            if self.requires_grad:
                # d/dx [x * σ(x)] = σ(x) + x * σ(x) * (1 - σ(x))
                local_grad = sig * (1.0 + self.data * (1.0 - sig))
                self.grad = (self.grad or 0.0) + local_grad * out.grad
        out._backward = _bw
        return out

    def backward(self) -> None:
        topo, visited = [], set()
        def build(node):
            if node not in visited:
                visited.add(node)
                for child in node._prev:
                    build(child)
                topo.append(node)
        build(self)
        self.grad = 1.0
        for node in reversed(topo):
            node._backward()

w = MiniTensor(2.0, requires_grad=True)
x = MiniTensor(1.5, requires_grad=False)
b = MiniTensor(-0.5, requires_grad=True)

# Forward pass builds dynamic DAG: y = SiLU(w * x + b)
z = (w * x) + b
loss = z.silu()
loss.backward()

print(f"Forward Output: z={z.data:.4f} (grad_fn={z.grad_fn}) -> loss={loss.data:.4f} (grad_fn={loss.grad_fn})")
print(f"Backward Grads: w.grad={w.grad:.6f} (is_leaf={w.is_leaf}), b.grad={b.grad:.6f}")

Custom torch.autograd.Function & The #1 OOM Bug

Custom Backward & Safety

Subclass torch.autograd.Function when writing custom Triton/CUDA kernels or memory-efficient activations, and never append raw loss tensors to a logging list:

import torch

# 1. Custom Autograd Function (e.g., Straight-Through Estimator / Custom Fused Kernel)
class StraightThroughQuantize(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x: torch.Tensor, scale: float) -> torch.Tensor:
        ctx.save_for_backward(x)
        ctx.scale = scale
        # Non-differentiable round() in forward pass:
        return torch.clamp(torch.round(x / scale), -8, 7) * scale

    @staticmethod
    def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None]:
        (x,) = ctx.saved_tensors
        # Pass gradient straight through inside clipping range [-8*s, 7*s]
        mask = (x >= -8 * ctx.scale) & (x <= 7 * ctx.scale)
        return grad_output * mask.to(grad_output.dtype), None

# 2. THE #1 PRODUCTION PYTORCH MEMORY LEAK:
# ❌ WRONG: loss carries a grad_fn pointer to the ENTIRE forward activation graph!
# history.append(loss)  # Pins gigabytes of GPU activations in VRAM forever!

# ✅ RIGHT: Detach or extract Python float via .item()
# running_loss += loss.detach()   # Keeps on GPU without CPU-GPU sync stall!
# print(running_loss.item())      # Syncs once at logging interval

# 3. torch.inference_mode() vs torch.no_grad()
@torch.inference_mode()  # Faster than @torch.no_grad(): skips version counter & view tracking!
def predict_logits(model: torch.nn.Module, input_ids: torch.Tensor) -> torch.Tensor:
    return model(input_ids)

04 Neural Networks & Transformers with nn.Module & FlashAttention-2 SDPA

Llama-4 / Qwen-3 Architecture in PyTorch

torch.nn.Module is PyTorch’s composable stateful container. When you assign an nn.Parameter or child nn.Module as an attribute on self, Module.__setattr__ automatically registers it in self._parameters or self._modules so that model.parameters(), model.to(device), and model.state_dict() traverse the entire hierarchy recursively.

1. nn.Parameter vs. register_buffer

Use nn.Parameter(t) for trainable weights updated by the optimizer. Use self.register_buffer("cos_cached", t, persistent=False) for non-trainable device tensors (like RoPE frequency tables or causal masks) that must move with model.to(device) without cluttering optimizer state or checkpoints.

2. F.scaled_dot_product_attention

Never write softmax(Q @ K.T / sqrt(d)) @ V manually in production—it materializes an O(T²) matrix in HBM. F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True) automatically dispatches fused FlashAttention-2 / cuDNN kernels in O(T) memory!

3. nn.ModuleList & Safetensors

Never store layers in a plain Python list self.layers = [Block() for _ in range(L)]—PyTorch won't register their parameters! Always wrap layer lists in nn.ModuleList(...), and serialize weights using safetensors.torch.save_file (zero-copy mmap, immune to pickle code execution).

Complete PyTorch 2.x Frontier Transformer Decoder Block (GQA + FlashAttention SDPA + Pre-RMSNorm + SwiGLU)

Production Architecture
import torch
import torch.nn as nn
import torch.nn.functional as F

class SwiGLUFFN(nn.Module):
    """3-Matrix Gated Feed-Forward Network used in Llama 3/4, Qwen 3, and DeepSeek."""
    def __init__(self, d_model: int, d_ff: int):
        super().__init__()
        self.w_gate = nn.Linear(d_model, d_ff, bias=False)
        self.w_up   = nn.Linear(d_model, d_ff, bias=False)
        self.w_down = nn.Linear(d_ff, d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))

class GroupedQueryCausalAttention(nn.Module):
    """Grouped-Query Attention (GQA) with native FlashAttention-2 SDPA dispatch."""
    def __init__(self, d_model: int, n_heads: int = 32, n_kv_heads: int = 8):
        super().__init__()
        assert n_heads % n_kv_heads == 0, "n_heads must be divisible by n_kv_heads"
        self.n_heads = n_heads
        self.n_kv_heads = n_kv_heads
        self.d_head = d_model // n_heads

        self.q_proj = nn.Linear(d_model, n_heads * self.d_head, bias=False)
        self.k_proj = nn.Linear(d_model, n_kv_heads * self.d_head, bias=False)
        self.v_proj = nn.Linear(d_model, n_kv_heads * self.d_head, bias=False)
        self.o_proj = nn.Linear(n_heads * self.d_head, d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, C = x.shape
        q = self.q_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2)
        k = self.k_proj(x).view(B, T, self.n_kv_heads, self.d_head).transpose(1, 2)
        v = self.v_proj(x).view(B, T, self.n_kv_heads, self.d_head).transpose(1, 2)

        # PyTorch 2.5+ native GQA + FlashAttention-2 fused kernel (O(T) SRAM tiling, 0 mask allocation!)
        attn_out = F.scaled_dot_product_attention(
            q, k, v,
            attn_mask=None,
            dropout_p=0.0,
            is_causal=True,
            enable_gqa=(self.n_kv_heads != self.n_heads),
        )
        # Merge heads back to [B, T, C]
        attn_out = attn_out.transpose(1, 2).contiguous().view(B, T, C)
        return self.o_proj(attn_out)

class FrontierTransformerBlock(nn.Module):
    def __init__(self, d_model: int = 4096, n_heads: int = 32, n_kv_heads: int = 8, d_ff: int = 14336):
        super().__init__()
        # Built-in fused C++/CUDA RMSNorm (PyTorch 2.4+)
        self.attn_norm = nn.RMSNorm(d_model, eps=1e-5)
        self.attn      = GroupedQueryCausalAttention(d_model, n_heads, n_kv_heads)
        self.ffn_norm  = nn.RMSNorm(d_model, eps=1e-5)
        self.ffn       = SwiGLUFFN(d_model, d_ff)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # Pre-Norm Residual Highway
        x = x + self.attn(self.attn_norm(x))
        x = x + self.ffn(self.ffn_norm(x))
        return x

05 High-Throughput DataLoader DMA & Production bfloat16 AMP Training Loop

Zero GPU Starvation

A single NVIDIA H100 or B200 GPU can consume thousands of training sequences per second. If your CPU data pipeline stalls on disk I/O, JSON tokenization, or pageable memory copies, your expensive GPU sits at 0% utilization. Pair a page-locked (pin_memory=True) multi-worker DataLoader with torch.amp.autocast("cuda", dtype=torch.bfloat16), torch.compile, fused AdamW(fused=True), gradient accumulation, and norm clipping:

The Gold-Standard PyTorch 2.x Mixed-Precision (BF16) + Gradient Accumulation Training Loop

Copy-Paste Production Template
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset

# 1. Enable TensorFloat-32 (TF32) on Ampere/Hopper/Blackwell for 3x faster FP32 matmuls
torch.set_float32_matmul_precision("high")

class TokenizedShardDataset(Dataset):
    def __init__(self, tokens_2d: torch.Tensor):
        self.data = tokens_2d  # Shape: [N_sequences, seq_len + 1]

    def __len__(self) -> int:
        return self.data.size(0)

    def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
        row = self.data[idx]
        return row[:-1], row[1:]  # (input_ids, causal next-token targets)

def train_epoch(
    model: nn.Module,
    dataset: Dataset,
    *,
    device: torch.device,
    micro_batch_size: int = 8,
    grad_accum_steps: int = 4,
    max_lr: float = 3e-4,
) -> float:
    # 2. High-Throughput DataLoader: Page-Locked Host Memory (pin_memory) + Persistent Workers
    loader = DataLoader(
        dataset,
        batch_size=micro_batch_size,
        shuffle=True,
        num_workers=4,
        pin_memory=(device.type == "cuda"),       # Enables asynchronous DMA copy to GPU HBM!
        persistent_workers=True,                  # Keeps worker processes alive across epochs
        prefetch_factor=2,
        drop_last=True,
    )

    # 3. Compile Model & Use Fused Multi-Tensor CUDA AdamW Kernel
    compiled_model = torch.compile(model.to(device), mode="default")
    optimizer = torch.optim.AdamW(
        compiled_model.parameters(),
        lr=max_lr,
        betas=(0.9, 0.95),
        weight_decay=0.1,
        fused=(device.type == "cuda"),            # Single fused CUDA kernel for AdamW weight update!
    )

    compiled_model.train()
    optimizer.zero_grad(set_to_none=True)         # Avoids memset zero-fill HBM write overhead
    running_loss = torch.zeros(1, device=device)

    for step, (input_ids, labels) in enumerate(loader, start=1):
        # 4. Async Host-to-Device DMA Transfer (non_blocking=True pairs with pin_memory=True)
        input_ids = input_ids.to(device, non_blocking=True)
        labels    = labels.to(device, non_blocking=True)

        # 5. Automatic Mixed Precision (BF16 forward pass; FP32 reductions & master weights)
        with torch.amp.autocast(device_type=device.type, dtype=torch.bfloat16):
            logits = compiled_model(input_ids)    # [B, T, V]
            loss = F.cross_entropy(
                logits.view(-1, logits.size(-1)),
                labels.view(-1),
                ignore_index=-100,                # Masks prompt/padding tokens in SFT!
            )
            scaled_loss = loss / grad_accum_steps

        # 6. Backward Pass (Accumulates gradients across micro-batches)
        scaled_loss.backward()
        running_loss += loss.detach()             # Detach! Never hold onto the autograd graph

        if step % grad_accum_steps == 0:
            # 7. Global L2 Gradient Norm Clipping (Prevents attention spike divergence)
            torch.nn.utils.clip_grad_norm_(compiled_model.parameters(), max_norm=1.0)
            optimizer.step()
            optimizer.zero_grad(set_to_none=True)

    return (running_loss / len(loader)).item()

06 Interactive PyTorch GPU VRAM, torch.compile & FSDP2 Sharding Simulator

Live Capacity Planner
PyTorch 2.x Training Memory & Throughput Estimator (AdamW + Mixed Precision)

Configure model parameter size (Ψ), distributed strategy (DDP vs. FSDP2), precision, and activation checkpointing:

✓ Fits on 8× H100 80GB (FSDP2)
8B Params
1B8B32B70B
8 GPUs
1 GPU8 (1 Node)64 GPUs
1. Weights + Gradients / GPU
4.00 GB
BF16 Weights (2Ψ/N) + BF16 Grads (2Ψ/N)
2. AdamW FP32 States / GPU
12.00 GB
FP32 Master W + m + v (12Ψ/N)
3. Activations + Transient Buffer
5.60 GB
With torch.utils.checkpoint + FlashSDPA
4. Total Per-GPU Peak VRAM
21.60 GB / GPU
torch.compile Triton speedup: ~1.85x

07 Distributed PyTorch: DDP vs. FSDP2 (fully_shard & DTensor)

Multi-GPU & Multi-Node Scaling

Never use legacy nn.DataParallel (it runs inside a single Python process, suffers from GIL contention, and bottlenecks on GPU 0). In modern PyTorch 2.x, launch one process per GPU with torchrun --nproc_per_node=8 train.py backed by NVIDIA NCCL collectives:

Table 7.1 — PyTorch Distributed Training Paradigms: DDP vs. FSDP1 vs. Modern FSDP2 (DTensor)
Paradigm PyTorch API Parameter Representation NCCL Collective Pattern Static VRAM / GPU
DDP DistributedDataParallel(model) Full replicated Tensor per GPU Bucketed AllReduce overlapped with backward pass 16Ψ (Replicates full model)
FSDP1 (Legacy) FullyShardedDataParallel(model) Concatenated 1D FlatParameter buffer AllGather + ReduceScatter on flat buffers 16Ψ / N
FSDP2 (PyTorch 2.4+) fully_shard(module, mesh=mesh) Per-parameter DTensor (Dim-0 sharded) Copy-free AllGather + ReduceScatter, composable with torch.compile & LoRA! 16Ψ / N (7% lower peak VRAM than FSDP1)
2D/3D DeviceMesh (TP + FSDP2) init_device_mesh("cuda", (dp, tp)) 2D DTensor (ColwiseParallel / RowwiseParallel) Intra-node NVLink Tensor Parallel + Inter-node InfiniBand FSDP2 16Ψ / (N_dp × N_tp)

Production FSDP2 (fully_shard) + DeviceMesh + Distributed Checkpoint (dcp) Blueprint

# Launch via CLI: torchrun --standalone --nproc_per_node=8 train_fsdp2.py
import torch
import torch.distributed as dist
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy

def setup_fsdp2_model(model: torch.nn.Module) -> torch.nn.Module:
    # 1. Initialize NCCL process group & 1D/2D DeviceMesh
    dist.init_process_group(backend="nccl")
    local_rank = int(torch.os.environ["LOCAL_RANK"])
    torch.cuda.set_device(local_rank)
    mesh = init_device_mesh("cuda", (dist.get_world_size(),))

    # 2. Configure BF16 compute with FP32 gradient reduction precision
    mp_policy = MixedPrecisionPolicy(
        param_dtype=torch.bfloat16,
        reduce_dtype=torch.float32,
    )

    # 3. Apply FSDP2 bottom-up: shard each Transformer block first, then the root model!
    # Every nn.Parameter becomes a clean DTensor sharded on dim-0 across the DeviceMesh
    for layer in model.layers:
        fully_shard(layer, mesh=mesh, mp_policy=mp_policy)
    fully_shard(model, mesh=mesh, mp_policy=mp_policy)

    return model

08 Frequently Asked PyTorch Engineering & Interview Questions

Production & Architecture
1. What is the exact difference between tensor.view(), tensor.reshape(), and tensor.contiguous()? →

tensor.view(shape) is strictly a zero-copy metadata operation: it returns a new Tensor sharing the exact same UntypedStorage buffer, and raises a RuntimeError if the tensor’s strides are non-contiguous (for example, right after transpose() or permute()). tensor.contiguous() returns self if already contiguous, or allocates a fresh contiguous buffer and copies elements into row-major order. tensor.reshape(shape) returns a zero-copy view whenever current strides permit, and automatically falls back to copying when non-contiguous.

2. How does torch.compile() achieve 1.5x–2.5x speedups in PyTorch 2.x, and what is a "Graph Break"? →

torch.compile() uses TorchDynamo (PEP 523 frame evaluation) to trace Python bytecode into FX graphs, AOTAutograd to capture both forward and backward passes ahead of time, and TorchInductor to generate fused OpenAI Triton GPU kernels. Kernel fusion eliminates HBM memory-bandwidth round-trips by keeping intermediate values in on-chip GPU SRAM. A Graph Break occurs when code executes a data-dependent Python condition (like if tensor.item() > 0:) or calls an untraced C library: TorchDynamo compiles the subgraph before the break, runs the offending line in eager Python, and resumes compiling the subgraph after the break.

3. Why does PyTorch accumulate gradients in param.grad by default, and why use zero_grad(set_to_none=True)? →

In-place gradient addition (param.grad += new_grad) makes Gradient Accumulation across multiple micro-batches (simulating a large effective batch size on limited VRAM) and shared-weight networks trivial. Setting optimizer.zero_grad(set_to_none=True) (the default in PyTorch 2.0+) deallocates or unbinds the gradient reference (param.grad = None) instead of launching a CUDA memset zero-fill kernel, saving HBM write bandwidth and changing the next backward pass from a read-modify-write (+=) into a single write (=).

4. Why is torch.bfloat16 preferred over torch.float16 in Automatic Mixed Precision (AMP) training? →

IEEE float16 allocates 1 sign bit, 5 exponent bits (max value ~65,504), and 10 mantissa bits—meaning small gradients easily underflow to zero and large attention logits overflow to NaN unless wrapped in a dynamic torch.amp.GradScaler. Brain Float 16 (bfloat16) allocates 1 sign bit, 8 exponent bits (the exact same dynamic range as float32, up to ~3.4 × 10³⁸!), and 7 mantissa bits, eliminating loss-scaling instability during LLM pre-training and fine-tuning.

5. What does model.eval() actually change versus torch.inference_mode()? →

They control two completely orthogonal subsystems! model.eval() flips the boolean flag module.training = False on every layer so that Dropout layers stop dropping activations and BatchNorm layers use running population statistics—but it does not disable Autograd graph construction! Conversely, with torch.inference_mode(): disables Autograd graph recording and view/version tracking to save VRAM and speed up execution, without altering Dropout or BatchNorm behavior. During evaluation/inference, you must always use both: model.eval() AND with torch.inference_mode():.

6. Why did PyTorch introduce FSDP2 (fully_shard) to replace FSDP1? →

FSDP1 concatenated multiple parameters in a module into a single monolithic 1D FlatParameter tensor, which complicated LoRA adapter freezing, per-parameter quantization (NF4/FP8), state_dict checkpointing, and torch.compile tracing. FSDP2 (fully_shard) represents each parameter cleanly as an independent DTensor sharded along dimension 0 across a DeviceMesh, using copy-free communication streams that reduce peak GPU memory by ~7% and compose seamlessly with torch.compile and Tensor Parallelism.

Companion Deep Learning Guide

TensorFlow 2.x & Keras 3 Masterclass

Compare PyTorch with TensorFlow 2.x & Keras 3: @tf.function AutoGraph tracing, OpenXLA, tf.GradientTape, C++ tf.data pipelines, Cloud TPUs, and TF Serving / LiteRT.

Explore TensorFlow 2.x Guide →
11-Page Multi-Module Course

LLM Engineering Masterclass Bootcamp

Take your PyTorch mastery into frontier LLM engineering: BPE tokenizers, GQA/MLA Transformers, LoRA & 4-bit QLoRA math, DPO/GRPO alignment, HITL gateways, and Top 10 LLM models.

Launch LLM Bootcamp →
11-Page Multi-Module Course

Python Engineering Masterclass Bootcamp

Master CPython internals beneath PyTorch: PyObject & pymalloc memory arenas, descriptors, metaclasses, all 20 Python data structures, and the Top 100 Coding Interview IDE.

Launch Python Bootcamp →