Skip to main content

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.whl
  • torchvision-0.19.1+cu124-cp312-cp312-win_amd64.whl
  • torchaudio-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

Use torch.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.
The schedule skips one step, warms up the profiler for one, then records three. Adjust it to reach a representative phase of a real workload; profiler warmup does not guarantee that compilation and model startup have finished. The toy inputs already reside on the device, so this example does not measure input loading or host-to-device copies. In a real loop, include those stages in labeled ranges too. Give each distributed rank a distinct trace filename. Tracing, shape recording, and optional memory profiling add overhead. Use traces to locate the bottleneck, then measure throughput separately with profiling disabled. CUDA execution is asynchronous: for wall-clock measurements, synchronize the relevant device before starting and before stopping the timer, rather than forcing synchronization inside every iteration. Do not add nested CPU totals and overlapping GPU durations and call the result wall-clock time.

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. Resetting position_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.
Percy Liang’s closing observation is the strategic point: the KV cache is a structural consequence of the Transformer’s design. An architecture built for inference from the start — state-space models, linear attention, non-autoregressive generation — is where the largest remaining gains may be, not in further tuning of the current recipe.

Data loading

Dataset and DataLoader

Image augmentation

Saving and loading models

Jupyter Notebook setup

Create a dedicated PyTorch kernel:
Reference: https://blog.csdn.net/ccaoshangfei/article/details/126521809

Useful tips

Set the random seed

Show model structure

Freeze part of the model

References

Learning resources

Last modified on October 18, 2026