PyTorch
PyTorch is an open-source deep learning framework developed by Facebook AI Research and widely used in both academic research and industry.Installation
Automatic installation
Choose the right command from the official website: https://pytorch.org/get-started/locally/Manual GPU installation
Download page: https://download.pytorch.org/whl/torch/ You need to download three packages, making sure the Python and CUDA versions match:torch-2.4.1+cu124-cp312-cp312-win_amd64.whltorchvision-0.19.1+cu124-cp312-cp312-win_amd64.whltorchaudio-2.4.1+cu124-cp312-cp312-win_amd64.whl
Verify the installation
Basic concepts
Tensors
Automatic differentiation
Building neural networks
Simple model
Convolutional neural network
Training a model
Profile training before optimizing it
A high GPU utilization number does not prove efficient training. NVIDIA’s GPU utilization metric measures the fraction of the sampling interval during which a kernel is executing, not the fraction of peak arithmetic throughput achieved. Databricks reported roughly 6× shorter training time in one Qwen fine-tuning workload despite an initial 98% average utilization. Treat that as a case study, not an expected speedup for your model.Choose data by downstream results, not proxy metrics
NVIDIA’s open midtraining work on Nemotron reports a useful evaluation lesson: base-model proxy metrics did not correlate reliably with post-training results. Their recipe trains between pretraining and SFT at 256K context on hundreds of billions of tokens of natural software-engineering data — packed repositories, pull requests, commit histories, build logs — plus a small share of agentic traces. After an identical full SFT, SWE-bench Verified rose from 60.7 to 64.5 on the smaller model with 500B midtraining tokens, and 72.9 to 74.3 on the larger one with 280B. Those are the authors’ published numbers on those benchmarks, which do not replace evaluation on your own traffic. The transferable method is how they chose data: score each candidate choice with short fixed SFT runs against the target task instead of trusting an upstream proxy. When changing pretraining or midtraining mixtures for an agentic workload, plan for a downstream evaluation budget — a proxy that looks better in isolation can lose after post-training.Capture a short CPU/GPU trace
Usetorch.profiler to inspect operator counts, CPU dispatch, device execution, and gaps between kernels. This small, standalone example needs an installed PyTorch build, uses CUDA when available, and otherwise records CPU activity. It downloads no model or data and writes one trace to the current directory.
Match the change to the bottleneck
Modal’s GPU glossary separates compute, memory movement, and overhead. Use these as hypotheses, then verify them in a timeline or device profiler:
In Databricks’ case, existing
flash-linear-attention and causal-conv1d kernels removed many small operations; reduced padding provided a further gain. That does not mean these packages help every model, or that compilation and CUDA Graphs are generally unsuitable for distributed training.
Before adopting a fast path, check model/backend support, GPU architecture, PyTorch/CUDA compatibility, and both forward and backward support. Pin the working environment and confirm the intended kernel actually appears in the trace: a successful package install does not prove it is being used. Recheck loss and gradients against the reference path within appropriate numerical tolerances.
Pack sequences without changing the task
Sequence packing reduces padding, but simply concatenating examples can change training semantics. Resettingposition_ids alone is not a universal isolation mechanism. The model and attention backend must consume compatible boundary metadata or masks; hybrid recurrent layers also need their state isolated at example boundaries.
The pinned Databricks implementation uses reset position_ids, cumulative sequence lengths for full attention, segment IDs for gated-delta layers, and loss masking so shifted targets do not cross example boundaries. It also masks prompt tokens for response-only SFT. These are backend-specific inputs, not a recipe to copy unchanged into an arbitrary model.
Test packed versus unpacked examples, including boundaries and truncated sequences, before measuring speed. Report non-padding tokens/s, padding fraction, effective batch size, sequence-length distribution, and validation quality. If packing changes tokens per optimizer step, account for the altered batch/optimization schedule. Compare equivalent training work, separating cold-start/compilation time from steady-state throughput.
Fine-tuning is not the default
Adapter-based fine-tuning (LoRA and similar) shrinks the trainable parameter count and optimizer memory, which is why it is often the right first attempt on a consumer GPU. It does not automatically reduce activation memory, KV-cache pressure at inference, or total training time — those depend on sequence length, batch size, and how much of the model you still update. Measure before assuming it makes a workload fit.Why inference is bandwidth-bound
Training time is only half of the performance story. For an interactive agent, decode latency often matters more, and it is governed by memory traffic rather than floating-point throughput. An autoregressive model generates one token at a time. At that point the batch is tiny relative to the weights, so each step must read essentially all parameters — and the accumulated KV cache — through memory bandwidth. Stanford CS336’s lecture 10 makes the argument arithmetic: compute arithmetic intensity (FLOPs per byte moved), compare it with the accelerator’s ratio of peak FLOP/s to memory bandwidth, and note that a low-intensity operation is memory-bound regardless of how fast the ALUs are. That single framing explains most inference optimizations:
Two practical consequences follow from the latency/throughput trade-off:
- Batch size is a policy choice, not a default. Larger batches amortize parameter reads — better tokens/s, worse latency for an individual user. Choose from your product’s requirement, not the benchmark.
- Capacity planning is a memory calculation. Parameter bytes plus KV cache for the maximum concurrent sequences must fit, or the throughput numbers are fiction. Use smaller batches during prefill for faster first token, and reserve larger batches for generation.
Data loading
Dataset and DataLoader
Image augmentation
Saving and loading models
Jupyter Notebook setup
Create a dedicated PyTorch kernel:Useful tips
Set the random seed
Show model structure
Freeze part of the model
References
- meng shao: CS336 lecture 10, Inference — Folo intake, October 18, 2026
- Stanford CS336: Language Modeling from Scratch — course site; lecture 10 covers inference performance
- CS336 lecture 10 (executable lecture) — arithmetic intensity, KV cache, batching, PagedAttention
- PagedAttention (arXiv 2309.06180) — vLLM’s KV-cache paging and prefix sharing
- elvis: NVIDIA midtraining recipe — Folo intake, October 17, 2026
- NVIDIA: Priming Base Models for Agentic Post-Training (arXiv 2610.22019) — midtraining stage and short-fixed-SFT evaluation protocol
- meng shao: Qwen training optimization case — Folo intake, October 15, 2026
- Databricks: Reducing Qwen training time by 6x on AI Runtime — profiling, fused kernels, and padding reduction in one workload
- Databricks: Pinned training implementation — packing metadata and loss boundaries
- PyTorch: Profiler recipe — activities, scheduled traces, and overhead
- NVIDIA: nvidia-smi documentation — meaning of utilization metrics
- meng shao: Modal GPU glossary recommendation — Folo intake, October 15, 2026; the glossary, not the financing news, is the reusable resource
- Modal: GPU glossary — performance bottleneck — compute, memory, and overhead
Learning resources
- Official docs: https://pytorch.org/docs/
- Official tutorials: https://pytorch.org/tutorials/
- Chinese docs: https://pytorch-cn.readthedocs.io/
- GitHub: https://github.com/pytorch/pytorch
