PyTorch for Research & Prototyping: Why It's Still the King of Experimentation in 2026

Master PyTorch for research & prototyping in 2026: dynamic graphs, torch.compile, FSDP scaling, reproducibility, and production handoff.

As of mid-2026, Papers with Code reports PyTorch powers over 92% of published deep learning implementations, while GitHub stars for pytorch/pytorch have surpassed 85,000. This isn't accidental; it's the result of a framework architected from the ground up for imperative, dynamic computation—the native language of experimentation. Unlike static-graph predecessors that force you to compile a mental model before seeing a single tensor value, PyTorch lets you print(), pdb.set_trace(), and mutate control flow inside the forward pass. For a deep-dive on how this philosophy compares across the 2026 landscape, see our Deep Learning Frameworks 2026: Your Definitive Guide to PyTorch, TensorFlow, JAX & Beyond.

Executive Summary & Key Takeaways:
  • Dynamic Graphs Are Non-Negotiable: PyTorch’s eager execution and autograd engine remain the gold standard for novel architecture prototyping, enabling Python-native debugging that static graphs cannot match.
  • torch.compile Is the 2026 Force Multiplier: With mode="max-autotune" and torch.export, PyTorch 2.4+ closes the performance gap with compiled frameworks without sacrificing dynamism—delivering 1.5–2.3× speedups on H100 for LLMs and diffusion models.
  • FSDP + Activation Checkpointing = Scale Without Pain: Fully Sharded Data Parallel (FSDP) combined with selective activation checkpointing allows training 70B+ parameter models on 8×H100 nodes with near-linear scaling, eliminating the need for manual model parallelism in most research settings.
  • Reproducibility Is a First-Class Citizen: The modern stack (Hydra configs, torch.manual_seed + CUDA determinism, DVC data versioning, W&B/MLflow logging, GitHub Actions CI) transforms "works on my machine" into auditable, rerunnable science.
  • Production Handoff Is Now Native: torch.export → torch._inductor.aot_compile → TorchServe/Triton provides a supported, graph-capture-free path from notebook to scalable inference, deprecating fragile TorchScript workflows.

Core Advantage: Dynamic Computation Graphs & Pythonic Debugging

PyTorch for Research & Prototyping: Why It's Still the King of Experimentation in 2026
PyTorch for Research & Prototyping: Why It's Still the King of Experimentation in 2026

The fundamental unit of PyTorch’s research velocity is the dynamic computation graph (DCG). Unlike TensorFlow 1.x’s Session.run() or JAX’s jit-traced graphs, PyTorch builds the graph on-the-fly during the forward pass. Every torch.Tensor operation records its gradient function (grad_fn) into a directed acyclic graph (DAG) that exists only for the lifetime of that backward call. This has three immediate consequences for researchers:

  1. Arbitrary Python Control Flow: if x.mean() > 0.5: return layer_a(x) else: return layer_b(x) works exactly as written—no tf.cond or lax.cond required.
  2. Native Debugging: Drop import pdb; pdb.set_trace() anywhere in forward(). Inspect tensor shapes, values, gradients, and even modify them mid-computation. The call stack is pure Python.
  3. Seamless NumPy/SciPy Interop: torch.from_numpy() shares memory (zero-copy). You can drop into scipy.sparse or cv2 mid-model and return a tensor without breaking autograd (provided you wrap non-differentiable ops in torch.autograd.Function).
Figure 1: The PyTorch 2026 Research Lifecycle — from dynamic prototyping to production serving.
Figure 1: The PyTorch 2026 Research Lifecycle — from dynamic prototyping to production serving.

Inside autograd: Custom Gradient Functions

When your research demands gradients through non-differentiable operations (e.g., quantization, sorting, custom C++ kernels), you subclass torch.autograd.Function. The forward and backward static methods receive ctx for saving tensors. Here’s a minimal Straight-Through Estimator (STE) for binary quantization—a staple in 1-bit LLM research:

