Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

## Unreleased

- Multi-GPU `vllm serve` captures (tensor and pipeline parallelism): `ledger report` writes one report
per GPU worker under `pid-<pid>/`, and the analysis refuses to merge the records of several
processes into one set of books. Step markers of pipeline ticks without a forward pass are folded
into the step before them, NCCL collectives get their own `## Collectives` section and a
`waiting in collectives` row instead of counting as underfilled launches, and the plugin warns when
a worker was forked and will record nothing (`VLLM_WORKER_MULTIPROC_METHOD=spawn`).
- `ledger build` finds CUPTI in pip-installed NVIDIA wheels and links `libcupti.so.<N>` and
`libcuda.so.1` by file name, so it works inside the official vLLM images.
- Fixed: the vLLM memory-map export failed on models with `ReplicatedLinear` layers (no
per-partition widths); the per-step idle time went negative when a kernel outlasted the last one to
start.
- `ledger ceilings --from-profile <VirtualGPU profile JSON> [--device <name>]` caches the bandwidth
and bf16 compute ceilings from a VirtualGPU GPU profile, so captures can be analyzed without the
GPU (and Ascend captures without hand-entered ceilings).
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ See [docs/quickstart.md](docs/quickstart.md) for the full walkthrough (including
| `ledger build` | Compile `capture/libledger.so` (and with `--access`, the Compute Sanitizer tracer) against the local CUDA toolkit. |
| `ledger ceilings` | Measure and cache GPU DRAM read bandwidth (`bench/bwtest.cu`) and GEMM TFLOP/s (`bench/flops.py`), or take them from a [VirtualGPU](https://github.com/VirtualGPU/VirtualGPU) profile with `--from-profile` when the GPU is not at hand. |
| `ledger profile` | Capture a vLLM run under CUPTI and write `<out>/report.md` (`analyze` + `steps`) and `<out>/trace.json`. |
| `ledger report` | Re-generate the combined `analyze` + `steps` Markdown report from an existing capture directory. |
| `ledger report` | Re-generate the combined `analyze` + `steps` Markdown report from an existing capture directory (one per process when the capture holds several GPU workers). |
| `ledger analyze` | Per-launch bandwidth, compute floor, same-kernel/same-shape splits, repeated reads, underfilled grids, and top `## Findings`. |
| `ledger steps` | Step-to-step cycle split (GPU busy, intra-step idle, host idle), speculative yield, KV-cache attention bandwidth, and SM clocks. |
| `ledger diff` | Compare two captures launch group by launch group past run-to-run clock/power-cap drift, plus token equality and `--fail-above` CI gating ([example workflow](docs/ci-diff-gate.yml)). |
Expand Down Expand Up @@ -105,7 +105,11 @@ See [docs/quickstart.md](docs/quickstart.md) for the full walkthrough (including
step, the same GPU busy time).
- NVML power readings on GB10 are not usable as GPU power (a few watts under full load); the SM
clock and temperature are.
- Tested on NVIDIA GB10 (sm_121) with vLLM 0.31, 0.34 and main.
- Tested on NVIDIA GB10 (sm_121) with vLLM 0.31, 0.34 and main, and on six RTX 5090 (sm_120) under
`vllm serve` 0.32 with tensor and pipeline parallelism.
- A capture of several GPU workers gets one report per worker (`ledger report` writes
`pid-<pid>/report.md`): each has its own address space and its own GPU. Collectives are listed with
the time the GPU did nothing but wait in them; whose work they waited for is not resolved.
- Copy addresses are decoded for linear copies (`cudaMemcpy[Async]`, `cuMemcpy[Async]`,
`cuMemcpy{HtoD,DtoH,DtoD}[Async]` and their per-thread-stream variants) and for memcpy nodes of
graphs. 2D/3D, peer and symbol copies are timed and counted but not attributed to a region.
Expand All @@ -121,7 +125,7 @@ See [docs/quickstart.md](docs/quickstart.md) for the full walkthrough (including

## Next

- Multi-GPU: account for collectives.
- Multi-GPU: one set of books across the workers, charging a collective's wait to the rank it waited for.

## License

Expand Down
7 changes: 6 additions & 1 deletion capture/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ CUDA ?= /usr/local/cuda
CUPTI_INC ?= $(firstword $(wildcard $(CUDA)/extras/CUPTI/include $(CUDA)/targets/*/include))
CUPTI_LIB ?= $(firstword $(wildcard $(CUDA)/extras/CUPTI/lib64 $(CUDA)/targets/*/lib))

# Link both libraries by file name. A pip-installed CUDA ships libcupti.so.<N> without the libcupti.so
# that -lcupti looks for, and a container gets the driver's libcuda.so.1 without a libcuda.so.
CUPTI_SO ?= $(firstword $(wildcard $(CUPTI_LIB)/libcupti.so $(CUPTI_LIB)/libcupti.so.*))
CUDA_SO ?= $(firstword $(wildcard $(CUDA)/lib64/stubs/libcuda.so $(CUDA)/targets/*/lib/stubs/libcuda.so) -l:libcuda.so.1)

libledger.so: ledger_cupti.cc
$(CXX) -O2 -std=c++17 -shared -fPIC -o $@ $< -I$(CUDA)/include -I$(CUPTI_INC) \
-L$(CUPTI_LIB) -L$(CUDA)/lib64 -Wl,-rpath,$(CUPTI_LIB) -lcupti -lcuda -ldl
-L$(CUDA)/lib64 -Wl,-rpath,$(CUPTI_LIB) $(CUPTI_SO) $(CUDA_SO) -ldl

clean:
rm -f libledger.so
2 changes: 2 additions & 0 deletions capture/ledger_cupti.cc
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,8 @@ void CUPTIAPI buffer_completed(CUcontext, uint32_t, uint8_t* buffer, size_t, siz
}

void ledger_start() {
// CUPTI records nothing in a child forked from here; the pid lets the child notice (ledger/vllm_plugin.py).
setenv("LEDGER_INIT_PID", std::to_string(getpid()).c_str(), 1);
cuptiActivityRegisterCallbacks(buffer_requested, buffer_completed);
cuptiSubscribe(&g_sub, callback, nullptr);
const CUpti_CallbackId driver[] = {
Expand Down
18 changes: 18 additions & 0 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ This compiles `capture/libledger.so` against your CUDA toolkit and caches it und
`~/.cache/ledger/build/` (printing the full path). Pass `--access` (and optionally `--arch <sm>`)
only if you also need the Compute Sanitizer access tracer.

CUPTI is looked up in the toolkit and, failing that, in pip-installed NVIDIA wheels
(`site-packages/nvidia/*/{include,lib}`), which is where the official vLLM images keep it. In a
container, build where the driver is visible (`--gpus ...`): the library links against `libcuda.so.1`.

## 3. Measure the GPU ceilings once

Make sure **no other process is using the GPU** — `ledger ceilings` checks `nvidia-smi` and refuses
Expand Down Expand Up @@ -154,6 +158,20 @@ window of 49 steps.
Because serving batch size varies from step to step, `run.json` has no fixed `batch` or `steps`, so
the `Compute` section (which needs `M`) applies only when steps have a known shape.

### More than one GPU

With `--tensor-parallel-size` or `--pipeline-parallel-size` above 1, add
`VLLM_WORKER_MULTIPROC_METHOD=spawn`. vLLM forks its GPU workers by default, and CUPTI records
nothing in a process forked from the one where the capture library started; the plugin says so on
stderr when it happens.

Every worker writes its own files into `out`, and `LEDGER_GRAPH_WINDOW` counts graph launches in
each worker separately. `ledger report out` then writes one report per worker,
`out/pid-<pid>/report.md`; `analyze`, `steps`, `perfetto`, `transfers` and `diff` take those
`pid-<pid>` directories. With pipeline parallelism a worker is stepped for every batch in flight, so
most of its step markers carry no forward pass: the analysis folds those into the step before them,
and a step is one forward pass on that worker.

---

## Profiling SGLang serve
Expand Down
16 changes: 15 additions & 1 deletion docs/reading-reports.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ Summarizes one step across the capture window:
is the gap between kernels inside the window. On GB10 Qwen3.8-27B (batch 1), wall time is
120.88 ms, GPU busy is 120.52 ms, and idle between kernels is 0.36 ms (0.3%). When idle is under
a percent, fusing kernels solely to eliminate launch gaps buys almost nothing.
- **waiting in collectives (part of busy)**: shown for multi-GPU workers. The time in which the only
kernels running were NCCL collectives, which occupy one block and spin until another GPU's data
arrives. It is counted in GPU busy, but it is another rank's time; the effective bandwidth below
is taken over GPU busy without it.
- **weight bytes streamed / effective bandwidth / floor at ceiling**: `floor = weight bytes / ceiling`.
In the same capture, 25.47 GB at 252 GB/s gives a 101.08 ms floor against 120.52 ms GPU busy
(211 GB/s, 84% of ceiling). The gap between GPU busy and the floor is the maximum time you could
Expand Down Expand Up @@ -121,10 +125,20 @@ Beneath the table, **Partial reads** lists tensors referenced by launches too sh
the whole weight even at 1.3× the ceiling (such as `embed_tokens`, which gathers a few rows rather
than streaming the matrix). These are excluded from the byte totals.

### `## Collectives`

Shown when the worker launched NCCL kernels (tensor or pipeline parallelism). One row per collective:
launches per step, median duration, total `ms/step` and **alone ms/step**, the part during which
this GPU ran nothing else. A long `Broadcast` or `SendRecv` with nearly all of its time alone is
typically a worker waiting for another stage of the pipeline; the all-reduces of tensor parallelism
are short and mostly overlap other work. The `waiting in collectives` row of `## Step` is the time
in which only collectives ran. Speeding this worker's kernels up does not shorten it.

### `## Launches with fewer blocks than SMs`

Shown when the SM count is known (`run.json` or `--sms`). Any kernel with `prod(grid) < SMs` leaves
SMs idle, but only costs the step when no other kernel runs beside it.
SMs idle, but only costs the step when no other kernel runs beside it. Collectives are one block by
design and are listed in their own section instead.

Read **alone ms/step** first (the table drops groups below 0.05 ms/step of alone time). A kernel on
a parallel CUDA graph branch can have a large total `ms/step` while its `alone ms/step` is near
Expand Down
110 changes: 100 additions & 10 deletions ledger/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,25 @@ def module(name):
return name.rsplit(".", 1)[0]


def processes(capture):
"""Ids of the processes that left kernel records in the capture (one per GPU worker)."""
paths = glob.glob(os.path.join(capture, "kernels-*.jsonl"))
return sorted(os.path.basename(p)[len("kernels-"):-len(".jsonl")] for p in paths)


def single_process(capture):
"""Records of several processes cannot share one set of books: every process has its own address
space, so one's pointers would resolve against another's memory map, and its own GPU, so their
kernels would count as overlapping on one device."""
pids = processes(capture)
if len(pids) > 1:
raise SystemExit(f"{capture}: kernel records of {len(pids)} processes ({', '.join(pids)}). Run "
"'ledger report' on it: it writes one report per process under pid-<pid>/, and "
"the other commands take those directories.")


def load(capture):
single_process(capture)
regions = []
for path in glob.glob(os.path.join(capture, "regions-*.json")):
regions += json.load(open(path))
Expand Down Expand Up @@ -219,29 +237,66 @@ def busy_and_gaps(rows):
cur_e = max(cur_e, r["end"])
if cur_e is not None:
busy += cur_e - cur_s
span = rows[-1]["end"] - rows[0]["start"] if rows else 0
# The last launch to start need not be the last to end: a collective waiting for another GPU, or a
# launch on a second stream, can outlast it.
span = max(r["end"] for r in rows) - rows[0]["start"] if rows else 0
return span, busy


COLLECTIVE = "ncclDevKernel" # NCCL's device kernels: one block that moves, or waits for, another GPU's data


def is_collective(r):
return COLLECTIVE in r["name"]


def waiting(rows):
"""Nanoseconds in which only collectives ran: the GPU is busy by the books, but with a kernel that
spins until another rank's data arrives."""
events = sorted([(r["start"], 1, is_collective(r)) for r in rows]
+ [(r["end"], -1, is_collective(r)) for r in rows])
total, active, last = 0, [0, 0], None
for t, kind, collective in events:
if active[1] and not active[0]:
total += t - last
active[collective] += kind
last = t
return total


MARKER = "spin_kernel" # torch.cuda._sleep, launched by examples/vllm_decode.py at the start of each step
DRAFT = ("speculator.", "drafter.", "spec_decode_model.", "draft.")


def split_steps(rows):
"""Cut the window at the step markers: (markers, steps), steps a list of row lists without the
markers. Rows of a step from its first launch streaming a draft-model weight on are marked
"draft". Without markers, (None, None)."""
"draft". Without markers, (None, None).

A marker is not always a forward pass. With pipeline parallelism every worker is stepped for every
batch in flight, also while the batch is at another stage: such a tick launches a collective or
nothing and touches no weight. Its launches join the forward pass before it, and it is not a step."""
marks = [i for i, r in enumerate(rows) if MARKER in r["name"]]
if not marks:
return None, None
steps = []
for a, b in zip(marks, marks[1:] + [len(rows)]):
step = rows[a + 1 : b]
spans = [rows[a + 1 : b] for a, b in zip(marks, marks[1:] + [len(rows)])]
forward = [any(r["weights"] or r["partial"] for r in span) for span in spans]
if not any(forward): # no memory map to tell by: every marker is a step
forward = [True] * len(spans)
markers, steps, has_pass = [], [], []
for mark, span, is_pass in zip(marks, spans, forward):
if steps and not (is_pass and has_pass[-1]):
steps[-1].extend(span)
has_pass[-1] = has_pass[-1] or is_pass
else:
markers.append(rows[mark])
steps.append(list(span))
has_pass.append(is_pass)
for step in steps:
first = next((i for i, r in enumerate(step) if r["weights"] and r["weights"][0]["name"].startswith(DRAFT)), len(step))
for i, r in enumerate(step):
r["draft"] = i >= first
steps.append(step)
return [rows[i] for i in marks], steps
return markers, steps


def precision(dtype):
Expand Down Expand Up @@ -343,10 +398,17 @@ def window_steps(capture):
return steps


def count_steps(capture, step_rows):
"""Steps in the window for per-step figures: run.json's count, else the forward passes between the
step markers (see split_steps), else whatever window_steps can tell."""
return load_run(capture).get("steps") or len(step_rows or ()) or window_steps(capture)


def report(capture, ceiling, steps, out, peaks=None, sms=None):
rows, unresolved, n_regions = build(capture, ceiling)
run = load_run(capture)
_, step_rows = split_steps(rows) # marks draft launches
steps = steps or count_steps(capture, step_rows)
rows = [r for r in rows if MARKER not in r["name"]]
for step in step_rows or [rows]:
slices = Counter(r["weights"][0]["name"] for r in step if r["weights"])
Expand Down Expand Up @@ -374,11 +436,19 @@ def report(capture, ceiling, steps, out, peaks=None, sms=None):
idle = (span - busy) / steps / 1e6
if idle >= 1 or idle * 1e6 * steps >= 0.02 * span:
findings.append((idle, f"the GPU idles {idle:.2f} ms per step between kernels (Step)"))
wait = waiting(rows)
wait_ms = wait / steps / 1e6
if wait_ms >= 0.5:
findings.append((wait_ms, f"the GPU waits {wait_ms:.2f} ms per step in collectives with no other kernel "
"running, for data from another GPU (Collectives)"))
emit("## Step\n")
emit("| | per step |\n|---|---|")
emit(f"| wall time (first launch to last) | {span / steps / 1e6:.2f} ms |")
emit(f"| GPU busy | {busy / steps / 1e6:.2f} ms |")
emit(f"| idle between kernels | {(span - busy) / steps / 1e6:.2f} ms ({(span - busy) / span * 100:.1f}%) |")
if wait:
emit(f"| waiting in collectives (part of busy) | {wait_ms:.2f} ms |")
busy -= wait # the bandwidth below is over the time the GPU computed
emit(f"| launches | {len(rows) / steps:.0f} |")
emit(f"| weight bytes streamed | {weight_total / steps / 1e9:.2f} GB |")
emit(f"| activation bytes of linear layers | {(total_bytes - weight_total) / steps / 1e9:.2f} GB |")
Expand Down Expand Up @@ -490,6 +560,7 @@ def report(capture, ceiling, steps, out, peaks=None, sms=None):
emit("Partial reads (too short to stream the whole tensor, not counted above): "
+ ", ".join(f"`{n}` ×{c / steps:.1f}/step" for n, c in gathered.most_common(5)) + "\n")

collectives(rows, steps, pretty, emit)
if sms:
for alone_ms, name, grid, gbps in underfilled(rows, steps, sms, pretty, emit):
# A launch streaming near the ceiling loses little to idle SMs; otherwise count their share.
Expand Down Expand Up @@ -537,14 +608,34 @@ def alone(rows):
last = t


def collectives(rows, steps, pretty, emit):
"""NCCL kernels by name: what the worker spent moving data to and from other GPUs. A collective is
one block that spins until its peer's data is there, so its time is mostly another rank's: "alone"
is the part during which this GPU did nothing else."""
groups = defaultdict(list)
for r in rows:
if is_collective(r):
groups[r["name"]].append(r)
if not groups:
return
alone(rows)
emit("## Collectives\n")
emit("| kernel | launches/step | median us | ms/step | alone ms/step |")
emit("|---|---|---|---|---|")
for name, rs in sorted(groups.items(), key=lambda kv: -sum(r["alone"] for r in kv[1])):
emit(f"| `{short(pretty[name], 60)}` | {len(rs) / steps:.1f} | {statistics.median(r['us'] for r in rs):.1f} | "
f"{sum(r['us'] for r in rs) / steps / 1e3:.2f} | {sum(r['alone'] for r in rs) / steps / 1e3:.2f} |")
emit("")


def underfilled(rows, steps, sms, pretty, emit):
"""Launches with fewer blocks than SMs: whatever their occupancy, some SMs sit idle. That costs a
compute-bound kernel time; a bandwidth-bound one may still saturate memory with fewer SMs, so read
it with the launch's bandwidth. "alone" is the time no other kernel ran next to it."""
alone(rows)
groups = defaultdict(list)
for r in rows:
if math.prod(r["grid"]) < sms:
if math.prod(r["grid"]) < sms and not is_collective(r): # a collective is one block by design
groups[(r["name"], r["grid"])].append(r)
found = sorted(((sum(r["alone"] for r in rs) / steps / 1e3, k, rs) for k, rs in groups.items()), key=lambda x: -x[0])
found = [f for f in found if f[0] >= 0.05]
Expand Down Expand Up @@ -617,8 +708,7 @@ def main():
ap.add_argument("--sms", type=int, default=None, help="SM count (default: run.json)")
ap.add_argument("--out", default=None)
a = ap.parse_args()
steps = a.steps or window_steps(a.capture)
report(a.capture, a.ceiling_gbps, steps, a.out, parse_peaks(a.peak_tflops), a.sms)
report(a.capture, a.ceiling_gbps, a.steps, a.out, parse_peaks(a.peak_tflops), a.sms)


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions ledger/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
def groups(capture, ceiling):
rows, _, _ = A.build(capture, ceiling)
run = A.load_run(capture)
A.split_steps(rows)
_, step_rows = A.split_steps(rows)
rows = [r for r in rows if A.MARKER not in r["name"]]
steps = A.window_steps(capture)
steps = A.count_steps(capture, step_rows)
out = defaultdict(list)
for r in rows:
# Only a streamed weight names a group: a small tensor (a scale) can be hit by a stray word, and
Expand Down
Loading
Loading