Skip to main content

Faster training

Author

Marie-Hélène Burle

The training loop of the previous section is complete, but it runs exactly as written, one Python-level operation at a time.

This section shows you how to benchmark your code and to use the profiler to assess where the time is spent, as well as how to determine whether a model fits on a GPU. Then it covers two key levers that make a working loop faster: just-in-time compilation and reduced-precision matrix math.

Measurements

Benchmarking properly and profiling are key before attempting any optimization.

Benchmarking

A benchmark is a timing solid enough to compare two versions of a code. Timing code means reading a clock twice. In practice however, four things make naive timings meaningless:

  • The first pass is not like the others. It pays one-time costs: loading the CUDA libraries, creating the context on the GPU, and choosing the algorithms. Our training run took 20.4 s for its first epoch and about 12 s for each of the following ones. Warm the code up before you start the clock.
  • Accelerator operations are asynchronous. When PyTorch runs an operation on a GPU, it queues the work and returns immediately. A loop that looks finished on the CPU may have most of its work still waiting in the queue of the GPU. torch.accelerator.synchronize() blocks until the queue is empty: call it before you read the clock.
  • Timings fluctuate. Other processes, the temperature, and the state of the caches all add noise. Repeat each measurement several times, compare medians, and look at the spread: a 2% difference between two versions means nothing if each of them varies by 5% from one run to the next.
  • You time what the code does, not what you would like to measure. A training epoch loads data and computes. To speed up the model, time the training step alone, on a batch already sitting on the device. To speed up the data pipeline, time whole epochs.

Let’s write a small benchmark for our model. It times bare training steps on fake data held on the device, so that nothing but the model is measured. Create a file called benchmark.py with a text editor such as nano:

nano benchmark.py

And paste in it the following:

import statistics  # to take the median of the timed repeats
import time  # to time steps

import torch
from torch import nn