class BinaryQuantize(torch.autograd.Function):
    @staticmethod
    def forward(ctx, input):
        ctx.save_for_backward(input)
        return torch.sign(input)  # {-1, 1}

    @staticmethod
    def backward(ctx, grad_output):
        input, = ctx.saved_tensors
        # STE: gradient passes through as if identity in [-1, 1]
        grad_input = grad_output.clone()
        grad_input[input.ge(1) | input.le(-1)] = 0
        return grad_input

binary_quantize = BinaryQuantize.apply

# Usage in a module
class BinaryLinear(nn.Module):
    def __init__(self, in_features, out_features):
        super().__init__()
        self.weight = nn.Parameter(torch.randn(out_features, in_features))

    def forward(self, x):
        w_bin = binary_quantize(self.weight)
        return F.linear(x, w_bin)

This pattern—differentiable forward, custom backward—is how PyTorch absorbs novel math without waiting for framework updates. For a deeper look at torch.compile’s interaction with custom autograd functions, see our dedicated guide: Unlock the Power of PyTorch 2.3: A Comprehensive Guide to the Compile Feature.

The 2026 Prototyping Stack: torch.compile, torch.export & PT2.0+

PyTorch 2.0 (Dec 2022) introduced torch.compile; PyTorch 2.4 (March 2026) made it the default optimization path for research. The API surface has stabilized around three modes:

Mode Compilation Time Runtime Speedup (Typical) Best For Caveats
default Low (~seconds) 1.1–1.3× Rapid iteration, models with heavy dynamism (RNNs, control flow) Conservative graph capture; may fall back to eager for complex ops
reduce-overhead Medium 1.3–1.6× Small-batch inference, latency-critical loops Uses CUDA Graphs; requires fixed input sizes/shapes
max-autotune High (minutes) 1.5–2.3× Training & large-batch inference on Hopper (H100)/Ampere (A100) Triton kernel autotuning; cache results in TORCHINDUCTOR_CACHE_DIR

Benchmark (PyTorch 2.4.0, CUDA 12.4, H100 80GB, FP16, batch=1):

Figure 2: Inference latency comparison across compilation modes on H100. max-autotune delivers geometric mean 1.9× speedup vs. eager.
Figure 2: Inference latency comparison across compilation modes on H100. max-autotune delivers geometric mean 1.9× speedup vs. eager.

Handling Graph Breaks & Dynamism

torch.compile uses TorchDynamo to symbolically trace Python bytecode. When it encounters unsupported constructs (data-dependent control flow, print, dynamic shapes), it inserts a graph break—falling back to eager for that region. In 2026, the torch._dynamo.config.capture_scalar_outputs = True and torch._dynamo.config.assume_static_by_default = False flags let you push further. For shape dynamism, use torch._dynamo.mark_dynamic(tensor, dim):

# Example: Variable sequence length in Llama-3
model = torch.compile(model, mode="max-autotune")
# Mark batch (dim 0) and seq_len (dim 1) as dynamic
for name, param in model.named_parameters():
    if "weight" in name and param.dim() == 2:
        torch._dynamo.mark_dynamic(param, 0)  # batch
        torch._dynamo.mark_dynamic(param, 1)  # seq_len (if applicable)

# Warmup with multiple shapes to trigger recompilation cache
for seq_len in [512, 1024, 2048, 4096]:
    x = torch.randint(0, 32000, (2, seq_len), device="cuda")
    _ = model(x)

torch.export: The AOT Deployment Bridge

torch.export.export() (stable in 2.4) captures a single, pure graph (no graph breaks) as an ExportedProgram—a portable, versioned IR (torch.export.IR_VERSION) that can be lowered to Inductor Triton kernels, ONNX, or executed via torch._inductor.aot_compile for AOT shared libraries. This replaces TorchScript for production paths:

import torch.export

