From 25e45c9df10a0bf4b9625a870b1c5088f86feeb2 Mon Sep 17 00:00:00 2001 From: 0chencc <19362246+0Chencc@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:55:26 +0900 Subject: [PATCH 1/2] Add Huawei Ascend CANN msprof + aclGraph capture importer Add ledger ascend-import (ledger/ascend.py) to convert CANN msprof exports (op_summary_*.csv and task_time_*.csv), aclmdlRIDebugPrint graph dumps, and weight/KV descriptor maps into standard Ledger capture directories so analyze, transfers, diff, and perfetto work on Ascend NPU traces. Also extend analyze.py and ceilings.py to recognize int8/int4 quantized weights and draft.* prefixes, and add unit and end-to-end tests in tests/test_ascend.py. --- README.md | 1 + docs/quickstart.md | 19 ++ ledger/analyze.py | 8 +- ledger/ascend.py | 445 +++++++++++++++++++++++++++++++++++++++++++ ledger/ceilings.py | 2 +- ledger/cli.py | 3 + tests/test_ascend.py | 191 +++++++++++++++++++ 7 files changed, 666 insertions(+), 3 deletions(-) create mode 100644 ledger/ascend.py create mode 100644 tests/test_ascend.py diff --git a/README.md b/README.md index fc5beb0..788198e 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ See [docs/quickstart.md](docs/quickstart.md) for the full walkthrough (including | `ledger sass` | Look up the SASS instruction behind a dead store from a cubin directory, function, and PC offset. | | `ledger perturb-plan` / `perturb-report` | Generate and summarize replay memory-poisoning experiments (e.g. Sibyl `replay_perturb`). | | `ledger sibyl-regions` | Convert a Sibyl recording's address ranges into Ledger's `regions-*.json` memory map. | +| `ledger ascend-import` | Convert Huawei Ascend CANN `msprof` + `aclGraph` dumps and weight/KV maps into a Ledger capture. | ## Documentation diff --git a/docs/quickstart.md b/docs/quickstart.md index 0d3889d..6f74364 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -174,3 +174,22 @@ For a [Sibyl](https://github.com/GeetoRinku/sibyl) replay, which preserves recor ledger sibyl-regions /ranges-rank0-.json out LD_PRELOAD=$(ledger build) LEDGER_OUT=out LEDGER_GRAPH_WINDOW=8:44 ... ``` + +--- + +## Huawei Ascend CANN (`msprof` + `aclGraph`) + +To analyze an Ascend NPU run exported with `msprof --export=on`, import its `op_summary_*.csv` +(and optional `task_time_*.csv`), `aclmdlRIDebugPrint` graph dumps (`--graph`), and weight / KV +descriptor maps (`--weights`, `--draft-weights`, `--owners`, or `--regions`): + +```sh +ledger ascend-import out \ + --graph capture.json --graph draft-graph.json \ + --weights target_weights.json --draft-weights draft_weights.json --owners owners.json \ + --device "Ascend 910B1" --sms 24 --steps 1 --batch 8 --draft-tokens 7 + +ledger analyze out --ceiling-gbps 1350 --peak-tflops bf16=320,int8=640 --out out/report.md +ledger transfers out --steps 1 --out out/transfers.md +ledger perfetto out --ceiling-gbps 1350 --out out/trace.json +``` diff --git a/ledger/analyze.py b/ledger/analyze.py index 330804f..7be446f 100644 --- a/ledger/analyze.py +++ b/ledger/analyze.py @@ -224,7 +224,7 @@ def busy_and_gaps(rows): 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 = ("speculator.", "drafter.", "spec_decode_model.", "draft.") def split_steps(rows): @@ -252,6 +252,10 @@ def precision(dtype): return "bf16", 1 if dtype == "uint8": return "fp4", 2 + if dtype == "int8": + return "int8", 1 + if dtype == "int4": + return "int4", 2 return dtype, 1 @@ -275,7 +279,7 @@ def gemm_flops(r, run): return cls, m, 2 * m * elements -ACT_BYTES = {"fp8": 1, "bf16": 2, "fp4": 0.5} # input activation element, by the weight's compute class +ACT_BYTES = {"fp8": 1, "bf16": 2, "fp4": 0.5, "int8": 1, "int4": 1} # input activation element, by the weight's compute class def act_bytes(r, run): diff --git a/ledger/ascend.py b/ledger/ascend.py new file mode 100644 index 0000000..5a63be3 --- /dev/null +++ b/ledger/ascend.py @@ -0,0 +1,445 @@ +"""Import Huawei Ascend CANN msprof + aclGraph traces into a Ledger capture directory. + + python -m ledger.ascend \\ + [--graph capture.json ...] [--weights target_weights.json ...] \\ + [--draft-weights draft_weights.json ...] [--owners owners.json ...] \\ + [--regions regions.json ...] [--stream-map 23:18 ...] \\ + [--device "Ascend 910B1"] [--sms 24] [--steps 1] [--batch 1] [--draft-tokens 0] [--prefill 0] + +CANN `msprof --export=on` writes `op_summary_*.csv` (per-task hardware timestamps, stream/task IDs, +block counts) and `task_time_*.csv` (including `MEMCPY_ASYNC` transfers). When an aclGraph debug +dump (`aclmdlRIDebugPrint`) is also provided, launches are joined by `(Stream ID, Task ID)` to +recover the exact 64-bit device pointer arguments (`Kernel Args`) for every AI Core, AI Vector, and +HCCL AIV task. Combining that with named weight and KV-cache maps (such as Sibyl's `kv-census` +descriptors or existing Ledger `regions-*.json`) lets `ledger analyze`, `ledger transfers`, +`ledger diff`, and `ledger perfetto` account for Ascend runs identically to CUDA captures. +""" + +import argparse +import csv +import glob +import json +import os +import struct + +from ledger import analyze as A +from ledger import sibyl_regions + +# CUPTI_ACTIVITY_MEMCPY_KIND_DTOD; used for device async copies when msprof does not record direction. +_MEMCPY_DTOD = 8 + + +def _find_csv(source, prefix): + """Locate an msprof CSV inside a PROF_* tree, mindstudio_profiler_output, or direct file.""" + if os.path.isfile(source): + return source if os.path.basename(source).startswith(prefix) else None + patterns = ( + os.path.join(source, f"{prefix}_*.csv"), + os.path.join(source, "mindstudio_profiler_output", f"{prefix}_*.csv"), + os.path.join(source, "PROF_*", "mindstudio_profiler_output", f"{prefix}_*.csv"), + ) + for pattern in patterns: + matches = sorted(glob.glob(pattern)) + if matches: + return matches[-1] + return None + + +def _parse_us_ns(text): + """Parse an msprof microsecond timestamp/duration string (which may carry a trailing tab) to ns.""" + text = (text or "").strip() + if not text or text == "N/A": + return None + try: + return round(float(text) * 1000.0) + except ValueError: + return None + + +def _parse_int(text, default=0): + text = (text or "").strip() + if not text or text == "N/A": + return default + try: + return int(float(text)) + except ValueError: + return default + + +def parse_kernel_args(text): + """Encode space-separated hex words from aclmdlRIDebugPrint `Kernel Args` as Ledger params.""" + words = [] + for tok in (text or "").split(): + try: + words.append(int(tok, 16) & 0xFFFFFFFFFFFFFFFF) + except ValueError: + continue + if not words: + return [] + raw = struct.pack(f"<{len(words)}Q", *words) + return [[0, len(raw), raw.hex()]] + + +def load_acl_graphs(paths, stream_map=None): + """Load aclmdlRIDebugPrint JSON dumps into a `(stream_id, task_id) -> node` lookup.""" + by_st = {} + for path in paths: + events = json.load(open(path)) + for ev in events: + if not isinstance(ev, dict): + continue + args = ev.get("args") or {} + if "Stream Id" not in args or "Task Id" not in args: + continue + ka = args.get("Kernel Args") + if not ka: + continue + params = parse_kernel_args(ka) + if not params: + continue + stream_id = int(args["Stream Id"]) + task_id = int(args["Task Id"]) + by_st[(stream_id, task_id)] = { + "name": ev.get("name", ""), + "blocks": int(args.get("Numblocks") or 1), + "params": params, + } + if stream_map: + for runtime_stream, graph_stream in stream_map.items(): + for (gs, tid), node in list(by_st.items()): + if gs == graph_stream and (runtime_stream, tid) not in by_st: + by_st[(runtime_stream, tid)] = node + return by_st + + +def _region_entry(kind, name, info): + addr = info.get("address", info.get("addr")) + size = info.get("bytes", info.get("size", 0)) + if addr is None or not size or size <= 0: + return None + dtype = str(info.get("dtype", "")).removeprefix("torch.") + shape = list(info.get("shape") or []) + entry = { + "kind": kind, + "name": name, + "addr": int(addr), + "size": int(size), + "shape": shape, + "dtype": dtype, + } + if kind == "weight" and len(shape) == 2 and all(isinstance(d, int) and d > 0 for d in shape): + entry["out_features"] = shape[0] + entry["in_features"] = shape[1] + return entry + + +def load_regions(weight_paths=(), draft_weight_paths=(), owner_paths=(), region_paths=()): + """Build Ledger regions from Ascend kv-census JSONs and/or existing region files.""" + regions = [] + seen = set() + + def add(entry): + if entry is None: + return + key = (entry["kind"], entry["addr"], entry["size"], entry["name"]) + if key not in seen: + seen.add(key) + regions.append(entry) + + for path in weight_paths: + data = json.load(open(path)) + for name, info in data.items(): + if isinstance(info, dict): + add(_region_entry("weight", name, info)) + + for path in draft_weight_paths: + data = json.load(open(path)) + for name, info in data.items(): + if isinstance(info, dict): + prefixed = name if name.startswith(A.DRAFT) else f"draft.{name}" + add(_region_entry("weight", prefixed, info)) + + for path in owner_paths: + data = json.load(open(path)) + for name, items in data.items(): + if isinstance(items, list): + for idx, info in enumerate(items): + if isinstance(info, dict): + label = name if len(items) == 1 else f"{name}[{idx}]" + add(_region_entry("cache", label, info)) + elif isinstance(items, dict): + add(_region_entry("cache", name, items)) + + for path in region_paths: + data = json.load(open(path)) + if isinstance(data, list) and data and isinstance(data[0], list): + for entry in sibyl_regions.convert(data): + add(entry) + elif isinstance(data, list): + for entry in data: + if isinstance(entry, dict): + add(entry) + + return regions + + +def _load_op_summary(csv_path): + """Read msprof op_summary CSV, deduplicating paired `Stream ID == N/A` HCCL summary rows. + + CANN msprof emits a high-level `Stream ID = N/A` COMMUNICATION row for every collective. + For AIV-expanded collectives that row duplicates a device `AivKernel` row with the same + timestamp and duration; for SDMA/RDMA collectives only the `N/A` row exists. We enrich + paired `AivKernel` rows with the collective name and retain unmatched `N/A` collectives on + a dedicated virtual stream (-1) so they are neither double-counted nor silently dropped. + """ + raw_rows = list(csv.DictReader(open(csv_path, newline=""))) + na_rows = {} + device_rows = [] + for idx, row in enumerate(raw_rows): + stream_text = (row.get("Stream ID") or "").strip() + start_ns = _parse_us_ns(row.get("Task Start Time(us)")) + dur_ns = _parse_us_ns(row.get("Task Duration(us)")) + if start_ns is None or dur_ns is None or dur_ns <= 0: + continue + model_id = (row.get("Model ID") or "").strip() + if stream_text in ("", "N/A"): + key = (model_id, start_ns // 1000, dur_ns // 1000) + na_rows.setdefault(key, []).append((idx, row, start_ns, dur_ns)) + continue + device_rows.append((row, start_ns, dur_ns)) + + out = [] + matched_na = set() + for row, start_ns, dur_ns in device_rows: + model_id = (row.get("Model ID") or "").strip() + stream_id = _parse_int(row.get("Stream ID")) + task_id = _parse_int(row.get("Task ID")) + op_name = (row.get("Op Name") or "").strip() + task_type = (row.get("Task Type") or "").strip() + if op_name in ("", "AivKernel", "N/A"): + key = (model_id, start_ns // 1000, dur_ns // 1000) + bucket = na_rows.get(key) + if bucket: + na_idx, na_row, _, _ = bucket.pop(0) + matched_na.add(na_idx) + enriched = (na_row.get("Op Name") or "").strip() + if enriched: + op_name = enriched + block_num = _parse_int(row.get("Block Num"), 0) + mix_blocks = _parse_int(row.get("Mix Block Num"), 0) + blocks = max(block_num, mix_blocks, 1) + out.append({ + "model_id": model_id, + "stream": stream_id, + "task": task_id, + "name": op_name or task_type or "unknown", + "task_type": task_type, + "start": start_ns, + "end": start_ns + dur_ns, + "blocks": blocks, + }) + + for bucket in na_rows.values(): + for na_idx, row, start_ns, dur_ns in bucket: + if na_idx in matched_na: + continue + op_name = (row.get("Op Name") or "").strip() + task_type = (row.get("Task Type") or "").strip() + out.append({ + "model_id": (row.get("Model ID") or "").strip(), + "stream": -1, + "task": 0, + "name": op_name or task_type or "communication", + "task_type": task_type, + "start": start_ns, + "end": start_ns + dur_ns, + "blocks": max(_parse_int(row.get("Block Num"), 0), 1), + }) + + out.sort(key=lambda r: r["start"]) + return out + + +def _load_memcpys(task_time_csv): + """Extract MEMCPY_ASYNC rows from msprof task_time_*.csv as Ledger memcpy records.""" + if not task_time_csv or not os.path.isfile(task_time_csv): + return [] + memcpys = [] + for idx, row in enumerate(csv.DictReader(open(task_time_csv, newline="")), start=1): + if (row.get("kernel_type") or "").strip() != "MEMCPY_ASYNC": + continue + start_ns = _parse_us_ns(row.get("task_start(us)")) + stop_ns = _parse_us_ns(row.get("task_stop(us)")) + dur_ns = _parse_us_ns(row.get("task_time(us)")) + if start_ns is None: + continue + if stop_ns is None or stop_ns <= start_ns: + if dur_ns is None or dur_ns <= 0: + continue + stop_ns = start_ns + dur_ns + memcpys.append({ + "start": start_ns, + "end": stop_ns, + "bytes": 0, + "kind": _MEMCPY_DTOD, + "src_kind": 3, + "dst_kind": 3, + "stream": _parse_int(row.get("stream_id")), + "node": 0, + "corr": idx, + "rcorr": 0, + }) + return memcpys + + +def import_capture( + source, + out_dir, + graph_paths=(), + weight_paths=(), + draft_weight_paths=(), + owner_paths=(), + region_paths=(), + stream_map=None, + device="Ascend 910B", + sms=24, + steps=1, + batch=1, + draft_tokens=0, + prefill=0, +): + """Convert an Ascend msprof export into a standard Ledger capture directory.""" + op_csv = _find_csv(source, "op_summary") + if not op_csv: + raise SystemExit(f"ledger ascend-import: no op_summary_*.csv found under {source}") + task_csv = _find_csv(source, "task_time") if not os.path.isfile(source) else None + + ops = _load_op_summary(op_csv) + graph_nodes = load_acl_graphs(graph_paths, stream_map=stream_map) + regions = load_regions(weight_paths, draft_weight_paths, owner_paths, region_paths) + memcpys = _load_memcpys(task_csv) + + os.makedirs(out_dir, exist_ok=True) + with open(os.path.join(out_dir, "regions-ascend.json"), "w") as f: + json.dump(regions, f) + + node_ids = {} + next_node_id = 1 + nodes_out = [] + kernels_out = [] + matched = 0 + + for corr, op in enumerate(ops, start=1): + key = (op["stream"], op["task"]) + gnode = graph_nodes.get(key) + node_id = 0 + blocks = op["blocks"] + name = op["name"] + if gnode is not None: + matched += 1 + if key not in node_ids: + node_ids[key] = next_node_id + nodes_out.append({"id": next_node_id, "params": gnode["params"]}) + next_node_id += 1 + node_id = node_ids[key] + if gnode["blocks"] > 0: + blocks = gnode["blocks"] + if name == "AivKernel" or name.startswith("hcom_"): + # Keep collective semantic prefix alongside AIV kernel name when both exist. + name = f"{name}:{gnode['name']}" if name.startswith("hcom_") else gnode["name"] + kernels_out.append({ + "start": op["start"], + "end": op["end"], + "name": name, + "grid": [blocks, 1, 1], + "stream": op["stream"], + "node": node_id, + "corr": corr, + }) + + with open(os.path.join(out_dir, "nodes-0.jsonl"), "w") as f: + for rec in nodes_out: + f.write(json.dumps(rec) + "\n") + with open(os.path.join(out_dir, "kernels-0.jsonl"), "w") as f: + for rec in kernels_out: + f.write(json.dumps(rec) + "\n") + if memcpys: + with open(os.path.join(out_dir, "memcpys-0.jsonl"), "w") as f: + for rec in memcpys: + f.write(json.dumps(rec) + "\n") + + run_meta = { + "device": device, + "backend": "ascend", + "steps": steps, + "batch": batch, + "draft_tokens": draft_tokens, + "prefill": prefill, + "sms": sms, + } + with open(os.path.join(out_dir, "run.json"), "w") as f: + json.dump(run_meta, f, indent=2) + f.write("\n") + + return { + "kernels": len(kernels_out), + "matched_nodes": matched, + "regions": len(regions), + "memcpys": len(memcpys), + } + + +def _parse_stream_maps(specs): + mapping = {} + for spec in specs or (): + for pair in spec.split(","): + pair = pair.strip() + if not pair: + continue + src, dst = pair.split(":", 1) + mapping[int(src)] = int(dst) + return mapping + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("source", help="msprof PROF_* directory, mindstudio_profiler_output dir, or op_summary_*.csv") + ap.add_argument("out", help="output Ledger capture directory") + ap.add_argument("--graph", action="append", default=[], help="aclmdlRIDebugPrint JSON dump (repeatable)") + ap.add_argument("--stream-map", action="append", default=[], + help="map runtime stream IDs to graph dump stream IDs, e.g. 23:18,24:19") + ap.add_argument("--weights", action="append", default=[], help="Ascend target_weights.json descriptor map") + ap.add_argument("--draft-weights", action="append", default=[], help="Ascend draft_weights.json descriptor map") + ap.add_argument("--owners", action="append", default=[], help="Ascend KV/state owners.json descriptor map") + ap.add_argument("--regions", action="append", default=[], help="existing Ledger regions.json or Sibyl ranges.json") + ap.add_argument("--device", default="Ascend 910B", help="Ascend device name written to run.json") + ap.add_argument("--sms", type=int, default=24, help="AI Core count for underfilled-grid accounting (default: 24)") + ap.add_argument("--steps", type=int, default=1, help="steps in the profiled window (default: 1)") + ap.add_argument("--batch", type=int, default=1, help="batch size in run.json") + ap.add_argument("--draft-tokens", type=int, default=0, help="speculative draft tokens per request") + ap.add_argument("--prefill", type=int, default=0, help="prefill token count (0 for decode)") + a = ap.parse_args() + summary = import_capture( + a.source, + a.out, + graph_paths=a.graph, + weight_paths=a.weights, + draft_weight_paths=a.draft_weights, + owner_paths=a.owners, + region_paths=a.regions, + stream_map=_parse_stream_maps(a.stream_map), + device=a.device, + sms=a.sms, + steps=a.steps, + batch=a.batch, + draft_tokens=a.draft_tokens, + prefill=a.prefill, + ) + print( + f"{summary['kernels']} kernels ({summary['matched_nodes']} with aclGraph params), " + f"{summary['regions']} regions, {summary['memcpys']} memcpys -> {a.out}" + ) + + +if __name__ == "__main__": + main() diff --git a/ledger/ceilings.py b/ledger/ceilings.py index 35a697d..eec0fff 100644 --- a/ledger/ceilings.py +++ b/ledger/ceilings.py @@ -63,7 +63,7 @@ def valid_ceiling(data, device): positive(data.get("ceiling_gbps")) and isinstance(peaks, dict) and bool(peaks) - and all(key in {"bf16", "fp8", "fp4"} and positive(value) for key, value in peaks.items()) + and all(key in {"bf16", "fp8", "fp4", "int8", "int4"} and positive(value) for key, value in peaks.items()) ) diff --git a/ledger/cli.py b/ledger/cli.py index afe6ad7..a7c7361 100644 --- a/ledger/cli.py +++ b/ledger/cli.py @@ -23,6 +23,7 @@ "perturb-plan": "Generate replay perturbation experiments", "perturb-report": "Report results of perturbation experiments", "sibyl-regions": "Convert a Sibyl recording's memory map", + "ascend-import": "Convert Ascend CANN msprof + aclGraph traces into a Ledger capture", "build": "Build the CUDA capture libraries", "ceilings": "Measure and cache a GPU's bandwidth and compute ceilings", "profile": "Capture a vLLM run and write its report and timeline", @@ -141,6 +142,8 @@ def main(): return handlers[selected](rest) if selected in REPORT_OPTIONS: rest = report_args(selected, rest) + if selected == "ascend-import": + return call_main("ascend", selected, rest) return call_main(selected.replace("-", "_"), selected, rest) except subprocess.CalledProcessError as error: raise SystemExit(f"ledger: {error}") from error diff --git a/tests/test_ascend.py b/tests/test_ascend.py new file mode 100644 index 0000000..e47089a --- /dev/null +++ b/tests/test_ascend.py @@ -0,0 +1,191 @@ +"""Tests for ledger.ascend: Ascend CANN msprof + aclGraph import and end-to-end Ledger analysis.""" + +import json +import sys + +import pytest + +from ledger import analyze, ascend, cli, perfetto, transfers +from report import section, table_rows + + +def _write_msprof_fixture(root): + """Build a minimal Ascend CANN msprof directory with AIV-expanded and SDMA collectives.""" + out = root / "PROF_000001_test" / "mindstudio_profiler_output" + out.mkdir(parents=True) + + # Op summary: + # - 1 weight-streaming INT8 matmul on stream 33, task 10 (matched by aclGraph) + # - 1 draft BF16 matmul on stream 27, task 5 (matched via --stream-map 27:22) + # - 1 paired AIV collective (Stream ID N/A summary + device AivKernel on stream 31, task 1) + # - 1 unmatched SDMA/RDMA collective (Stream ID N/A only -> kept on virtual stream -1) + op_summary = "\n".join([ + "Device_id,Model ID,Task ID,Stream ID,Op Name,OP Type,OP State,Task Type,Task Start Time(us),Task Duration(us),Task Wait Time(us),Block Num,Mix Block Num", + "0,4294967295,10,33,QuantBatchMatmulV3_int8,QuantBatchMatmulV3,N/A,MIX_AIC,1000.000\t,20.000,0,16,0", + "0,48,N/A,N/A,hcom_allGather__503_1_1,hcom_allGather,N/A,COMMUNICATION,1025.000\t,15.000,0,N/A,N/A", + "0,48,1,31,AivKernel,AivKernel,N/A,COMMUNICATION,1025.000\t,15.000,0,8,0", + "0,4294967295,N/A,N/A,hcom_reduceScatter__503_2_1,hcom_reduceScatter,N/A,COMMUNICATION,1045.000\t,30.000,0,N/A,N/A", + "0,4294967295,5,27,MatMulV2_bf16,MatMulV2,N/A,AI_CORE,1080.000\t,40.000,0,24,0", + ]) + "\n" + (out / "op_summary_20261127.csv").write_text(op_summary) + + task_time = "\n".join([ + "Device_id,kernel_name,kernel_type,stream_id,task_id,task_time(us),task_start(us),task_stop(us)", + "0,N/A,MEMCPY_ASYNC,43,100,5.000,1040.000\t,1045.000\t", + "0,QuantBatchMatmulV3_int8,MIX_AIC,33,10,20.000,1000.000\t,1020.000\t", + ]) + "\n" + (out / "task_time_20261127.csv").write_text(task_time) + + w_addr = 0x12D0_0000_0000 + d_addr = 0x12E0_0000_0000 + c_addr = 0x12F0_0000_0000 + + capture_graph = [ + { + "name": "QuantBatchMatmulV3_int8", + "args": { + "Model Id": 48, + "Stream Id": 33, + "Task Id": 10, + "Numblocks": 16, + "Kernel Args": f"0x{w_addr:016x} 0x{c_addr:016x}", + }, + }, + { + "name": "aiv_all_gather_bfloat16_t", + "args": { + "Model Id": 48, + "Stream Id": 31, + "Task Id": 1, + "Numblocks": 8, + "Kernel Args": "0x000012c000001000 0x0000000000000008", + }, + }, + ] + draft_graph = [ + { + "name": "MatMulV2_bf16", + "args": { + "Model Id": 46, + "Stream Id": 22, + "Task Id": 5, + "Numblocks": 24, + "Kernel Args": f"0x{d_addr:016x}", + }, + } + ] + target_weights = { + "model.layers.0.self_attn.wq_a.weight": { + "dtype": "torch.int8", + "shape": [4096, 1024], + "address": w_addr, + "bytes": 4194304, + } + } + draft_weights = { + "model.layers.43.self_attn.wo_b.weight": { + "dtype": "torch.bfloat16", + "shape": [4096, 2048], + "address": d_addr, + "bytes": 16777216, + } + } + owners = { + "model.layers.0.self_attn.kv_cache": [ + { + "dtype": "torch.bfloat16", + "shape": [1024, 512], + "address": c_addr, + "bytes": 1048576, + } + ] + } + + (root / "capture.json").write_text(json.dumps(capture_graph)) + (root / "draft.json").write_text(json.dumps(draft_graph)) + (root / "target_weights.json").write_text(json.dumps(target_weights)) + (root / "draft_weights.json").write_text(json.dumps(draft_weights)) + (root / "owners.json").write_text(json.dumps(owners)) + return root + + +def test_ascend_import_and_end_to_end_analysis(tmp_path, monkeypatch): + """Importing an Ascend msprof + aclGraph capture feeds analyze, transfers, and perfetto cleanly.""" + src = _write_msprof_fixture(tmp_path / "src") + cap = tmp_path / "capture" + + monkeypatch.setattr( + sys, + "argv", + [ + "ledger", + "ascend-import", + str(src), + str(cap), + "--graph", str(src / "capture.json"), + "--graph", str(src / "draft.json"), + "--stream-map", "27:22", + "--weights", str(src / "target_weights.json"), + "--draft-weights", str(src / "draft_weights.json"), + "--owners", str(src / "owners.json"), + "--device", "Ascend 910B1", + "--sms", "24", + "--steps", "1", + "--batch", "8", + "--draft-tokens", "7", + ], + ) + cli.main() + + run = json.loads((cap / "run.json").read_text()) + assert run["device"] == "Ascend 910B1" + assert run["backend"] == "ascend" + assert run["sms"] == 24 + + kernels = [json.loads(line) for line in (cap / "kernels-0.jsonl").read_text().splitlines()] + # Paired AIV collective is deduplicated (4 total kernels, not 5), and unmatched SDMA collective is retained. + assert len(kernels) == 4 + names = [k["name"] for k in kernels] + assert "hcom_allGather__503_1_1:aiv_all_gather_bfloat16_t" in names + assert "hcom_reduceScatter__503_2_1" in names + sdma = [k for k in kernels if k["name"] == "hcom_reduceScatter__503_2_1"][0] + assert sdma["stream"] == -1 + + report_path = tmp_path / "report.md" + analyze.report(str(cap), ceiling=1350, steps=1, out=str(report_path), + peaks=analyze.parse_peaks("bf16=320,int8=640"), sms=24) + text = report_path.read_text() + + weight_rows = {r[0].strip("`"): r for r in table_rows(section(text, "Weight-streaming launches by weight"))} + assert "model.layers.N.self_attn.wq_a.weight" in weight_rows + assert "draft.model.layers.N.self_attn.wo_b.weight" in weight_rows + + compute_rows = {r[0].strip("`"): r for r in table_rows(section(text, "Compute"))} + assert compute_rows["model.layers.N.self_attn.wq_a.weight"][1] == "int8" + assert compute_rows["model.layers.N.self_attn.wq_a.weight"][8] == "memory" + + # Transfers picks up MEMCPY_ASYNC from task_time_*.csv (5 us exposed between 1040..1045 us). + xfer_path = tmp_path / "transfers.md" + with open(xfer_path, "w") as f: + transfers.report(str(cap), {}, steps=1, out=f) + assert "5.0 us of it with no kernel running" in xfer_path.read_text() + + # Perfetto export produces valid Chrome Trace JSON. + trace_path = tmp_path / "trace.json" + perfetto.export(str(cap), ceiling=1350, out=str(trace_path)) + trace = json.loads(trace_path.read_text()) + assert len(trace["traceEvents"]) > 4 + + +def test_parse_kernel_args_ignores_non_hex_tokens(): + params = ascend.parse_kernel_args("0x000012c07ca00000 not_hex 0x10") + assert len(params) == 1 + off, size, raw_hex = params[0] + assert off == 0 and size == 16 + assert int.from_bytes(bytes.fromhex(raw_hex)[:8], "little") == 0x12C07CA00000 + assert int.from_bytes(bytes.fromhex(raw_hex)[8:16], "little") == 0x10 + + +def test_import_capture_missing_op_summary_exits(tmp_path): + with pytest.raises(SystemExit, match="op_summary"): + ascend.import_capture(str(tmp_path), str(tmp_path / "out")) From f04b45d44208816dbbe6e6befeb73008a20ad825 Mon Sep 17 00:00:00 2001 From: ZacharyZcR Date: Sat, 28 Nov 2026 05:45:48 +0800 Subject: [PATCH 2/2] ascend-import: warn on clashing graph dumps, exact timestamps, drop int4 Rename the module to ascend_import so the CLI dispatches it like every other command. Graph dumps that give one (stream, task) pair different kernel args now warn instead of overwriting silently. Timestamps are parsed as decimals: epoch microseconds lose nanoseconds in a float. A malformed --stream-map exits with a message. Document that msprof memcpys carry no size or direction. int4 is not a dtype any capture has produced; remove it until one does. --- docs/quickstart.md | 3 +++ ledger/analyze.py | 4 +--- ledger/{ascend.py => ascend_import.py} | 28 ++++++++++++++++++++------ ledger/ceilings.py | 2 +- ledger/cli.py | 2 -- tests/test_ascend.py | 23 +++++++++++++++++++-- 6 files changed, 48 insertions(+), 14 deletions(-) rename ledger/{ascend.py => ascend_import.py} (93%) diff --git a/docs/quickstart.md b/docs/quickstart.md index 6f74364..e6b521c 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -193,3 +193,6 @@ ledger analyze out --ceiling-gbps 1350 --peak-tflops bf16=320,int8=640 --out out ledger transfers out --steps 1 --out out/transfers.md ledger perfetto out --ceiling-gbps 1350 --out out/trace.json ``` + +msprof does not record the size or direction of `MEMCPY_ASYNC` tasks: `ledger transfers` reports +their times, but the copies are imported with 0 bytes and labelled DtoD. diff --git a/ledger/analyze.py b/ledger/analyze.py index 7be446f..25abfc8 100644 --- a/ledger/analyze.py +++ b/ledger/analyze.py @@ -254,8 +254,6 @@ def precision(dtype): return "fp4", 2 if dtype == "int8": return "int8", 1 - if dtype == "int4": - return "int4", 2 return dtype, 1 @@ -279,7 +277,7 @@ def gemm_flops(r, run): return cls, m, 2 * m * elements -ACT_BYTES = {"fp8": 1, "bf16": 2, "fp4": 0.5, "int8": 1, "int4": 1} # input activation element, by the weight's compute class +ACT_BYTES = {"fp8": 1, "bf16": 2, "fp4": 0.5, "int8": 1} # input activation element, by the weight's compute class def act_bytes(r, run): diff --git a/ledger/ascend.py b/ledger/ascend_import.py similarity index 93% rename from ledger/ascend.py rename to ledger/ascend_import.py index 5a63be3..2ecc62b 100644 --- a/ledger/ascend.py +++ b/ledger/ascend_import.py @@ -1,6 +1,6 @@ """Import Huawei Ascend CANN msprof + aclGraph traces into a Ledger capture directory. - python -m ledger.ascend \\ + python -m ledger.ascend_import \\ [--graph capture.json ...] [--weights target_weights.json ...] \\ [--draft-weights draft_weights.json ...] [--owners owners.json ...] \\ [--regions regions.json ...] [--stream-map 23:18 ...] \\ @@ -13,6 +13,10 @@ HCCL AIV task. Combining that with named weight and KV-cache maps (such as Sibyl's `kv-census` descriptors or existing Ledger `regions-*.json`) lets `ledger analyze`, `ledger transfers`, `ledger diff`, and `ledger perfetto` account for Ascend runs identically to CUDA captures. + +msprof records when a `MEMCPY_ASYNC` task ran but not how many bytes it moved or in which +direction, so the imported copies carry 0 bytes and are all labelled device-to-device: their +times in `ledger transfers` are measured, their MB and GB/s columns are not. """ import argparse @@ -21,6 +25,8 @@ import json import os import struct +import sys +from decimal import Decimal, InvalidOperation from ledger import analyze as A from ledger import sibyl_regions @@ -51,8 +57,8 @@ def _parse_us_ns(text): if not text or text == "N/A": return None try: - return round(float(text) * 1000.0) - except ValueError: + return round(Decimal(text) * 1000) # epoch microseconds do not fit a float to the nanosecond + except InvalidOperation: return None @@ -83,6 +89,7 @@ def parse_kernel_args(text): def load_acl_graphs(paths, stream_map=None): """Load aclmdlRIDebugPrint JSON dumps into a `(stream_id, task_id) -> node` lookup.""" by_st = {} + clashes = 0 for path in paths: events = json.load(open(path)) for ev in events: @@ -99,11 +106,17 @@ def load_acl_graphs(paths, stream_map=None): continue stream_id = int(args["Stream Id"]) task_id = int(args["Task Id"]) - by_st[(stream_id, task_id)] = { + node = { "name": ev.get("name", ""), "blocks": int(args.get("Numblocks") or 1), "params": params, } + clashes += by_st.setdefault((stream_id, task_id), node)["params"] != params + by_st[(stream_id, task_id)] = node + if clashes: + print(f"ledger ascend-import: {clashes} (stream, task) pairs appear in the graph dumps with different " + "kernel args; the last one wins, so some launches may resolve to the wrong pointers", + file=sys.stderr) if stream_map: for runtime_stream, graph_stream in stream_map.items(): for (gs, tid), node in list(by_st.items()): @@ -396,8 +409,11 @@ def _parse_stream_maps(specs): pair = pair.strip() if not pair: continue - src, dst = pair.split(":", 1) - mapping[int(src)] = int(dst) + try: + src, dst = pair.split(":") + mapping[int(src)] = int(dst) + except ValueError: + raise SystemExit(f"ledger ascend-import: --stream-map expects RUNTIME:GRAPH stream ids, got {pair!r}") from None return mapping diff --git a/ledger/ceilings.py b/ledger/ceilings.py index eec0fff..75152d6 100644 --- a/ledger/ceilings.py +++ b/ledger/ceilings.py @@ -63,7 +63,7 @@ def valid_ceiling(data, device): positive(data.get("ceiling_gbps")) and isinstance(peaks, dict) and bool(peaks) - and all(key in {"bf16", "fp8", "fp4", "int8", "int4"} and positive(value) for key, value in peaks.items()) + and all(key in {"bf16", "fp8", "fp4", "int8"} and positive(value) for key, value in peaks.items()) ) diff --git a/ledger/cli.py b/ledger/cli.py index a7c7361..ac3d42b 100644 --- a/ledger/cli.py +++ b/ledger/cli.py @@ -142,8 +142,6 @@ def main(): return handlers[selected](rest) if selected in REPORT_OPTIONS: rest = report_args(selected, rest) - if selected == "ascend-import": - return call_main("ascend", selected, rest) return call_main(selected.replace("-", "_"), selected, rest) except subprocess.CalledProcessError as error: raise SystemExit(f"ledger: {error}") from error diff --git a/tests/test_ascend.py b/tests/test_ascend.py index e47089a..93c298e 100644 --- a/tests/test_ascend.py +++ b/tests/test_ascend.py @@ -1,11 +1,11 @@ -"""Tests for ledger.ascend: Ascend CANN msprof + aclGraph import and end-to-end Ledger analysis.""" +"""Tests for ledger.ascend_import: Ascend CANN msprof + aclGraph import and end-to-end Ledger analysis.""" import json import sys import pytest -from ledger import analyze, ascend, cli, perfetto, transfers +from ledger import analyze, ascend_import as ascend, cli, perfetto, transfers from report import section, table_rows @@ -189,3 +189,22 @@ def test_parse_kernel_args_ignores_non_hex_tokens(): def test_import_capture_missing_op_summary_exits(tmp_path): with pytest.raises(SystemExit, match="op_summary"): ascend.import_capture(str(tmp_path), str(tmp_path / "out")) + + +def test_timestamps_keep_nanoseconds(): + assert ascend._parse_us_ns("1764251755123456.789\t") == 1764251755123456789 + + +def test_clashing_graph_dumps_warn(tmp_path, capsys): + paths = [] + for name, arg in (("a", "0x10"), ("b", "0x20"), ("c", "0x20")): + path = tmp_path / f"{name}.json" + path.write_text(json.dumps([{"name": name, "args": {"Stream Id": 1, "Task Id": 1, "Kernel Args": arg}}])) + paths.append(str(path)) + assert ascend.load_acl_graphs(paths)[(1, 1)]["name"] == "c" + assert "1 (stream, task) pairs" in capsys.readouterr().err + + +def test_bad_stream_map_exits(): + with pytest.raises(SystemExit, match="--stream-map"): + ascend._parse_stream_maps(["23"])