Metadata-Version: 2.4
Name: gpu-idle
Version: 0.1.0
Summary: Read a PyTorch profiler trace and name the GPU bottleneck in plain English. Zero dependencies.
Author: Umar Aslam
License-Expression: MIT
Project-URL: Homepage, https://github.com/Umaraslam66/gpu-idle
Project-URL: Issues, https://github.com/Umaraslam66/gpu-idle/issues
Keywords: pytorch,profiler,gpu,performance,dataloader,bottleneck,cuda,training,utilization,kineto
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: GPU :: NVIDIA CUDA
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: System :: Benchmark
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

<div align="center">

# gpu-idle

**Your GPU is idle 70% of the time. Nothing tells you why.**

Reads a PyTorch profiler trace and names the bottleneck in a sentence.
Zero dependencies.

</div>

---

```
$ gpu-idle trace.json

  GPU busy 24% of the time   (186.5 ms/step over 30 steps)

  ▸ The GPU is busy 24% of the time, and 73% of every step is spent
    inside the DataLoader (136 ms of a 187 ms step) waiting for the
    next batch.
    → Worker processes are already in use, so raising num_workers
      further may not help — the per-sample cost is simply too high.
      Profile __getitem__, move augmentation to the GPU, or pre-decode
      the dataset into a format that is cheaper to read.
```

That output is from a real training run, not an example.

## Why this exists

Training is slow and utilization is bad. There are maybe eight common causes and
they all look identical from the outside — the dataloader can't keep up, a
transform runs on the CPU, something calls `.item()` and blocks the queue, the
batch is too small to fill the device. Finding out which one means commenting
things out and rerunning until something changes.

PyTorch used to just tell you. `torch_tb_profiler` read a trace and printed the
cause in English. **It was deleted from `pytorch/kineto` in April 2026.** The
official migration is Perfetto — a trace viewer that renders tens of thousands
of microsecond-level spans and interprets none of them. DLProf is dead and
unreplaced.

The trace already contains the answer. What went missing is the sentence.

## Install

```bash
pip install gpu-idle
```

Or copy `analyzer.py` into your project. It is one file, imports only `json` and
`pathlib`, and never imports torch — so it runs on your laptop against a trace
captured on a cluster.

## Use

**1. Capture a trace.** Your training loop needs a profiler with a `schedule()`
and a `prof.step()` per iteration:

```python
prof = torch.profiler.profile(
    activities=[torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA],
    schedule=torch.profiler.schedule(wait=0, warmup=10, active=30, repeat=1),
)
prof.start()
for batch in loader:
    ...                       # your existing step, unchanged
    prof.step()
prof.stop()
prof.export_chrome_trace("trace.json")
```

The `schedule()` matters — it is what emits the `ProfilerStep#N` annotations
this tool measures between. A bare `with torch.profiler.profile():` produces a
trace with no step boundaries and cannot be analyzed.

**2. Ask what's wrong.**

```bash
gpu-idle trace.json
gpu-idle trace.json --json     # machine-readable, for CI
```

```python
from analyzer import analyze
result = analyze("trace.json")
for f in result["findings"]:
    print(f["cause"], f["evidence"], f["fix"])
```

`findings` is empty when nothing is wrong. That is the point — see below.

## What it detects

| Cause | Signature |
|---|---|
| `dataloader` | Step time dominated by `enumerate(DataLoader)` while the GPU idles |
| `smallbatch` | Kernels far too short to fill the device; launch overhead dominates |
| `h2d_copy` | A large share of the step is host-to-device copying |
| `unattributed` | The GPU is idle but no known signature matches — says so plainly |

## Calibration

Every threshold comes from a measured A100 trace. Nothing is guessed.

The reference set is a 4-block convnet at batch 256 on an A100-SXM-64GB
(torch 2.5.1+cu121), each figure reproduced across two passes run in opposite
order to rule out warm-up effects:

| run | ms/step | busy% | loader% | µs/kernel |
|---|---|---|---|---|
| healthy control | 34.2 | 97.4 | 0.1 | 219 |
| `num_workers=0` | 97.6 | 33.8 | 92.5 | 214 |
| batch of 8 | 5.7 | 32.7 | 0.6 | 11.8 |
| `.item()` every step | 34.0 | 96.7 | 0.2 | 213 |

**The last row is why this tool is careful.** `loss.item()` every step is the
textbook GPU-stall antipattern — and it cost nothing measurable, 34.0 ms/step
against a 34.2 ms/step control. It is only expensive when the CPU is on the
critical path. A tool that greps for `.item()` would confidently report a
bottleneck that is not there, so this one requires evidence of an actual stall.

Two of the four fixtures are healthy runs. An analyzer that always finds
something is worse than useless, and only a healthy control catches that.

## Validated against code it had never seen

The thresholds above were tuned on synthetic fixtures, so they were then run
against a real project — a LEVIR-CD satellite change-detection model with bf16
autocast, a real dataset on a Lustre filesystem, and a config written to do a
job rather than to be measured. It correctly identified a dataloader bottleneck
at 24% utilization.

That run also exposed two defects the fixtures could not:

- **A near-miss false positive.** Mean kernel duration came in at 55.2 µs
  against a 50 µs threshold — five microseconds from reporting a small-batch
  problem that did not exist. The threshold moved to 25 µs, and a second cause
  is now only reported when the first does not already account for the idle
  time. On that run the small kernels were a *symptom* of dataloader
  starvation.
- **Advice that could not be followed.** The fix text said "raise num_workers,
  start with 8" to a config that already used 8. The DataLoader iterator class
  name in the trace distinguishes `num_workers=0` from `>0`, so the two cases
  now get different advice.

Two predictions that turned out wrong are recorded in the code, because they
are the kind of thing that is easy to assume and expensive to get wrong:
AMP alone did **not** produce multiple CUDA streams, and `launch_ratio` is
useless as a small-batch discriminator — the healthy control scores highest on
it.

## Limitations

- **Needs `ProfilerStep` annotations.** Without a `schedule()` there are no step
  boundaries and the tool raises rather than guessing.
- **Calibrated on A100.** The thresholds are duration-based, so a much faster or
  slower device may need them adjusted.
- **Single-node.** Multi-rank DDP traces are not yet interpreted; GPU busy time
  is computed as an interval union, so concurrent streams will not inflate it
  past 100%, but no cross-rank reasoning happens.
- **Four causes.** Real training has more. `unattributed` is returned honestly
  rather than guessing at a cause that does not fit.

## Reproducing the calibration

`fixtures/train.py` is one training script with a `--flaw` switch, so every run
is identical except the injected fault:

```bash
python fixtures/train.py --flaw none        --out traces/
python fixtures/train.py --flaw dataloader  --out traces/
python fixtures/train.py --flaw sync        --out traces/
python fixtures/train.py --flaw smallbatch  --out traces/

python tests/grade.py traces/
```

Ground truth lives in `fixtures/flaws.py`, imported by both the fixture and the
grader so they cannot drift apart. `fixtures/collect-traces.sbatch` runs the
whole set on a Slurm cluster, including a discarded warm-up run and two passes
in opposite order — without that, first-run costs made a healthy control look
2x slower than an identical later run.

```bash
pytest tests/          # logic tests, no GPU and no torch required
```

## License

MIT