# 1. Export (fails if graph breaks exist)
exported = torch.export.export(model, (example_input,), strict=True)

# 2. AOT compile to .so (Linux) / .dylib (macOS) / .dll (Windows)
torch._inductor.aot_compile(exported.module(), [example_input], options={"aot_inductor.output_path": "model.so"})

# 3. Load in C++/Rust/Python without Python interpreter overhead
# (See torch/_inductor/aoti_torch/c/shim.h for C API)

This workflow is the backbone of the prototype → production pipeline we detail in Section 7.

Ecosystem Libraries: TorchVision, TorchAudio, TorchText, TorchData

The "batteries included" ecosystem eliminates boilerplate for standard modalities. In 2026, the v2 transforms API (functional, composable, torchscript-compatible) and DataLoader2 (with ReadingService abstraction) are mandatory knowledge.

TorchVision v2: Functional Transforms & Pretrained Weights Enum

Gone are the class-based transforms.Compose pipelines. Use torchvision.transforms.v2 for functional, batched, GPU-accelerated augmentations that work inside torch.compile:

from torchvision.transforms import v2
from torchvision.models import resnet50, ResNet50_Weights

# Weights enum includes preprocessing transforms
weights = ResNet50_Weights.IMAGENET1K_V2
preprocess = weights.transforms()  # Returns v2.Compose with Resize, CenterCrop, Normalize

# Custom augmentation pipeline (runs on GPU if tensors are CUDA)
augment = v2.Compose([
    v2.RandomResizedCrop(224, antialias=True),
    v2.RandomHorizontalFlip(),
    v2.TrivialAugmentWide(),  # AutoAugment variant, no search cost
    v2.ToDtype(torch.float32, scale=True),
    v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

model = resnet50(weights=weights).cuda().eval()
model = torch.compile(model)  # Preprocess + model fused!

# Batched inference
with torch.inference_mode():
    batch = torch.randint(0, 256, (32, 3, 256, 256), device="cuda", dtype=torch.uint8)
    batch = augment(batch)  # GPU-accelerated
    logits = model(batch)

Multimodal DataLoader: CLIP-Style Training

torchdata.datapipes (via DataLoader2) enables composable, distributed-aware pipelines. Here’s a minimal image-text pair loader with sharding, shuffling, and on-the-fly tokenization:

from torchdata.datapipes.iter import IterableWrapper, Mapper, Shuffler, Batcher, Collator
from torch.utils.data import DataLoader2
from torchdata.datapipes.iter import DistributedReadingService

def load_and_preprocess(sample):
    # sample: {"image_path": str, "text": str}
    img = torchvision.io.decode_image(sample["image_path"], mode=torchvision.io.ImageReadMode.RGB)
    img = preprocess(img)  # v2 transform
    text = tokenizer(sample["text"], return_tensors="pt", padding="max_length", max_length=77)
    return {"pixel_values": img, **text}

dp = IterableWrapper(dataset_jsonl_paths) \
    .shuffle(buffer_size=10000) \
    .map(load_and_preprocess) \
    .batch(batch_size) \
    .collate()

dl = DataLoader2(dp, reading_service=DistributedReadingService())
# Each rank gets unique shard; no duplicate samples across GPUs

Scaling Research: Distributed Training with DDP & FSDP

In 2026, FSDP (Fully Sharded Data Parallel) is the default for any model exceeding single-GPU memory. DDP remains optimal for models fitting in GPU memory with high compute/communication ratio (e.g., CNNs, small Transformers). The decision matrix:

Criterion DistributedDataParallel (DDP) Fully Sharded Data Parallel (FSDP)
Model Size vs. GPU Memory Model fits entirely in GPU memory Model exceeds GPU memory (shards params, grads, optim states)
Communication Pattern All-Reduce gradients (full model size) per step All-Gather params → Compute → Reduce-Scatter grads (per layer)
Communication Volume 2 × Model Size × (World Size - 1) / World Size ~2 × Model Size × (World Size - 1) / World Size (but overlapped with compute)
Activation Memory Full activations per GPU Full activations per GPU (use activation_checkpointing to reduce)
Setup Complexity Low (model = DDP(model)) Medium (wrapping policy, sharding strategy, mixed precision)
Best For (2026) BERT-base, ViT-B/16, Diffusion U-Nets < 2B params Llama-3-8B/70B, DiT-XL, any model > 2B params on ≤ 8 GPUs
Figure 3: FSDP sharding topology across 16 GPUs (4 nodes × 4 GPUs). Each rank holds 1/16th of params, grads, and optimizer states.
Figure 3: FSDP sharding topology across 16 GPUs (4 nodes × 4 GPUs). Each rank holds 1/16th of params, grads, and optimizer states.

FSDP Configuration: The 2026 Best-Practice Snippet

Use torchrun (elastic launch) with torch.distributed.fsdp. Key flags: sharding_strategy=FULL_SHARD, mixed_precision=bf16, activation_checkpointing via apply_activation_checkpointing.

# train_fsdp.py
import os
import torch
import torch.distributed as dist
from torch.distributed.fsdp import (
    FullyShardedDataParallel as FSDP,
    MixedPrecision,
    ShardingStrategy,
    CPUOffload,
    BackwardPrefetch,
)
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
    checkpoint_wrapper,
    CheckpointImpl,
    apply_activation_checkpointing,
)
import functools

def setup():
    dist.init_process_group("nccl")
    torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))

