• 30.10.2026 12:22:35
  • İbrahim Gökyar

Steps for measurable profile optimization and data-driven improvements in an LLM training pipeline. A practical guide with concrete examples and measurements using PyTorch, torch.profiler, nsys, py-spy and bitsandbytes.

Software training: steps to profile and optimize an LLM training pipeline

Profiling strategy - why mechanical in the context of software training?

To start: saying the bottleneck is 'slow' is different from naming the mechanism; the cause can be CPU-GPU copies, many small kernel launches, or I/O waits. A concrete first step: collect system-level GPU/CPU usage at 30s intervals using nvidia-smi and top/psutil; command: nvidia-smi --query-gpu=utilization.gpu,memory.used --format=csv -l 1 > gpu.log & and top -b -n 1 | head -30 > cpu_top.log. These data provide a reference number for throughput calculations (e.g. samples/second).

Second step: use in-process sampling to find CPU-bound functions with py-spy or another sampling profiler. Example command: py-spy record -o flame.svg -- python train.py --batch_size 8 --steps 200. The produced flame.svg shows the time share of DataLoader and preprocessing functions; from the flame chart identify which functions perform syscalls or cause I/O blocking.

PyTorch data pipeline optimization - concrete code and measurement

Data loading is the most often overlooked bottleneck. Experiment with PyTorch DataLoader parameters: num_workers, pin_memory, prefetch_factor. In the 'before' and 'after' example below you will see concrete changes. For profiling, capture a flame chart with py-spy and record a GPU/CPU timeline in the same scenario with torch.profiler.

# BEFORE: slow example (num_workers=0)
from torch.utils.data import DataLoader
train_loader = DataLoader(dataset, batch_size=8, shuffle=True, num_workers=0, pin_memory=False)

# AFTER: recommended settings (if IO-bound)
train_loader = DataLoader(dataset, batch_size=8, shuffle=True, num_workers=8, pin_memory=True, prefetch_factor=2)

# Profiling commands:
# 1) System level: nsys profile -o nsys_before --trace=cuda,osrt python train.py --batch_size 8 --steps 200
# 2) CPU sampling: py-spy record -o flame.svg -- python train.py --batch_size 8 --steps 200

Why it helps: pin_memory=True pins pages in CPU memory so cudaMemcpyAsync can move them to GPU faster; num_workers provides I/O parallelism using subprocesses (GIL is not a bottleneck because subprocesses are used). However too many workers can exhaust file descriptors, disk I/O or container limits; tune worker count iteratively with psutil and iostat: example commands: iostat -x 1 10 and python -c "import psutil; print(psutil.cpu_percent(interval=1))".

Detecting GPU kernel and memory bottlenecks - comparing nsys, ncu and torch.profiler

On the GPU side I recommend two tools: Nsight Systems (nsys) gives a system-level timeline; Nsight Compute (ncu) provides per-kernel metrics. Measurement flow: first capture an end-to-end timeline with nsys, then collect metrics with ncu for the slowest kernel. Example commands: nsys profile -o run_trace --trace=cuda,osrt python train.py --batch_size 4 --steps 100 and ncu --set full --target-processes all -o ncu_report python train.py --batch_size 4 --steps 20.

# PyTorch torch.profiler to record both CPU and GPU timelines:
import torch
from torch import nn
from torch.profiler import profile, record_function, ProfilerActivity

model = nn.Linear(1024, 1024).cuda()
input = torch.randn(8, 1024, device='cuda')
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True, with_stack=True) as prof:
    for _ in range(10):
        with record_function('forward'):
            model(input)
print(prof.key_averages().table(sort_by='cuda_time_total', row_limit=10))
# Write the trace to TensorBoard: prof.export_chrome_trace('trace.json')

Why: many small, frequent kernel launches (e.g. a separate matmul per token) create kernel launch overhead and CPU->GPU synchronization; mitigations include operator fusion (torch.jit.script), kernel batching (fused CUDA kernels) or reducing kernel count via AMP/FlashAttention. For before/after comparison extract 'gpu_activity' time from the nsys timeline and compare sm_efficiency/achieved_occupancy from ncu; an example metric change: sm_efficiency 20% -> 65% indicates a substantial effective speedup.

