Mixed precision training

From wenmin-wu/ds-skills · View interactive version

Mixed precision training is an AI agent skill from the GitHub repository wenmin-wu/ds-skills. Uses PyTorch AMP autocast and GradScaler for FP16 training, halving memory usage and speeding up training on modern GPUs.

How to use this skill

Skill file

Mixed Precision Training

Overview

Run forward pass in FP16 (half precision) while keeping master weights in FP32. This halves GPU memory for activations and enables larger batch sizes or image resolutions. PyTorch's autocast handles dtype selection per operation; GradScaler prevents underflow in FP16 gradients.

Quick Start

import torch
from torch.cuda.amp import autocast, GradScaler

scaler = GradScaler()

for images, labels in train_loader:
    images, labels = images.cuda(), labels.cuda()
    optimizer.zero_grad()

    with autocast():
        logits = model(images)
        loss = criterion(logits, labels)

    scaler.scale(loss).backward()
    scaler.unscale_(optimizer)
    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    scaler.step(optimizer)
    scaler.update()

Workflow

  1. Create GradScaler() before training loop
  2. Wrap forward pass + loss in autocast() context
  3. Call scaler.scale(loss).backward() instead of loss.backward()
  4. Optionally unscale before gradient clipping
  5. scaler.step(optimizer) and scaler.update() replace optimizer.step()

Key Decisions

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.