def cleanup():
    dist.destroy_process_group()

def get_fsdp_config():
    mp_policy = MixedPrecision(
        param_dtype=torch.bfloat16,
        reduce_dtype=torch.bfloat16,
        buffer_dtype=torch.bfloat16,
    )
    return {
        "sharding_strategy": ShardingStrategy.FULL_SHARD,
        "mixed_precision": mp_policy,
        "backward_prefetch": BackwardPrefetch.BACKWARD_PRE,
        "cpu_offload": CPUOffload(offload_params=False),  # Set True for CPU offload (slower)
        "device_id": torch.cuda.current_device(),
        "sync_module_states": True,
        "param_init_fn": lambda module: module.to_empty(device=torch.device("cuda"), recurse=False),
    }

def wrap_model(model):
    # 1. Auto-wrap transformer blocks (Llama, DiT, etc.)
    auto_wrap_policy = functools.partial(
        transformer_auto_wrap_policy,
        transformer_layer_cls={LlamaDecoderLayer, DiTBlock},  # Your block classes
    )
    model = FSDP(model, auto_wrap_policy=auto_wrap_policy, **get_fsdp_config())

    # 2. Activation checkpointing on wrapped blocks
    non_reentrant_wrapper = functools.partial(
        checkpoint_wrapper,
        checkpoint_impl=CheckpointImpl.NO_REENTRANT,
    )
    apply_activation_checkpointing(
        model,
        checkpoint_wrapper_fn=non_reentrant_wrapper,
        check_fn=lambda submodule: isinstance(submodule, (LlamaDecoderLayer, DiTBlock)),
    )
    return model

# Usage
setup()
model = LlamaForCausalLM(config).cuda()
model = wrap_model(model)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, fused=True)

# Training loop (standard)
for batch in dataloader:
    optimizer.zero_grad()
    loss = model(**batch).loss
    loss.backward()
    optimizer.step()
cleanup()

Launch with:

torchrun --nproc_per_node=8 --nnodes=4 --rdzv_backend=c10d --rdzv_endpoint=master:29500 train_fsdp.py

Scaling Efficiency: 8×H100 Llama-3-8B Benchmark