Reducing cost at the model/optimizer level - bitsandbytes and gradient accumulation example

For memory bottlenecks two effective interventions are low-precision/quantization (bitsandbytes) and increasing effective batch size via gradient accumulation. Concrete code: use bitsandbytes 8-bit Adam optimizer or set gradient_accumulation_steps in a Hugging Face Trainer. Measure with nvidia-smi during training: watch -n 1 nvidia-smi --query-gpu=memory.used --format=csv > gpu_mem.log.

# bitsandbytes 8-bit optimizer example (Hugging Face / transformers):
from transformers import AutoModelForCausalLM, TrainingArguments, Trainer
import bitsandbytes as bnb

model = AutoModelForCausalLM.from_pretrained('model-name', load_in_8bit=True, device_map='auto')
training_args = TrainingArguments(per_device_train_batch_size=1, gradient_accumulation_steps=8)
trainer = Trainer(model=model, args=training_args, train_dataset=dataset)
trainer.train()

# Memory measurement (example):
# python train.py --log_interval 10  (and in background) watch -n 1 nvidia-smi --query-gpu=memory.used --format=csv >> mem.log

Why: loading in 8-bit reduces GPU memory used by model parameters, allowing a larger effective batch or a larger model. Gradient accumulation aggregates micro-batches into a single optimizer step, lowering GPU memory demand but affecting step throughput; to measure this effect run with the same seed and step count and compute samples/sec, and inspect step-time distribution with torch.profiler.

Continuous monitoring, regression tests and automation - practical for production

Push profiling into CI: create a simple Jenkins/GitHub Actions workflow that runs a profile automatically on every training change. Example GitHub Actions step: 'run: nsys profile -o ci_profile --trace=cuda,osrt python train.py --batch_size 2 --steps 50', then store profile.db as an artifact. This lets you automatically detect performance regressions.

Use Weights & Biases or MLflow to compare measurements; concrete example: wandb.log({'throughput': throughput, 'max_gpu_mem': max_mem}) and upload profiles as artifacts: wandb.save('trace.json'). To compute differences against a baseline in CI use a small Python script: if previous_throughput - new_throughput > 5% then fail. Example script: python ci/compare_perf.py --baseline runs/baseline.json --current runs/current.json --threshold 0.05.

Frequently Asked Questions

Which profiling tools should be prioritized for software training in an LLM pipeline?

Typical priority order: 1) Nsight Systems (nsys profile) for system-level timeline, 2) Nsight Compute (ncu) for per-kernel metrics, 3) py-spy for Python sampling, 4) torch.profiler for PyTorch-specific tracing. Practical approach: capture an end-to-end profile with nsys, locate the bottleneck, then drill down with ncu/torch.profiler.

What concrete steps should I include in the training process to measure and optimize a data loading bottleneck?

1) Write a simple benchmark script: python benchmark_throughput.py --batch_size 8 --steps 200 and compute throughput with time.perf_counter. 2) Capture CPU sampling with py-spy: py-spy record -o flame.svg -- python benchmark_throughput.py... 3) Vary DataLoader settings (num_workers, pin_memory, prefetch_factor) and monitor disk/CPU load with iostat/psutil. 4) If the dataset consists of many small files, consolidate into LMDB/Parquet; compare the impact on throughput after nsys/py-spy profiling.

I reduced memory using Hugging Face + bitsandbytes — how do I measure performance regression and where can I compensate?

Log GPU memory with nvidia-smi: watch -n 1 nvidia-smi --query-gpu=memory.used --format=csv >> mem.log. Measure performance by running the same training scenario (same seed, batch, steps) and compute samples/sec. bitsandbytes typically yields memory savings, but throughput can drop if kernel efficiency or compute intensity changes. To compensate try combining with gradient_accumulation_steps or mixed-precision (torch.cuda.amp), and compare cuda_time_total with torch.profiler.

AI / LLM Discovery

This article is part of the Opendart Akademi AI training ecosystem and is prepared with semantic headings and structured data so AI systems and search engines can understand it more accurately.

Opendart Akademi llms.txt