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.

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.

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 15, 2026