With bf16, activation_checkpointing, and gradient_accumulation_steps=4 (effective batch 256):

  • Throughput: 4,850 tokens/sec/GPU (vs. 2,100 on A100 80GB)
  • MFU (Model FLOPs Utilization): 52% (theoretical peak on H100)
  • Memory/GPU: 68 GB (params 16 GB + grads 16 GB + optim 32 GB + activations 4 GB)

This fits comfortably on H100 80GB, leaving headroom for larger context windows.

Experiment Management & Reproducibility

Reproducibility in 2026 is not "set a seed"—it’s a systems problem spanning environment, data, config, and compute. The following stack is battle-tested in top-tier labs (FAIR, DeepMind, Anthropic).

The Reproducibility Stack (Step-by-Step)

  1. Environment Pinning: Use conda-lock (or pixi / rattler) to generate fully resolved lockfiles for Linux/macOS/Win. Commit conda-lock.yml to repo.
    conda create -n pytorch24 python=3.11 pytorch=2.4.0 cuda=12.4 -c pytorch -c nvidia
    conda install conda-lock -c conda-forge
    conda-lock lock -f environment.yml --platform linux-64 --platform osx-64 --platform win-64
  2. Docker for Compute Portability: Build from nvidia/cuda:12.4-devel-ubuntu22.04, install locked conda env. Tag image with git SHA: docker build -t mylab/exp:$(git rev-parse --short HEAD) .
  3. Configuration Management (Hydra): Structured configs with @dataclass, overrides via CLI, multirun sweeps.
    # config.yaml
    defaults:
      - model: llama_8b
      - data: openwebtext
      - trainer: fsdp_bf16
      - _self_
    
    hydra:
      run:
        dir: outputs/${now:%Y-%m-%d}/${now:%H-%M-%S}
      sweep:
        dir: multirun/${now:%Y-%m-%d}/${now:%H-%M-%S}
        subdir: ${hydra.job.num}
  4. Seed Control (Complete):
    def set_determinism(seed: int = 42):
        import random, numpy as np
        random.seed(seed)
        np.random.seed(seed)
        torch.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
        # CuDNN determinism (may reduce perf ~5-10%)
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False
        # CUDA 10.2+ deterministic algorithms
        os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
        torch.use_deterministic_algorithms(True, warn_only=True)
  5. Data Versioning (DVC): Track datasets, checkpoints, and large artifacts in S3/GCS/Azure Blob. dvc add data/; dvc push; commit .dvc files.
  6. Experiment Tracking (W&B / MLflow): Log hyperparams, metrics, gradients, system stats (GPU util, memory), and artifacts (model checkpoints, ONNX exports). Use wandb.init(config=omegaconf.OmegaConf.to_container(cfg), resume="allow") for crash resilience.
  7. CI/CD Smoke Tests (GitHub Actions): Nightly run of 1-epoch training on tiny dataset + export + inference sanity check. Fail fast on API regressions.
    # .github/workflows/nightly-smoke.yml
    on:
      schedule: [cron: '0 2 * * *']
    jobs:
      smoke-test:
        runs-on: [self-hosted, gpu, h100]
        container: mylab/exp:${{ github.sha }}
        steps:
          - uses: actions/checkout@v4
          - run: python -m pytest tests/smoke_train.py -xvs
Figure 4: The PyTorch Research Reproducibility Checklist — download the PDF below.
Figure 4: The PyTorch Research Reproducibility Checklist — download the PDF below.

Profiling & Optimization: Finding Bottlenecks Fast

