diff --git a/CHANGELOG.md b/CHANGELOG.md index cb557e9..ace0af5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +- Multi-GPU `vllm serve` captures (tensor and pipeline parallelism): `ledger report` writes one report + per GPU worker under `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.` 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 [--device ]` 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). diff --git a/README.md b/README.md index 6b3f01f..ca8c89f 100644 --- a/README.md +++ b/README.md @@ -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 `/report.md` (`analyze` + `steps`) and `/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)). | @@ -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-/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. @@ -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 diff --git a/capture/Makefile b/capture/Makefile index 906c8bb..c3288a6 100644 --- a/capture/Makefile +++ b/capture/Makefile @@ -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. 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 diff --git a/capture/ledger_cupti.cc b/capture/ledger_cupti.cc index ff7502f..a21783b 100644 --- a/capture/ledger_cupti.cc +++ b/capture/ledger_cupti.cc @@ -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[] = { diff --git a/docs/quickstart.md b/docs/quickstart.md index bd91241..5ba426b 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -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 `) 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 @@ -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-/report.md`; `analyze`, `steps`, `perfetto`, `transfers` and `diff` take those +`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 diff --git a/docs/reading-reports.md b/docs/reading-reports.md index fb4f626..ffc52a7 100644 --- a/docs/reading-reports.md +++ b/docs/reading-reports.md @@ -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 @@ -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 diff --git a/ledger/analyze.py b/ledger/analyze.py index 25abfc8..1e96333 100644 --- a/ledger/analyze.py +++ b/ledger/analyze.py @@ -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-/, 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)) @@ -219,10 +237,33 @@ 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.") @@ -230,18 +271,32 @@ def busy_and_gaps(rows): 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): @@ -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"]) @@ -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 |") @@ -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. @@ -537,6 +608,26 @@ 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 @@ -544,7 +635,7 @@ def underfilled(rows, steps, sms, pretty, emit): 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] @@ -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__": diff --git a/ledger/diff.py b/ledger/diff.py index 6ddfbd4..4bbfc8b 100644 --- a/ledger/diff.py +++ b/ledger/diff.py @@ -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 diff --git a/ledger/profile.py b/ledger/profile.py index 23300ed..eeadf34 100644 --- a/ledger/profile.py +++ b/ledger/profile.py @@ -5,6 +5,7 @@ from contextlib import redirect_stdout import fcntl from hashlib import sha256 +import importlib.util from io import StringIO import os from pathlib import Path @@ -12,7 +13,7 @@ import subprocess import sys -from ledger import ceilings, perfetto +from ledger import analyze, ceilings, perfetto from ledger.cli import call_main, report_ceilings CAPTURE_SOURCES = ("Makefile", "ledger_cupti.cc") @@ -30,8 +31,17 @@ def _find_first(env_name, candidates, filename_glob): return None +def _wheel_dirs(leaf): + """`include` or `lib` directories of pip-installed NVIDIA wheels (nvidia/cu13, nvidia/cuda_cupti, ...). + An image built around a wheel-installed torch often has nvcc but no CUPTI in its toolkit.""" + spec = importlib.util.find_spec("nvidia") + roots = list(spec.submodule_search_locations or ()) if spec else [] + return [directory for root in roots for directory in sorted(Path(root).glob(f"*/{leaf}"))] + + def _check_build_prereqs(group, cuda_root): - """Fail early with an actionable message if make, C++ compiler, CUPTI, or Sanitizer is missing.""" + """Fail early with an actionable message if make, C++ compiler, CUPTI, or Sanitizer is missing. + Returns the make variables for what was found outside the toolkit's own layout.""" if not shutil.which("make"): raise SystemExit("ledger: cannot find 'make' on PATH. Install GNU make to build Ledger.") cxx = os.getenv("CXX") or "c++" @@ -39,18 +49,23 @@ def _check_build_prereqs(group, cuda_root): raise SystemExit(f"ledger: cannot find C++ compiler '{cxx}'. Install g++ or set CXX=.") if group == "capture": - inc_candidates = [cuda_root / "extras/CUPTI/include", *sorted(cuda_root.glob("targets/*/include"))] - if not _find_first("CUPTI_INC", inc_candidates, "cupti.h"): + inc_candidates = [cuda_root / "extras/CUPTI/include", *sorted(cuda_root.glob("targets/*/include")), + *_wheel_dirs("include")] + inc = _find_first("CUPTI_INC", inc_candidates, "cupti.h") + if not inc: raise SystemExit( - f"ledger: cannot find CUPTI headers (cupti.h) under {cuda_root}. " + f"ledger: cannot find CUPTI headers (cupti.h) under {cuda_root} or in the nvidia wheels. " "Install the CUDA CUPTI development package or set CUPTI_INC=." ) - lib_candidates = [cuda_root / "extras/CUPTI/lib64", *sorted(cuda_root.glob("targets/*/lib"))] - if not _find_first("CUPTI_LIB", lib_candidates, "libcupti.so*"): + lib_candidates = [cuda_root / "extras/CUPTI/lib64", *sorted(cuda_root.glob("targets/*/lib")), + *_wheel_dirs("lib")] + lib = _find_first("CUPTI_LIB", lib_candidates, "libcupti.so*") + if not lib: raise SystemExit( - f"ledger: cannot find CUPTI libraries (libcupti.so) under {cuda_root}. " + f"ledger: cannot find CUPTI libraries (libcupti.so) under {cuda_root} or in the nvidia wheels. " "Install the CUDA CUPTI package or set CUPTI_LIB=." ) + return (f"CUPTI_INC={inc}", f"CUPTI_LIB={lib}") elif group == "access": san = Path(os.getenv("SANITIZER") or (cuda_root / "compute-sanitizer")).expanduser() if not (san / "include/sanitizer.h").is_file() or not any(san.glob("libsanitizer-public.so*")): @@ -58,6 +73,7 @@ def _check_build_prereqs(group, cuda_root): f"ledger: cannot find Compute Sanitizer headers/libraries under {san}. " "Install CUDA Compute Sanitizer or set SANITIZER=." ) + return () def _format_build_failure(group, cuda_root, result): @@ -67,6 +83,8 @@ def _format_build_failure(group, cuda_root, result): ("cupti.h", "missing CUPTI headers; set CUPTI_INC= or CUDA_HOME="), ("-lcupti", "missing libcupti; set CUPTI_LIB= or CUDA_HOME="), ("-lcuda", "missing CUDA driver library (libcuda); check LIBRARY_PATH or driver stubs"), + ("libcuda.so.1", "missing CUDA driver library (libcuda.so.1); build where the driver is visible, " + "or set CUDA_SO= or LIBRARY_PATH"), ("sanitizer.h", "missing Compute Sanitizer headers; set SANITIZER="), ("-lsanitizer-public", "missing Compute Sanitizer library; set SANITIZER="), ] @@ -83,7 +101,7 @@ def _format_build_failure(group, cuda_root, result): def build_library(group, sources, targets, compiler, *flags): """Build once for these sources and CUDA toolkit, publishing only complete targets.""" cuda_root = compiler.parents[1] - _check_build_prereqs(group, cuda_root) + flags = (*flags, *_check_build_prereqs(group, cuda_root)) source = ceilings.source_dir(group) inputs = [(name, (source / name).read_bytes()) for name in sources] config = (str(compiler), compiler.stat().st_mtime_ns, flags, [os.getenv(name) for name in BUILD_VARIABLES]) @@ -178,6 +196,29 @@ def capture(opts, vllm_args, library, out): raise SystemExit(f"ledger: vLLM exited with status {result.returncode}. Log: {log}\n{tail}") +def split_processes(capture_dir): + """A capture of several GPU workers, one directory per process: pid-/ with links to that + process's files and to the files they share (run.json). Empty for a capture of one process.""" + pids = analyze.processes(str(capture_dir)) + if len(pids) < 2: + return [] + owned = {pid: [path for path in capture_dir.iterdir() if path.is_file() and path.stem.endswith(f"-{pid}")] + for pid in pids} + claimed = {path for paths in owned.values() for path in paths} + shared = [path for path in capture_dir.iterdir() + if path.is_file() and path.suffix in (".json", ".jsonl") and path not in claimed] + parts = [] + for pid in pids: + part = capture_dir / f"pid-{pid}" + part.mkdir(exist_ok=True) + for path in (*owned[pid], *shared): + link = part / path.name + if not link.exists(): + link.symlink_to(Path("..") / path.name) + parts.append(part) + return parts + + def write_report(capture_dir, report, bandwidth, peaks): """Combine the launch analysis and step breakdown in one Markdown report.""" common = [str(capture_dir), "--ceiling-gbps", str(bandwidth)] @@ -199,9 +240,14 @@ def report_main(args): parser.add_argument("--peak-tflops", help="measured peaks per precision, e.g. bf16=91,fp8=181 (default: GPU cache)") opts = parser.parse_args(args) capture_dir = opts.capture.resolve() - report = (opts.out or capture_dir / "report.md").resolve() bandwidth, peaks = report_ceilings("analyze", [capture_dir], opts.ceiling_gbps, opts.peak_tflops) - print(write_report(capture_dir, report, bandwidth, peaks)) + parts = split_processes(capture_dir) + if parts and opts.out: + parser.error(f"{capture_dir} holds {len(parts)} processes, each with its own report: omit --out") + for part in parts: + print(write_report(part, part / "report.md", bandwidth, peaks)) + if not parts: + print(write_report(capture_dir, (opts.out or capture_dir / "report.md").resolve(), bandwidth, peaks)) def main(args): diff --git a/ledger/vllm_plugin.py b/ledger/vllm_plugin.py index 2555f08..1fd8898 100644 --- a/ledger/vllm_plugin.py +++ b/ledger/vllm_plugin.py @@ -8,6 +8,10 @@ LEDGER_OUT=out LEDGER_GRAPH_WINDOW=: LD_PRELOAD=/capture/libledger.so \\ vllm serve ... +With more than one GPU, vLLM forks its workers by default and a forked worker records nothing (CUPTI's +threads do not survive fork()): set VLLM_WORKER_MULTIPROC_METHOD=spawn. Each worker then writes its own +files, and `ledger report` writes one report per worker. + The window is counted in graph launches (LEDGER_GRAPH_WINDOW); send load while it is open. run.json has no fixed batch or step count here: the analysis counts steps from the markers, and the batch of a serving step varies, so the compute section (which needs M) only fits steps of a known shape. @@ -16,6 +20,7 @@ import functools import json import os +import sys def register(): @@ -27,6 +32,10 @@ def register(): if getattr(Worker, "_ledger_patched", False): # plugins can load more than once per process return Worker._ledger_patched = True + started = os.environ.get("LEDGER_INIT_PID") # set by the capture library where it started CUPTI + if started and started != str(os.getpid()): + print(f"ledger: worker {os.getpid()} was forked from {started}, where the capture library started, and " + "will record nothing: set VLLM_WORKER_MULTIPROC_METHOD=spawn", file=sys.stderr) warm_up, execute = Worker.compile_or_warm_up_model, Worker.execute_model @functools.wraps(warm_up) diff --git a/ledger/vllm_regions.py b/ledger/vllm_regions.py index a58674d..6e1ea7a 100644 --- a/ledger/vllm_regions.py +++ b/ledger/vllm_regions.py @@ -10,6 +10,14 @@ from pathlib import Path +def linear_widths(layer): + """Input and output width of this rank's slice of a linear layer. A layer that is not split across + ranks (ReplicatedLinear) only has its full widths.""" + k = getattr(layer, "input_size_per_partition", None) or getattr(layer, "input_size", None) + n = getattr(layer, "output_size_per_partition", None) or getattr(layer, "output_size", None) + return k, n + + def dump_regions(worker, out_dir): import torch @@ -57,7 +65,9 @@ def add(kind, name, t): widths = {} for mod_name, mod in model.named_modules(): if isinstance(mod, LinearBase): - k, n = mod.input_size_per_partition, mod.output_size_per_partition + k, n = linear_widths(mod) + if not (k and n): + continue for p_name, _ in mod.named_parameters(recurse=False): widths[f"{mod_name}.{p_name}" if mod_name else p_name] = (k, n) for r in regions: diff --git a/tests/test_build.py b/tests/test_build.py index 6be40bf..d771afd 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -19,6 +19,7 @@ def test_build_missing_cupti_headers_gives_clear_hint(tmp_path, monkeypatch): monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) monkeypatch.delenv("CUPTI_INC", raising=False) monkeypatch.delenv("CUPTI_LIB", raising=False) + monkeypatch.setattr(profile, "_wheel_dirs", lambda leaf: []) # the test machine may have the wheels nvcc = _fake_nvcc(tmp_path) with pytest.raises(SystemExit) as exc: @@ -32,6 +33,7 @@ def test_build_missing_cupti_lib_gives_clear_hint(tmp_path, monkeypatch): monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) monkeypatch.delenv("CUPTI_INC", raising=False) monkeypatch.delenv("CUPTI_LIB", raising=False) + monkeypatch.setattr(profile, "_wheel_dirs", lambda leaf: []) # the test machine may have the wheels nvcc = _fake_nvcc(tmp_path) inc = tmp_path / "cuda" / "extras" / "CUPTI" / "include" inc.mkdir(parents=True) @@ -77,3 +79,30 @@ def fake_run(*_args, **_kwargs): msg = str(exc.value) assert "libcuda" in msg assert "LIBRARY_PATH" in msg + + +def test_build_finds_cupti_in_nvidia_wheels(tmp_path, monkeypatch): + """A wheel-installed CUDA keeps CUPTI under site-packages/nvidia//{include,lib} with only the + versioned library name; the build passes both directories to make.""" + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) + monkeypatch.delenv("CUPTI_INC", raising=False) + monkeypatch.delenv("CUPTI_LIB", raising=False) + nvcc = _fake_nvcc(tmp_path) + wheel = tmp_path / "site-packages" / "nvidia" / "cu13" + (wheel / "include").mkdir(parents=True) + (wheel / "lib").mkdir() + (wheel / "include" / "cupti.h").write_text("// stub\n") + (wheel / "lib" / "libcupti.so.13").write_text("") + spec = type("Spec", (), {"submodule_search_locations": [str(wheel.parent)]})() + monkeypatch.setattr(profile.importlib.util, "find_spec", lambda name: spec if name == "nvidia" else None) + commands = [] + + def fake_run(command, **_kwargs): + commands.append(command) + (profile.Path(command[command.index("-C") + 1]) / "libledger.so").write_text("") + return subprocess.CompletedProcess(command, 0, stdout="", stderr="") + + monkeypatch.setattr(subprocess, "run", fake_run) + assert profile.build_capture(nvcc).name == "libledger.so" + assert f"CUPTI_INC={wheel / 'include'}" in commands[0] + assert f"CUPTI_LIB={wheel / 'lib'}" in commands[0] diff --git a/tests/test_multi_gpu.py b/tests/test_multi_gpu.py new file mode 100644 index 0000000..9d29ff4 --- /dev/null +++ b/tests/test_multi_gpu.py @@ -0,0 +1,96 @@ +"""Tests for captures of multi-GPU runs: one process per GPU worker, pipeline-parallel step markers and +NCCL collectives.""" + +import json +import shutil +from types import SimpleNamespace + +import pytest + +from ledger import analyze, profile +from ledger.vllm_regions import linear_widths +from report import section, table_rows + +WEIGHT = [{"name": "layers.0.weight"}] + + +def row(name, start, end, weights=(), partial=()): + return {"name": name, "start": start, "end": end, "us": (end - start) / 1e3, "grid": (1, 1, 1), + "weights": list(weights), "partial": list(partial)} + + +def test_busy_and_gaps_span_ends_at_the_last_kernel_to_finish(): + """A launch that starts early and outlasts the last one to start (a collective) ends the span.""" + rows = [row("wait", 0, 1000), row("a", 100, 200), row("b", 300, 400)] + span, busy = analyze.busy_and_gaps(rows) + assert (span, busy) == (1000, 1000) + + +def test_waiting_counts_only_time_with_nothing_but_collectives(): + rows = [row("ncclDevKernel_Broadcast_RING_LL", 0, 1000), row("gemm", 100, 300), row("gemm", 2000, 2500)] + assert analyze.waiting(rows) == 800 + assert analyze.waiting([r for r in rows if r["name"] == "gemm"]) == 0 + + +def test_split_steps_folds_markers_without_a_forward_pass(): + """Pipeline parallelism steps a worker for batches at other stages: those markers are not steps, + and what they launched (a collective) joins the forward pass before them.""" + rows = [ + row(analyze.MARKER, 0, 1), + row("gemm", 10, 20, WEIGHT), + row(analyze.MARKER, 30, 31), + row("ncclDevKernel_SendRecv", 40, 50), + row(analyze.MARKER, 60, 61), + row(analyze.MARKER, 70, 71), + row("gather", 80, 90, partial=["embed.weight"]), + row("gemm", 91, 99, WEIGHT), + ] + markers, steps = analyze.split_steps(rows) + assert [m["start"] for m in markers] == [0, 70] + assert [[r["name"] for r in step] for step in steps] == [["gemm", "ncclDevKernel_SendRecv"], ["gather", "gemm"]] + + +def test_split_steps_keeps_every_marker_without_a_memory_map(): + rows = [row(analyze.MARKER, 0, 1), row("k", 10, 20), row(analyze.MARKER, 30, 31), row("k", 40, 50)] + markers, steps = analyze.split_steps(rows) + assert len(markers) == len(steps) == 2 + + +def test_linear_widths_fall_back_to_full_widths(): + """vLLM's ReplicatedLinear has no per-partition widths.""" + assert linear_widths(SimpleNamespace(input_size_per_partition=8, output_size_per_partition=4)) == (8, 4) + assert linear_widths(SimpleNamespace(input_size=16, output_size=2)) == (16, 2) + assert linear_widths(SimpleNamespace()) == (None, None) + + +@pytest.fixture +def two_workers(captures, tmp_path): + """decode-q38 twice under different pids, as two GPU workers would leave it.""" + capture = tmp_path / "two-workers" + shutil.copytree(captures / "decode-q38", capture) + pid = analyze.processes(str(capture))[0] + for path in list(capture.iterdir()): + if path.stem.endswith(f"-{pid}"): + shutil.copy(path, path.with_name(path.name.replace(f"-{pid}.", "-999999."))) + return capture, pid + + +def test_loading_several_processes_as_one_is_refused(two_workers): + capture, pid = two_workers + assert analyze.processes(str(capture)) == sorted([pid, "999999"]) + with pytest.raises(SystemExit) as exc: + analyze.load(str(capture)) + assert "ledger report" in str(exc.value) + + +def test_report_writes_one_report_per_process(two_workers, capsys): + capture, pid = two_workers + profile.report_main([str(capture), "--ceiling-gbps", "252"]) + capsys.readouterr() + reports = [capture / f"pid-{p}" / "report.md" for p in (pid, "999999")] + texts = [path.read_text() for path in reports] + assert texts[0].replace(f"pid-{pid}", "") == texts[1].replace("pid-999999", "") + assert dict(table_rows(section(texts[0], "Step")))["launches"] + assert json.loads((capture / f"pid-{pid}" / "run.json").read_text())["batch"] == 1 + with pytest.raises(SystemExit): + profile.report_main([str(capture), "--ceiling-gbps", "252", "--out", str(capture / "one.md")])