Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

add model_compare tool (#303)

uuuvnab1747f25ad2
diff --git a/tools/model_compare/pyproject.toml b/tools/model_compare/pyproject.toml
new file mode 100644
index 000000000..111b2f2f3
--- /dev/null
+++ b/tools/model_compare/pyproject.toml
@@ -0,0 +1,16 @@
+[project]
+name = "model-compare"
+version = "0.1.0"
+description = "Compare GPU hardware counters across model variants"
+requires-python = ">=3.12"
+dependencies = ["rich>=13.0.0"]
+
+[project.scripts]
+model_compare = "model_compare.main:cli"
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/model_compare"]
diff --git a/tools/model_compare/src/model_compare/__init__.py b/tools/model_compare/src/model_compare/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tools/model_compare/src/model_compare/__main__.py b/tools/model_compare/src/model_compare/__main__.py
new file mode 100644
index 000000000..f9afe44af
--- /dev/null
+++ b/tools/model_compare/src/model_compare/__main__.py
@@ -0,0 +1,3 @@
+from .main import cli
+
+cli()
diff --git a/tools/model_compare/src/model_compare/comparison.py b/tools/model_compare/src/model_compare/comparison.py
new file mode 100644
index 000000000..5833e2406
--- /dev/null
+++ b/tools/model_compare/src/model_compare/comparison.py
@@ -0,0 +1,132 @@
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass
+from pathlib import Path
+
+
+@dataclass(frozen=True)
+class KernelCounters:
+ name: str
+ total_ns: int
+ count: int
+ counters: dict[str, float]
+
+ @property
+ def total_ms(self) -> float:
+ return self.total_ns / 1e6
+
+ @property
+ def avg_us(self) -> float:
+ return self.total_ns / max(self.count, 1) / 1e3
+
+ def counter(self, name: str) -> float | None:
+ return self.counters.get(name)
+
+ @property
+ def bottleneck(self) -> str:
+ limiter_counters = {
+ k: v for k, v in self.counters.items() if "Limiter" in k and v > 0
+ }
+ if not limiter_counters:
+ return "--"
+ top = max(limiter_counters, key=limiter_counters.__getitem__)
+ return top.replace(" Limiter", "")
+
+
+@dataclass(frozen=True)
+class TraceProfile:
+ label: str
+ device: str
+ duration_ns: int
+ kernels: dict[str, KernelCounters]
+
+
+_ID_SUFFIX = re.compile(r"\s*\(\d+\)\s*$")
+
+
+def _normalize_kernel_name(raw_name: str) -> str:
+ return _ID_SUFFIX.sub("", raw_name).strip()
+
+
+def load_trace_profile(json_path: Path | str, label: str) -> TraceProfile:
+ with open(json_path) as f:
+ data = json.load(f)
+
+ device = data.get("metadata", {}).get("device_name", "unknown")
+ duration_ns = data.get("metadata", {}).get("duration_ns", 0)
+
+ kernels: dict[str, KernelCounters] = {}
+
+ for entry in data.get("kernel_counter_stats", []):
+ raw_name = entry["name"]
+ normalized = _normalize_kernel_name(raw_name)
+ counters = {name: value for name, value in entry.get("counters", [])}
+
+ kc = KernelCounters(
+ name=normalized,
+ total_ns=entry["total_ns"],
+ count=entry["count"],
+ counters=counters,
+ )
+
+ if normalized in kernels:
+ existing = kernels[normalized]
+ merged_counters = dict(existing.counters)
+ for k, v in counters.items():
+ if k in merged_counters:
+ w1, w2 = existing.total_ns, kc.total_ns
+ total_w = w1 + w2
+ merged_counters[k] = (merged_counters[k] * w1 + v * w2) / total_w if total_w > 0 else 0
+ else:
+ merged_counters[k] = v
+ kernels[normalized] = KernelCounters(
+ name=normalized,
+ total_ns=existing.total_ns + kc.total_ns,
+ count=existing.count + kc.count,
+ counters=merged_counters,
+ )
+ else:
+ kernels[normalized] = kc
+
+ return TraceProfile(
+ label=label,
+ device=device,
+ duration_ns=duration_ns,
+ kernels=kernels,
+ )
+
+
+KEY_COUNTERS = [
+ "ALU Utilization",
+ "ALU Limiter",
+ "Buffer Load Utilization",
+ "Buffer Load Limiter",
+ "Compute Occupancy",
+]
+
+
+@dataclass(frozen=True)
+class KernelRow:
+ name: str
+ entries: tuple[KernelCounters | None, ...]
+
+
+def build_comparison(profiles: list[TraceProfile]) -> list[KernelRow]:
+ all_names: dict[str, int] = {}
+ for profile in profiles:
+ for kc in sorted(profile.kernels.values(), key=lambda k: -k.total_ns):
+ if kc.name not in all_names:
+ all_names[kc.name] = 0
+ all_names[kc.name] = max(all_names[kc.name], kc.total_ns)
+
+ sorted_names = sorted(all_names, key=lambda n: -all_names[n])
+
+ return [
+ KernelRow(
+ name=name,
+ entries=tuple(p.kernels.get(name) for p in profiles),
+ )
+ for name in sorted_names
+ ]
diff --git a/tools/model_compare/src/model_compare/formatting.py b/tools/model_compare/src/model_compare/formatting.py
new file mode 100644
index 000000000..7a24d6308
--- /dev/null
+++ b/tools/model_compare/src/model_compare/formatting.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from rich.console import Console
+from rich.table import Table
+
+from .comparison import KEY_COUNTERS, KernelCounters, KernelRow, TraceProfile
+
+
+def _fmt_time(kc: KernelCounters | None) -> str:
+ if kc is None:
+ return "--"
+ if kc.total_ms >= 1.0:
+ return f"{kc.total_ms:.2f} ms"
+ return f"{kc.total_ns / 1e3:.1f} us"
+
+
+def _fmt_count(kc: KernelCounters | None) -> str:
+ if kc is None:
+ return "--"
+ return str(kc.count)
+
+
+def _fmt_counter(kc: KernelCounters | None, counter_name: str) -> str:
+ if kc is None:
+ return "--"
+ val = kc.counter(counter_name)
+ if val is None:
+ return "--"
+ return f"{val:.1f}%"
+
+
+def _fmt_bottleneck(kc: KernelCounters | None) -> str:
+ if kc is None:
+ return "--"
+ return kc.bottleneck
+
+
+def _short_name(name: str) -> str:
+ name = name.removeprefix("_D")
+ if len(name) > 1 and name[0].isdigit():
+ i = 0
+ while i < len(name) and name[i].isdigit():
+ i += 1
+ name = name[i:]
+ if len(name) > 40:
+ name = name[:37] + "..."
+ return name
+
+
+def print_comparison_table(
+ profiles: list[TraceProfile],
+ rows: list[KernelRow],
+ console: Console | None = None,
+ top_n: int = 15,
+) -> None:
+ console = console or Console()
+
+ labels = [p.label for p in profiles]
+ title = " vs ".join(labels)
+
+ table = Table(title=f"Kernel Comparison: {title}", show_lines=True, expand=False)
+ table.add_column("Kernel", style="bold", max_width=30)
+
+ for label in labels:
+ table.add_column(f"{label} time", justify="right", max_width=10)
+ table.add_column("#", justify="right", max_width=5)
+
+ table.add_column("ALU%", justify="right", max_width=6)
+ table.add_column("BufRd%", justify="right", max_width=6)
+ table.add_column("Occup%", justify="right", max_width=6)
+ table.add_column("Bottleneck", justify="right", max_width=12)
+
+ for row in rows[:top_n]:
+ cells: list[str] = [_short_name(row.name)]
+
+ for entry in row.entries:
+ cells.append(_fmt_time(entry))
+ cells.append(_fmt_count(entry))
+
+ first_present = next((e for e in row.entries if e is not None), None)
+ cells.append(_fmt_counter(first_present, "ALU Utilization"))
+ cells.append(_fmt_counter(first_present, "Buffer Load Utilization"))
+ cells.append(_fmt_counter(first_present, "Compute Occupancy"))
+ cells.append(_fmt_bottleneck(first_present))
+
+ table.add_row(*cells)
+
+ total_row: list[str] = ["TOTAL"]
+ for profile in profiles:
+ total_ns = sum(kc.total_ns for kc in profile.kernels.values())
+ total_calls = sum(kc.count for kc in profile.kernels.values())
+ total_row.append(f"{total_ns / 1e6:.1f} ms")
+ total_row.append(str(total_calls))
+ total_row.extend(["", "", "", ""])
+ table.add_row(*total_row, style="bold")
+
+ console.print(table)
+
+ console.print()
+ for profile in profiles:
+ console.print(f"[cyan]{profile.label}[/cyan]: {profile.device}, {profile.duration_ns / 1e9:.2f}s recording")
+
+
+def print_counter_detail(
+ profiles: list[TraceProfile],
+ rows: list[KernelRow],
+ console: Console | None = None,
+ top_n: int = 10,
+) -> None:
+ console = console or Console()
+
+ for row in rows[:top_n]:
+ console.print(f"\n[bold]{_short_name(row.name)}[/bold]")
+ detail_table = Table(show_header=True, show_lines=False, pad_edge=False)
+ detail_table.add_column("Counter", no_wrap=True)
+
+ present_indices: list[int] = []
+ for i, entry in enumerate(row.entries):
+ if entry is not None:
+ detail_table.add_column(profiles[i].label, justify="right")
+ present_indices.append(i)
+
+ if not present_indices:
+ continue
+
+ all_counter_names: dict[str, None] = {}
+ for idx in present_indices:
+ entry = row.entries[idx]
+ assert entry is not None
+ for k in entry.counters:
+ all_counter_names[k] = None
+
+ for counter_name in all_counter_names:
+ cells = [counter_name]
+ for idx in present_indices:
+ entry = row.entries[idx]
+ assert entry is not None
+ val = entry.counter(counter_name)
+ cells.append(f"{val:.2f}" if val is not None else "--")
+ detail_table.add_row(*cells)
+
+ timing_cells = ["Total time"]
+ for idx in present_indices:
+ entry = row.entries[idx]
+ assert entry is not None
+ timing_cells.append(_fmt_time(entry))
+ detail_table.add_row(*timing_cells, style="bold")
+
+ count_cells = ["Dispatches"]
+ for idx in present_indices:
+ entry = row.entries[idx]
+ assert entry is not None
+ count_cells.append(str(entry.count))
+ detail_table.add_row(*count_cells)
+
+ console.print(detail_table)
diff --git a/tools/model_compare/src/model_compare/main.py b/tools/model_compare/src/model_compare/main.py
new file mode 100644
index 000000000..45cce7326
--- /dev/null
+++ b/tools/model_compare/src/model_compare/main.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+from rich.console import Console
+
+from .comparison import build_comparison, load_trace_profile
+from .formatting import print_comparison_table, print_counter_detail
+from .runner import RunConfig, record_all
+
+
+def cmd_compare(args: argparse.Namespace) -> int:
+ console = Console()
+
+ json_paths: list[Path] = args.traces
+ labels: list[str] = args.labels.split(",") if args.labels else [p.stem for p in json_paths]
+
+ if len(labels) != len(json_paths):
+ console.print(f"[red]Error: {len(labels)} labels for {len(json_paths)} traces[/red]")
+ return 1
+
+ profiles = []
+ for path, label in zip(json_paths, labels):
+ if not path.exists():
+ console.print(f"[red]Error: {path} not found[/red]")
+ return 1
+ profiles.append(load_trace_profile(path, label))
+
+ rows = build_comparison(profiles)
+ print_comparison_table(profiles, rows, console, top_n=args.top)
+
+ if args.verbose:
+ print_counter_detail(profiles, rows, console, top_n=args.top)
+
+ return 0
+
+
+def cmd_run(args: argparse.Namespace) -> int:
+ console = Console()
+
+ config_path = Path(args.config)
+ if not config_path.exists():
+ console.print(f"[red]Error: Config not found: {config_path}[/red]")
+ return 1
+
+ config = RunConfig.from_file(config_path)
+ output_dir = Path(args.output) if args.output else None
+
+ profiles = record_all(config, output_dir=output_dir, console=console)
+ rows = build_comparison(profiles)
+
+ console.print()
+ print_comparison_table(profiles, rows, console, top_n=args.top)
+
+ if args.verbose:
+ print_counter_detail(profiles, rows, console, top_n=args.top)
+
+ return 0
+
+
+def cli() -> None:
+ parser = argparse.ArgumentParser(
+ prog="model_compare",
+ description="Compare GPU hardware counters across model variants",
+ )
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ compare_parser = subparsers.add_parser(
+ "compare",
+ help="Compare pre-recorded gpu_trace JSON files",
+ )
+ compare_parser.add_argument(
+ "traces",
+ type=Path,
+ nargs="+",
+ help="gpu_trace JSON export files to compare",
+ )
+ compare_parser.add_argument(
+ "--labels",
+ type=str,
+ default=None,
+ help="Comma-separated labels for each trace (default: filename stems)",
+ )
+ compare_parser.add_argument(
+ "--top",
+ type=int,
+ default=15,
+ help="Number of top kernels to show (default: 15)",
+ )
+ compare_parser.add_argument(
+ "-v", "--verbose",
+ action="store_true",
+ help="Show detailed per-kernel counter breakdown",
+ )
+
+ run_parser = subparsers.add_parser(
+ "run",
+ help="Record traces for multiple models and compare",
+ )
+ run_parser.add_argument(
+ "--config",
+ type=str,
+ required=True,
+ help="Path to comparison config JSON",
+ )
+ run_parser.add_argument(
+ "--output",
+ type=str,
+ default=None,
+ help="Output directory for traces (default: temp dir)",
+ )
+ run_parser.add_argument(
+ "--top",
+ type=int,
+ default=15,
+ help="Number of top kernels to show (default: 15)",
+ )
+ run_parser.add_argument(
+ "-v", "--verbose",
+ action="store_true",
+ help="Show detailed per-kernel counter breakdown",
+ )
+
+ args = parser.parse_args()
+
+ if args.command == "compare":
+ sys.exit(cmd_compare(args))
+ elif args.command == "run":
+ sys.exit(cmd_run(args))
diff --git a/tools/model_compare/src/model_compare/runner.py b/tools/model_compare/src/model_compare/runner.py
new file mode 100644
index 000000000..ba8f5665e
--- /dev/null
+++ b/tools/model_compare/src/model_compare/runner.py
@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+import json
+import subprocess
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+
+from rich.console import Console
+
+from .comparison import TraceProfile, load_trace_profile
+
+
+@dataclass(frozen=True)
+class ModelSpec:
+ label: str
+ model_path: str
+
+
+@dataclass(frozen=True)
+class RunConfig:
+ cli_binary: str
+ gpu_trace_dir: str
+ task: dict
+ models: list[ModelSpec]
+
+ @classmethod
+ def from_file(cls, path: Path | str) -> RunConfig:
+ with open(path) as f:
+ data = json.load(f)
+ return cls(
+ cli_binary=data["cli_binary"],
+ gpu_trace_dir=data.get("gpu_trace_dir", ""),
+ task=data["task"],
+ models=[ModelSpec(**m) for m in data["models"]],
+ )
+
+
+def record_trace_for_model(
+ spec: ModelSpec,
+ cli_binary: Path,
+ gpu_trace_dir: Path,
+ task: dict,
+ output_dir: Path,
+ console: Console,
+) -> Path:
+ task_file = output_dir / f"{spec.label.replace(' ', '_')}_task.json"
+ task_file.write_text(json.dumps(task, indent=2))
+
+ result_file = output_dir / f"{spec.label.replace(' ', '_')}_result.json"
+ trace_file = output_dir / f"{spec.label.replace(' ', '_')}.trace"
+ json_file = trace_file.with_suffix(".json")
+
+ console.print(f"[cyan]Recording trace for {spec.label}...[/cyan]")
+
+ cmd = [
+ "uv", "run", "gpu_trace", "run",
+ "-v", "--gpu-counters",
+ "--json", str(json_file),
+ "-o", str(trace_file),
+ "--",
+ str(cli_binary), "bench",
+ spec.model_path,
+ str(task_file),
+ str(result_file),
+ ]
+
+ proc = subprocess.run(cmd, cwd=str(gpu_trace_dir), capture_output=True, text=True)
+
+ if proc.returncode != 0:
+ console.print(f"[red]Error recording {spec.label}:[/red]")
+ console.print(proc.stderr[-500:] if proc.stderr else "(no stderr)")
+ raise RuntimeError(f"gpu_trace failed for {spec.label}")
+
+ console.print(f"[green]Done: {spec.label} -> {json_file}[/green]")
+ return json_file
+
+
+def record_all(config: RunConfig, output_dir: Path | None = None, console: Console | None = None) -> list[TraceProfile]:
+ console = console or Console()
+
+ if output_dir is None:
+ output_dir = Path(tempfile.mkdtemp(prefix="model_compare_"))
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ cli_binary = Path(config.cli_binary).resolve()
+ gpu_trace_dir = Path(config.gpu_trace_dir).resolve() if config.gpu_trace_dir else Path.cwd()
+
+ profiles: list[TraceProfile] = []
+ for spec in config.models:
+ json_path = record_trace_for_model(
+ spec=spec,
+ cli_binary=cli_binary,
+ gpu_trace_dir=gpu_trace_dir,
+ task=config.task,
+ output_dir=output_dir,
+ console=console,
+ )
+ profile = load_trace_profile(json_path, spec.label)
+ profiles.append(profile)
+
+ return profiles
diff --git a/tools/model_compare/uv.lock b/tools/model_compare/uv.lock
new file mode 100644
index 000000000..5c9aef772
--- /dev/null
+++ b/tools/model_compare/uv.lock
@@ -0,0 +1,57 @@
+version = 1
+revision = 3
+requires-python = ">=3.12"
+
+[[package]]
+name = "markdown-it-py"
+version = "4.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/5b/f5/4ec618ed16cc4f8fb3b701563655a69816155e79e24a17b651541804721d/markdown_it_py-4.0.0.tar.gz", hash = "sha256:cb0a2b4aa34f932c007117b194e945bd74e0ec24133ceb5bac59009cda1cb9f3", size = 73070, upload-time = "2025-08-11T12:57:52.854Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
+[[package]]
+name = "model-compare"
+version = "0.1.0"
+source = { editable = "." }
+dependencies = [
+ { name = "rich" },
+]
+
+[package.metadata]
+requires-dist = [{ name = "rich", specifier = ">=13.0.0" }]
+
+[[package]]
+name = "pygments"
+version = "2.19.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631, upload-time = "2025-06-21T13:39:12.283Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" },
+]
+
+[[package]]
+name = "rich"
+version = "14.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b3/c6/f3b320c27991c46f43ee9d856302c70dc2d0fb2dba4842ff739d5f46b393/rich-14.3.3.tar.gz", hash = "sha256:b8daa0b9e4eef54dd8cf7c86c03713f53241884e814f4e2f5fb342fe520f639b", size = 230582, upload-time = "2026-02-19T17:23:12.474Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/14/25/b208c5683343959b670dc001595f2f3737e051da617f66c31f7c4fa93abc/rich-14.3.3-py3-none-any.whl", hash = "sha256:793431c1f8619afa7d3b52b2cdec859562b950ea0d4b6b505397612db8d5362d", size = 310458, upload-time = "2026-02-19T17:23:13.732Z" },
+]