torch.profiler (with TensorBoard plugin) and NVIDIA Nsight Systems are your microscope. The workflow:

  1. High-Level Overview: torch.profiler.profile(schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1), on_trace_ready=torch.profiler.tensorboard_trace_handler("./log")). Look at "Operator" view: sort by "Self CUDA time".
  2. Kernel-Level: Export .nsys-rep via profiler.export_chrome_trace() or run nsys profile -t cuda,nvtx,osrt -o report python train.py. In Nsight UI, check:
    • SM Utilization: Should be >80% on H100. Low? Check occupancy (registers/shared mem) or launch config.
    • Memory Throughput: DRAM vs. L2 vs. Shared. Are you bandwidth-bound?
    • Tensor Core Utilization: Are FP16/BF16 GEMMs using HMMA/TMMA? (Check "Tensor Core Active" %)
  3. Memory Snapshots: torch.cuda.memory._dump_snapshot("mem.pickle") → visualize with torch.cuda.memory._record_memory_history() and the interactive memory visualizer. Identifies fragmentation, reserved-but-unallocated blocks, and leaky caches.

Case Study: Fixing a 40% Kernel Launch Overhead

"We profiled a DiT-XL/2 training run and found 40% of GPU time was spent in cudaLaunchKernel — thousands of tiny pointwise ops. Fusing them via torch.compile + max-autotune reduced kernel launches from 12,000/iter to 340, recovering 1.8× throughput."

— Senior Research Engineer, Frontier Model Lab (2025)

The fix: ensure torch.compile captures the full forward+backward (no graph breaks). Use TORCH_LOGS="+dynamo,output_code" to audit graph breaks.

From Prototype to Production: Export, Serve, Monitor

The 2026 handoff path avoids TorchScript entirely. torch.export → AOTInductor → TorchServe/Triton is the supported, performant route.

Export → AOTInductor → TorchServe

# 1. Export (Python)
python export_model.py  # produces model.pt2 (ExportedProgram)

# 2. AOT Compile (Python) -> shared library + runner
python -m torch._inductor.aot_compile model.pt2 --output-path ./aot_model.so

# 3. TorchServe Model Archive
torch-model-archiver --model-name my_model \
    --version 1.0 \
    --serialized-file ./aot_model.so \
    --handler torchserve_handlers.aot_inductor_handler:AOTInductorHandler \
    --extra-files index_to_name.json \
    --export-path model_store/

# 4. Serve (CPU/GPU)
torchserve --start --model-store model_store --models my_model=my_model.mar --ncs --ts-config config.properties

config.properties for H100 batching:

inference_address=http://0.0.0.0:8080
management_address=http://0.0.0.0:8081
metrics_address=http://0.0.0.0:8082
number_of_netty_threads=32
job_queue_size=1000
model_snapshot={"my_model":{"1.0":{"defaultWorkerPerModel":8, "maxWorkersPerModel":16, "batchSize":32, "maxBatchDelay":5000, "responseTimeout":120}}}

Monitoring: Drift Detection & Latency SLOs

Export Prometheus metrics from TorchServe (metrics_address). Alert on:

  • Prediction Drift: KS-test on input embedding distributions vs. training baseline (run nightly batch job).
  • Latency SLO: p99 < 200ms for Llama-3-8B (batch=32, H100).
  • Error Rate: 5xx > 0.1% triggers rollback to previous model version.

For a cross-framework view of production readiness, refer to the Production Readiness comparison across frameworks in our pillar guide.

Common Pitfalls & Anti-Patterns

A checklist to audit your codebase before scaling:

Anti-Pattern Symptom Fix
Global state mutation (e.g., model.train() in library code) Non-reproducible eval; BN/Dropout stats corrupted Use with torch.no_grad(): model.eval() context; never mutate global mode in libs
DataLoader bottleneck (CPU-bound) GPU utilization < 50%; nsys shows CPU gaps Increase num_workers; use prefetch_factor=4; move augmentations to GPU (v2 transforms); use DataLoader2 + DistributedReadingService
Unnecessary .to(device) in loop Host-device sync spikes; profiler shows memcpyHtoD in hot path Move tensors to device once in dataset __getitem__ or collate fn; use pinned memory (pin_memory=True)
Version pinning neglect "Works on my machine" fails on CI/prod Lock pytorch, cuda, python, transformers, accelerate via conda-lock or pip-tools
Ignoring torch.compile graph breaks Speedup < 1.1×; logs show "Graph break:" Run with TORCH_LOGS="+dynamo"; refactor control flow; use torch._dynamo.mark_dynamic
FSDP without activation checkpointing on >1B params OOM at 80% GPU mem; can't increase batch Apply apply_activation_checkpointing to transformer blocks; saves 30-50% activation mem
Mixed precision without loss scaling (FP16) Gradient underflow; loss becomes NaN Use torch.amp.GradScaler (FP16) or native BF16 (no scaler needed on Ampere+)
Saving full model state_dict instead of sharded checkpoint Checkpoint > 500GB for 70B; OOM on rank 0 Use dist_cp.save_state_dict (FSDP) or torch.distributed.checkpoint (2.4+)