class Net(nn.Module):
    """A small CNN for 64x64 images and 10 classes."""

    def __init__(self):
        super().__init__()
        self.layers = nn.Sequential(
            # 3 conv blocks: each doubles the channels; the first two halve the image
            nn.Conv2d(3, 32, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 64 -> 32
            nn.Conv2d(32, 64, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 32 -> 16
            nn.Conv2d(64, 128, 3, padding=1),
            nn.ReLU(),  # 16 -> 16
            nn.AdaptiveAvgPool2d(1),  # one value per channel: 128 features
            nn.Flatten(),
            nn.Linear(128, 10),  # one score per class
        )

    def forward(self, x):
        return self.layers(x)


def main():
    device = (
        torch.accelerator.current_accelerator()
        if torch.accelerator.is_available()
        else torch.device("cpu")
    )
    print(f"Torch version: {torch.__version__}\nDevice: {device}")
    torch.manual_seed(42)

    model = Net().to(device)
    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

    def benchmark(m, batch, steps=50, repeats=5):
        """Median time (in s) of one bare training step of model m on fake batches."""
        # fake data held on the device: the steps are timed alone, without data loading
        x = torch.randn(batch, 3, 64, 64, device=device)
        y = torch.randint(0, 10, (batch,), device=device)
        times = []
        for i in range(repeats + 2):  # the first 2 repeats warm up and are discarded
            torch.accelerator.synchronize()  # queued work must be done before the clock starts
            t0 = time.perf_counter()
            for _ in range(steps):
                optimizer.zero_grad()
                loss = loss_fn(m(x), y)
                loss.backward()
                optimizer.step()
            torch.accelerator.synchronize()  # steps are only queued: wait for the last one
            if i >= 2:
                times.append(time.perf_counter() - t0)
        return statistics.median(times) / steps, times

    for batch in (16, 32, 64, 128, 256, 512):
        per_step, times = benchmark(model, batch)
        print(" ".join(f"{t:.2f}" for t in times), "s for 50 steps")
        print(
            f"batch {batch:4d}: {per_step * 1e3:5.1f} ms/step, {batch / per_step:6.0f} images/s"
        )


if __name__ == "__main__":
    main()
  • benchmark() runs a block of 50 steps 7 times, discards the first 2 blocks (warmup), and returns the median duration of the 5 others divided by 50: the time of one step. It also returns the 5 durations, to show the spread.
  • torch.accelerator.synchronize() is called right before the clock starts and right after it stops.
  • The fake batch has the shape and the types of a real one (batch images of 3 × 64 × 64 pixels and integer labels): the model does the same work whatever the values of the pixels.
  • The optimizer, the loss, and the steps are those of train.py, without the scheduler, the metrics, and mixed precision, which have a negligible effect on timing.
  • The loop over batch sizes is there because a benchmark only serves to compare things. It will answer a question for us: is our batch of 64 making good use of the GPU?

Run it:

srun --mem=10000 --gpus-per-node=1 --cpus-per-task=3 python benchmark.py

This script does not read our data, so it would run just as well on a login node. Do not benchmark there however: the CPUs of login nodes are shared and the timings would not mean anything. Always benchmark inside an allocation, on the hardware you will train on.

Results

This is what I got on the training cluster:

Torch version: 2.14.1
Device: cuda
0.33 0.33 0.33 0.33 0.33 s for 50 steps
batch   16:   6.6 ms/step,   2415 images/s
0.30 0.30 0.32 0.33 0.33 s for 50 steps
batch   32:   6.3 ms/step,   5072 images/s
0.46 0.46 0.46 0.46 0.46 s for 50 steps
batch   64:   9.2 ms/step,   6968 images/s
0.56 0.56 0.56 0.56 0.56 s for 50 steps
batch  128:  11.3 ms/step,  11364 images/s
1.05 1.05 1.05 1.05 1.05 s for 50 steps
batch  256:  21.1 ms/step,  12157 images/s
2.09 2.09 2.09 2.09 2.09 s for 50 steps
batch  512:  41.7 ms/step,  12272 images/s

And on my laptop:

Torch version: 2.13.0+cu130
Device: cuda
0.10 0.11 0.11 0.11 0.11 s for 50 steps
batch   16:   2.1 ms/step,   7449 images/s
0.20 0.20 0.20 0.20 0.20 s for 50 steps
batch   32:   4.0 ms/step,   7995 images/s
0.38 0.38 0.38 0.38 0.38 s for 50 steps
batch   64:   7.7 ms/step,   8337 images/s
0.75 0.75 0.75 0.75 0.75 s for 50 steps
batch  128:  15.0 ms/step,   8560 images/s
1.64 1.64 1.64 1.64 1.64 s for 50 steps
batch  256:  32.8 ms/step,   7813 images/s
3.28 3.27 3.28 3.29 3.29 s for 50 steps
batch  512:  65.7 ms/step,   7794 images/s
  • Most repeats of a measurement agree within 2%: the timings are solid, and a difference of a few percent between two versions would mean something. The shortest measurements (the smallest batches) wander by up to 10%: time blocks long enough to drown this noise.
  • On the training cluster, the steps at batch 16 and at batch 32 take the same time: doubling the batch costs nothing. This time is a fixed cost per step, spent by the CPU launching the kernels one by one while the GPU waits. On my laptop, the floor is lower and the time per step grows from the smallest batch on.
  • From batch 128 on, doubling the batch doubles the time per step on the training cluster: the GPU is now the busy part, and the throughput stops improving at about 12,000 images/s (8,500 images/s on my laptop).
  • Our batch of 64 sits right at the turning point on the training cluster: 9.2 ms per step, of which up to 6.6 ms is overhead. Larger batches are discussed in how to choose the batch size.

Finally, compare these numbers with our epochs: 338 steps of 9.2 ms add up to 3.1 s, yet the training loop takes about 12 s per epoch on the training cluster. The rest of the time, the GPU waits for data (the subject of an earlier section). Keep this in mind when we optimize the training step below.

Your turn:

Without running anything, say which of these changes benchmark.py would show and which ones it would not:

  • more DataLoader workers,
  • a faster GPU,
  • pinned memory,
  • a faster CPU.

Then: which script of this course would you run to measure the effect of the first and third changes?

Profiling

A benchmark tells you how long code takes. The profiler tells you where the time goes: torch.profiler records every operation, for how long it ran, and on which device.

Let’s profile 5 training steps of our model:

nano profiling.py
import os

import torch
from torch import nn
from torch.profiler import ProfilerActivity, profile


class Net(nn.Module):
    """A small CNN for 64x64 images and 10 classes."""

    def __init__(self):
        super().__init__()
        self.layers = nn.Sequential(
            # 3 conv blocks: each doubles the channels; the first two halve the image
            nn.Conv2d(3, 32, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 64 -> 32
            nn.Conv2d(32, 64, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 32 -> 16
            nn.Conv2d(64, 128, 3, padding=1),
            nn.ReLU(),  # 16 -> 16
            nn.AdaptiveAvgPool2d(1),  # one value per channel: 128 features
            nn.Flatten(),
            nn.Linear(128, 10),  # one score per class
        )

    def forward(self, x):
        return self.layers(x)


def main():
    device = (
        torch.accelerator.current_accelerator()
        if torch.accelerator.is_available()
        else torch.device("cpu")
    )
    print(f"Torch version: {torch.__version__}\nDevice: {device}")
    torch.manual_seed(42)

    os.environ["KINETO_LOG_LEVEL"] = "100"  # silence the profiler's own logging

    model = Net().to(device)
    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

    # fake data held on the device: the profile shows the training step alone
    x = torch.randn(64, 3, 64, 64, device=device)
    y = torch.randint(0, 10, (64,), device=device)

    for _ in range(3):  # warmup: the first steps always run extra one-time work
        optimizer.zero_grad()
        loss = loss_fn(model(x), y)
        loss.backward()
        optimizer.step()

    activities = [ProfilerActivity.CPU]
    if device.type == "cuda":
        activities.append(ProfilerActivity.CUDA)

    with profile(activities=activities) as prof:
        for _ in range(5):
            optimizer.zero_grad()
            loss = loss_fn(model(x), y)
            loss.backward()
            optimizer.step()

    sort_by = "self_cpu_time_total" if device.type == "cpu" else "self_cuda_time_total"
    print(prof.key_averages().table(sort_by=sort_by, row_limit=8))
    prof.export_chrome_trace("trace.json")  # then open https://ui.perfetto.dev


if __name__ == "__main__":
    main()
  • activities lists what to record: the CPU always, and CUDA when there is a GPU.
  • Everything that runs inside the with profile(...) block is recorded. The warmup steps that precede it keep the profile free of one-time work.
  • key_averages() aggregates all the calls of each operation. Its table() method returns a text table, sorted here by the time spent in the operation itself on the GPU (self_cuda_time_total), or on the CPU when there is no accelerator.
  • export_chrome_trace() saves all the individual events to a file.

Do not name this script profile.py: a file with this name would hide a module of the Python standard library that PyTorch needs, and the script would crash at import with a confusing error.

Run it:

srun --mem=10000 --gpus-per-node=1 --cpus-per-task=3 python profiling.py

Results

This is what I got on the training cluster:

Torch version: 2.14.1
Device: cuda
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                                                   Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg     Self CUDA   Self CUDA %    CUDA total  CUDA time avg    # of Calls
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                             aten::convolution_backward         6.97%       3.868ms        16.55%       9.184ms     612.235us      26.235ms        57.62%      27.360ms       1.824ms            15
sm80_xmma_wgrad_implicit_gemm_indexed_wo_smem_tf32f3...         0.00%       0.000us         0.00%       0.000us       0.000us      17.894ms        39.30%      17.894ms       3.579ms             5
                 aten::max_pool2d_with_indices_backward         1.05%     582.899us         2.34%       1.297ms     129.655us       5.383ms        11.82%       5.922ms     592.169us            10
void at::native::(anonymous namespace)::max_pool_bac...         0.00%       0.000us         0.00%       0.000us       0.000us       5.383ms        11.82%       5.383ms     538.341us            10
                                aten::cudnn_convolution         3.68%       2.041ms        10.42%       5.781ms     385.430us       4.021ms         8.83%       4.021ms     268.088us            15
void cudnn::engines_precompiled::nchwToNhwcKernel<fl...         0.00%       0.000us         0.00%       0.000us       0.000us       2.580ms         5.67%       2.580ms      86.015us            30
                               aten::threshold_backward         1.02%     564.072us         1.60%     888.127us      59.208us       2.048ms         4.50%       2.048ms     136.530us            15
void at::native::vectorized_elementwise_kernel<4, at...         0.00%       0.000us         0.00%       0.000us       0.000us       2.048ms         4.50%       2.048ms     136.530us            15
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
Self CPU time total: 55.499ms
Self CUDA time total: 45.533ms

And on my laptop:

Torch version: 2.13.0+cu130
Device: cuda
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                                                   Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg     Self CUDA   Self CUDA %    CUDA total  CUDA time avg    # of Calls
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                             aten::convolution_backward         2.17%       1.045ms         4.84%       2.336ms     155.751us      18.415ms        39.41%      20.200ms       1.347ms            15
                                   volta_sgemm_64x64_nt         0.00%       0.000us         0.00%       0.000us       0.000us       7.011ms        15.00%       7.011ms     701.137us            10
                 aten::max_pool2d_with_indices_backward         0.30%     145.434us         0.78%     374.220us      37.422us       6.506ms        13.92%       7.508ms     750.760us            10
void at::native::(anonymous namespace)::max_pool_bac...         0.00%       0.000us         0.00%       0.000us       0.000us       6.506ms        13.92%       6.506ms     650.619us            10
                                aten::cudnn_convolution         1.38%     667.182us         4.76%       2.296ms     153.068us       6.441ms        13.78%       6.687ms     445.773us            15
                               aten::threshold_backward         0.42%     200.609us         0.65%     314.114us      20.941us       3.615ms         7.74%       3.615ms     240.968us            15
void at::native::vectorized_elementwise_kernel<4, at...         0.00%       0.000us         0.00%       0.000us       0.000us       3.615ms         7.74%       3.615ms     240.968us            15
void cudnn::winograd_nonfused::winogradForwardData4x...         0.00%       0.000us         0.00%       0.000us       0.000us       2.913ms         6.23%       2.913ms     145.671us            20
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
Self CPU time total: 48.253ms
Self CUDA time total: 46.729ms

How to read the table:

  • Each row aggregates all the calls to one operation. Self is the time spent in the operation itself, while total also counts its children. Look at the self columns to find the actual hot spots.
  • The rows named aten::... are PyTorch operations. The other rows are the CUDA kernels that run them. On the training cluster, 39% of the GPU time goes to the kernel sm80_xmma_wgrad_implicit_gemm..., which computes the gradients of the convolution weights inside aten::convolution_backward.
  • An operation with a time in the CPU columns and nothing in the CUDA ones runs on the CPU. A large one there is a sign that something (data manipulation, a metric computed on CPU tensors) silently left the accelerator.
  • nchwToNhwcKernel converts images between the layout of PyTorch (channels first) and the layout cuDNN prefers (channels last): on the training cluster, these conversions cost 5.7% of the GPU time.
  • The name of the main kernel contains tf32: cuDNN already computes the convolutions in TF32, a reduced precision that we will come back to.
  • For these 5 steps, the CPU side accounts for 55 ms and the GPU side for 46 ms on the training cluster. With a model this small, launching and coordinating the kernels costs as much as running them. This is the overhead that torch.compile reduces.

The table answers “which operation”. To know “when”, look at the trace: trace.json was written in the directory from which you launched the job. Transfer it to your machine (from a terminal on your machine):

scp userxx@xxx.xxx.xxx:pytorch_course/trace.json .

then drag the file into a trace viewer such as Perfetto. Every kernel appears on a timeline, and the gaps between kernels show when the GPU was waiting.

The profiler only sees what runs inside its context: our script holds the batch on the device to keep the profile focused on compute, so the data pipeline of the parallel loading section is invisible here. For a data-starved run, the diagnosis tools of that section (epoch times, nvidia-smi) come first.

Optimizations

Compilation

A baseline epoch

This is eager PyTorch: each operation is launched one at a time, exactly as the code is written. On small models like ours, the accelerator spends much of each step waiting for the next kernel launch: the model is so small that its 95,000 parameters cannot keep the hardware busy. The benchmark measured a step at 9.2 ms on the training cluster and 7.7 ms on my laptop: this is our baseline.

Just-in-time (JIT) compilation

torch.compile wraps a module so that its first call captures the operations into a graph, which is then JIT-compiled into fused kernels and optimized as a whole:

compiled = torch.compile(model)
  • The return value is a drop-in replacement: call it, train with it, everything works as before.
  • The wrapped model’s parameters are the same objects the optimizer already holds: no new optimizer needed.
  • Nothing happens yet: compilation is deferred to the first call.

What happens under the hood?

First, TorchDynamo records the operations your Python code performs on the model into a graph (stopping at “graph breaks” it cannot handle and compiling each fragment).

Then the Inductor backend generates optimized kernels for that graph: Triton kernels on GPUs. Fusing sequences of elementwise operations into one kernel is where much of the speedup comes from: fewer launches and intermediate results stay in fast GPU memory.

Watch out for recompilations.

A graph is compiled for the shapes it sees. Our training loader yields batches of shape (64, 3, 64, 64) all the way, except the last one, which has 32 images, so the first epoch compiles the model twice. With many distinct shapes (variable sequence lengths, varying image sizes), torch.compile can spend its time recompiling instead of training. In that case, there are two remedies: drop_last=True on the training loader (we saw that option earlier in the course when counting batches), and torch.compile(model, dynamic=True) to compile shape-generic graphs.

torch.compile also takes a mode argument: the default balances compile time against speed, while mode="max-autotune" lets the compiler try more kernel variants at the cost of longer compilation. For a loop that runs for hours, a few extra minutes of compilation are a good trade.

Test run

We measure compilation twice: on the training step alone, then on the complete epoch.

The step alone. Edit benchmark.py and add these lines at the end of the main() function:

benchmark.py
...
    for batch in (16, 32, 64, 128, 256, 512):
        per_step, times = benchmark(model, batch)
        print(" ".join(f"{t:.2f}" for t in times), "s for 50 steps")
        print(
            f"batch {batch:4d}: {per_step * 1e3:5.1f} ms/step, {batch / per_step:6.0f} images/s"
        )

    # These are the new lines:
    compiled = torch.compile(model)  # a drop-in replacement for model

    t0 = time.perf_counter()
    benchmark(compiled, 64)  # the first call compiles
    print(f"\nCompilation: {time.perf_counter() - t0:.1f} s")
    per_step, _ = benchmark(compiled, 64)
    print(
        f"batch  64, compiled: {per_step * 1e3:5.1f} ms/step, {64 / per_step:6.0f} images/s"
    )
...

Run it again. After the batch size sweep, this is what I got on the training cluster:

Compilation: 14.5 s
batch  64, compiled:   7.5 ms/step,   8505 images/s

And on my laptop:

Compilation: 4.4 s
batch  64, compiled:   7.8 ms/step,   8246 images/s

The complete epoch. The benchmark leaves the data pipeline out. train_faster.py times whole epochs of bare training steps with our real data loader, in eager mode first, then compiled. It applies the rules of the benchmarking section to epochs: one warmup epoch, then 3 timed epochs, and the median:

nano train_faster.py
import statistics  # to take the median of the timed epochs
import time  # to time epochs
from pathlib import Path

import torch
from torch import nn
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import EuroSAT
from torchvision.transforms import v2 as T


class Net(nn.Module):
    """A small CNN for 64x64 images and 10 classes."""

    def __init__(self):
        super().__init__()
        self.layers = nn.Sequential(
            # 3 conv blocks: each doubles the channels; the first two halve the image
            nn.Conv2d(3, 32, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 64 -> 32
            nn.Conv2d(32, 64, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 32 -> 16
            nn.Conv2d(64, 128, 3, padding=1),
            nn.ReLU(),  # 16 -> 16
            nn.AdaptiveAvgPool2d(1),  # one value per channel: 128 features
            nn.Flatten(),
            nn.Linear(128, 10),  # one score per class
        )

    def forward(self, x):
        return self.layers(x)


def main():
    device = (
        torch.accelerator.current_accelerator()
        if torch.accelerator.is_available()
        else torch.device("cpu")
    )
    print(f"Torch version: {torch.__version__}\nDevice: {device}")
    torch.manual_seed(42)

    root = Path("/project/def-sponsor00/data")
    IMAGENET_MEAN, IMAGENET_STD = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]

    train_tf = T.Compose(
        [
            T.RandomHorizontalFlip(),
            T.RandomVerticalFlip(),
            T.RandomRotation(90),
            T.ToImage(),
            T.ToDtype(torch.float32, scale=True),
            T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
        ]
    )

    idx = torch.load(root / "split.pt", weights_only=True)
    train = Subset(EuroSAT(root=root, transform=train_tf), idx["train"])

    loader_kwargs = {
        "batch_size": 64,
        "num_workers": 3,
        "persistent_workers": True,
        "pin_memory": True,
    }
    train_loader = DataLoader(
        train,
        shuffle=True,
        generator=torch.Generator().manual_seed(42),
        **loader_kwargs,
    )
    print(f"Train batches: {len(train_loader)}")

    model = Net().to(device)
    print("Parameters:", sum(p.numel() for p in model.parameters()))

    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

    def timed_epochs(m, n=3):
        """Run n epochs of bare training steps on model m, return their durations in s."""
        times = []
        for _ in range(n):
            t0 = time.perf_counter()
            for x, y in train_loader:
                x = x.to(device, non_blocking=True)
                y = y.to(device, non_blocking=True)
                optimizer.zero_grad()
                loss = loss_fn(m(x), y)
                loss.backward()
                optimizer.step()
            torch.accelerator.synchronize()  # the steps are only queued: wait for them
            times.append(time.perf_counter() - t0)
        return times

    def report(name, times):
        middle = statistics.median(times)
        print(
            f"{name + ':':<9} {' '.join(f'{t:4.1f}' for t in times)} s"
            f"  (median {middle:.1f} s/epoch)"
        )

    timed_epochs(model, 1)  # warmup epoch
    report("Eager", timed_epochs(model))

    compiled = torch.compile(model)

    t0 = time.perf_counter()
    timed_epochs(compiled, 1)  # first call: compiles
    torch.accelerator.synchronize()
    print(f"First epoch (with compilation): {time.perf_counter() - t0:4.1f} s")

    report("Compiled", timed_epochs(compiled))


if __name__ == "__main__":
    main()

Run it with:

srun --mem=10000 --gpus-per-node=1 --cpus-per-task=3 python train_faster.py

This takes about 2.5 minutes and only 2 persons could run it at a time since we only have 2 GPU nodes on this cluster.

Results

This is what I got on the cluster:

Torch version: 2.14.1
Device: cuda
Train batches: 338
Parameters: 94538
Eager:     9.9 10.2 10.2 s  (median 10.2 s/epoch)
W1203 [...] Not enough SMs to use max_autotune_gemm mode
UserWarning: TRITON_DEFAULT_FP_FUSION is unset: defaulting to FP fusion ENABLED
for backward compatibility in Triton 3.9. The default will change to DISABLED in
Triton 3.10; set TRITON_DEFAULT_FP_FUSION=1 to keep fusion enabled or =0 to adopt
the new default early and silence this warning.
First epoch (with compilation): 69.7 s
Compiled: 10.3 10.2 10.0 s  (median 10.2 s/epoch)

Adapting the data path and the loader arguments to my hardware as usual, this is what I got on my machine:

Torch version: 2.13.0+cu130
Device: cuda
Train batches: 338
Parameters: 94538
Eager:     2.8  2.8  2.8 s  (median 2.8 s/epoch)
W1203 [...] Not enough SMs to use max_autotune_gemm mode
First epoch (with compilation): 14.2 s
Compiled:  2.3  2.3  2.3 s  (median 2.3 s/epoch)

Three things to read in these numbers:

  • The first compiled pass pays a one-time compilation cost: its epoch lasted 69.7 s on the training cluster, against 10.2 s for an eager epoch (and 36 s for the very first compilation of our model on this cluster). The compiled kernels are cached on disk (under Triton’s cache directory), so later processes that compile the same graph start faster.
  • On the training cluster, compilation leaves the epoch where it was. The loader brings a batch every 30 ms or so (10 s for 338 batches), three times longer than the step: the GPU was already waiting for data most of the time, so a shorter step only lengthens the wait. A benchmark of the step alone would have announced a gain that the real training loop never sees.
  • On my laptop, there is a slight improvement per epoch.

With our CNN, the big convolutions were already well served by cuDNN and compilation brings little to no gain depending on the hardware. Models with more Python-level overhead (e.g. transformers) do see large speedups from compilation.

TensorFloat-32 (TF32)

The compute that dominates training is matrix multiplication and GPUs have fast units for it. Since the Ampere generation (2020), NVIDIA GPUs can run float32 matrix products in TF32, a format that keeps float32’s range but carries only 10 bits of mantissa. The accuracy loss is invisible for deep learning, and the speedup on matmul-heavy workloads is substantial.

Format Sign Exponent Mantissa Notes
float32 1 8 23 The default dtype of training
TF32 1 8 10 float32 range, reduced precision, used internally by tensor cores
bfloat16 1 8 7 The autocast format of our loop

PyTorch lets you pick how float32 matmuls are allowed to degrade:

To try short snippets such as the ones of this section on the cluster, start an interactive Python session inside an allocation, with ipython (no GPU needed here):

srun --mem=3800 --cpus-per-task=1 ipython
print(torch.get_float32_matmul_precision())
highest
  • The default, "highest", never leaves float32.
  • "high" allows TF32 (or bfloat16 on hardware without TF32).
  • "medium" allows bfloat16.

Convolutions have a separate switch, torch.backends.cudnn.allow_tf32, which has been True by default for years.

torch.set_float32_matmul_precision("high")  # one line, usually near the top of a script

What it changes for us

I timed training steps with the benchmark of this page, on the GPU of the training cluster (a MIG of an H100), before and after that line:

Model Batch "highest" "high" Speedup
our CNN 64 9.15 ms 9.19 ms none
3 large linear layers 64 18.19 ms 14.90 ms 1.2×
3 large linear layers 512 43.96 ms 18.84 ms 2.3×
3 large linear layers 2048 136.84 ms 34.84 ms 3.9×

Our CNN gains nothing: its only matrix product is the tiny final layer, and its convolutions already ran in TF32 (the profiler showed it). Switching TF32 off for cuDNN (torch.backends.cudnn.allow_tf32 = False) makes our step 10% slower: 10.0 ms. The switch for matmuls matters for models made of large linear layers, transformers in particular.

TF32 needs Ampere or newer. The RTX 2060 of my laptop is a Turing GPU: no TF32 units, so none of these settings changes anything there. On the GPUs of the Alliance clusters, both switches are open: the one for convolutions by default, the one for matmuls after the line above.

Your turn:

Build a model that has something to gain from TF32: three large linear layers on the flattened images. Time its training step at batch 64, 512, and 2048, with the matmul precision set to "highest" then to "high". Start from benchmark.py.

  • First hint: nn.Sequential(nn.Flatten(), nn.Linear(64 * 64 * 3, 4096), nn.GELU(), nn.Linear(4096, 4096), nn.GELU(), nn.Linear(4096, 10)).
  • Second hint: call torch.set_float32_matmul_precision(...) between two calls of benchmark().
  • Third hint: 50 steps of batch 2048 take a while: reduce the number of steps for that batch size.

The memory side

Speed is one constraint; memory (VRAM) is the other. Training a model keeps several copies of the parameters in GPU memory, and knowing their sizes tells you at a glance what fits.

For a model trained in float32 with an adaptive optimizer like AdamW:

def training_footprint(n_params):
    """Approximate VRAM for the learned state of a model in MiB."""
    per_param = (
        4  # weights
        + 4  # gradients
        + 4
        + 4  # AdamW keeps two moments per parameter
    )
    return n_params * per_param / 2**20

Apply the arithmetic to our CNN and to ResNet-18, the pretrained model of the next section (the classifier head replaced for our 10 classes):

n_ours = sum(p.numel() for p in model.parameters())
print(f"our CNN:  {n_ours:>10,} params  ~{training_footprint(n_ours):6.1f} MiB")

resnet = resnet18(num_classes=10)  # random weights: we only count parameters here
n_rn18 = sum(p.numel() for p in resnet.parameters())
print(f"resnet18: {n_rn18:>10,} params  ~{training_footprint(n_rn18):6.1f} MiB")
our CNN:        94,538 params  ~   1.4 MiB
resnet18:   11,181,642 params  ~ 170.6 MiB

Two conclusions:

  • Both models fit easily in the 12 GiB of the GPU of our training cluster (and in the 6 GiB of my laptop). Add activations (the intermediate results of the forward pass, which scale with batch size and image size), and the measured peak of fine-tuning ResNet-18 on our 64 × 64 images at batch 64 is 300 MiB on the training cluster (330 MiB on my laptop).
  • The arithmetic explains when models stop fitting: a 7-billion-parameter model trained in float32 with AdamW needs about 104 GiB for weights, gradients, and moments alone, before a single activation. Few GPUs hold that much; splitting the training state across several of them is the topic of a later section.

To measure rather than estimate on a CUDA GPU, read the allocator’s high-water mark after a training step:

torch.cuda.reset_peak_memory_stats()  # then run one step
print(f"peak: {torch.cuda.max_memory_allocated() / 2**20:.0f} MiB")

Note that mixed precision does not halve this footprint: with autocast, weights, gradients, and optimizer state stay in float32; only the compute runs in bf16.

Your turn:

The GPU of the training cluster has 12 GiB of memory. If all of it went to the learned state, how many parameters could we train in float32 with AdamW?

Where to start

In the order that pays off the soonest:

  1. Feed the accelerator: workers, prefetching, pinned memory. No code change in the model.
  2. JIT-compilation of the model: one line, a gain that depends on the model and on how much of its time is overhead, first-call compilation cost.
  3. Precision: TF32 where available, bf16 autocast otherwise (the gate of our loop).
  4. More hardware: when one GPU is genuinely not enough, use multiple GPUs as we will see later.

Measure between each of these steps: steps on the device and whole epochs before and after the change, the profiler to know where the time goes.