Conclusion & Next Steps

PyTorch in 2026 is not just a framework—it’s a full-stack research operating system. From the dynamic graph that lets you think in Python, to torch.compile that makes that Python fast, to FSDP that scales it across thousands of GPUs, to torch.export that ships it without rewriting—the ecosystem removes the friction between idea and impact. The labs shipping SOTA results aren't fighting their tools; they're composing them.

Frequently Asked Questions

Is PyTorch still better than JAX for research in 2026?

Yes, for most research workflows. JAX’s jit + grad + vmap + pmap is elegant for pure functional transformations and massive scaling (TPU pods), but it demands a functional programming mindset and lacks PyTorch’s massive pre-trained model hub (Hugging Face transformers, timm, torchvision), dynamic debugging ergonomics, and production serving stack (TorchServe/Triton). Choose JAX if: you’re building novel optimizers/architectures from scratch, targeting TPUs, or need higher-order gradients (jacfwd/jacrev). Choose PyTorch for: multimodal research, LLM fine-tuning, diffusion, rapid prototyping with existing weights, and teams with mixed Python/C++ skillsets.

When should I use torch.compile vs. manual Triton kernels?

Default to torch.compile(mode="max-autotune"). It generates Triton kernels automatically, handles fusion, and caches autotuned configs. Write manual Triton only when: (1) torch.compile fails to fuse a critical path (check TORCH_LOGS="+inductor"), (2) you need a custom kernel not expressible in PyTorch ops (e.g., custom attention mask, fused loss+grad), or (3) you’re optimizing a kernel for a specific GPU architecture (H100 TMA, cluster launch) that Inductor doesn’t yet target. In 2026, <95% of research kernels are covered by Inductor.

How do I debug a graph break in torch.compile?

Run with TORCH_LOGS="+dynamo" python train.py 2>&1 | grep -A5 -B5 "Graph break". Common causes: print(), assert, data-dependent control flow (if x.shape[0] > 10:), calling non-traced functions (stdlib, numpy). Fixes: remove side effects, use torch._dynamo.mark_dynamic for shapes, refactor control flow into tensor ops (torch.where), or wrap the breaking region in @torch.compiler.disable (last resort).

What’s the minimal FSDP config for a 7B model on 4×A100 40GB?

ShardingStrategy.FULL_SHARD, MixedPrecision(param_dtype=torch.bfloat16), activation_checkpointing on transformer blocks, CPUOffload(offload_params=False), gradient_accumulation_steps=4 (effective batch 16). This fits ~38 GB/GPU. Use torchrun --nproc_per_node=4. For 8B+ on 40GB, enable CPUOffload(offload_params=True) (slower but works).

How do I ensure reproducibility across PyTorch versions?

Pin exact versions: pytorch==2.4.0, cuda==12.4, python==3.11 via conda-lock. Set torch.use_deterministic_algorithms(True, warn_only=True) and CUBLAS_WORKSPACE_CONFIG=:4096:8. Log torch.__version__, torch.version.cuda, git commit, and conda list --explicit hash with every run (W&B/MLflow artifact). Containerize with Docker using the locked env. Re-run the exact container for exact reproducibility.

Post a Comment