Download scripts/plot_shape_distributions.py from humanfia-lab/inference-kernels: direct link, hf CLI and curl.
- Browser
- Download file 8.64 kB
-
https://huggingface.co/datasets/humanfia-lab/inference-kernels/resolve/main/scripts/plot_shape_distributions.py
- Command line
-
hf download hf://datasets/humanfia-lab/inference-kernels/scripts/plot_shape_distributions.py
-
curl -L -o plot_shape_distributions.py https://huggingface.co/datasets/humanfia-lab/inference-kernels/resolve/main/scripts/plot_shape_distributions.py
8.64 kB
| """Render one exact-shape histogram per definition from workload metadata only.""" | |
| import argparse | |
| from collections import Counter | |
| import json | |
| import os | |
| from pathlib import Path | |
| import textwrap | |
| ROOT = Path(__file__).resolve().parents[1] | |
| os.environ.setdefault("MPLCONFIGDIR", str(ROOT / "results/shape-distributions/matplotlib")) | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from matplotlib.ticker import MaxNLocator | |
| def load_distributions(): | |
| distributions = [] | |
| seen_uuids = set() | |
| for path in sorted((ROOT / "definitions").rglob("*.json")): | |
| definition = json.loads(path.read_text()) | |
| workload_path = (ROOT / "workloads" / path.relative_to(ROOT / "definitions")).with_suffix(".jsonl") | |
| axes = [name for name, spec in definition["axes"].items() if spec["type"] == "var"] | |
| counts = Counter() | |
| for line in workload_path.read_text().splitlines(): | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| workload = row["workload"] | |
| if row["definition"] != definition["name"] or set(workload["axes"]) != set(axes): | |
| raise ValueError(f"Definition or runtime dimensions mismatch: {workload_path}") | |
| if workload["uuid"] in seen_uuids: | |
| raise ValueError(f"Duplicate workload UUID: {workload['uuid']}") | |
| seen_uuids.add(workload["uuid"]) | |
| counts[tuple(workload["axes"][axis] for axis in axes)] += 1 | |
| if not counts: | |
| raise ValueError(f"No workloads: {workload_path}") | |
| distributions.append((path, workload_path, definition, axes, counts)) | |
| return distributions | |
| def plot_distribution(definition, axes, counts): | |
| shapes = sorted(counts) | |
| frequencies = [counts[shape] for shape in shapes] | |
| horizontal = len(axes) != 1 | |
| labels = [str(shape[0]) if len(axes) == 1 else str(shape) for shape in shapes] | |
| height = max(4.8, 2.7 + len(shapes) * 0.28) if horizontal else 5.4 | |
| fig = plt.figure(figsize=(11.8, height), facecolor="white") | |
| left = max(2.0, max(map(len, labels)) * 0.077 + 0.25) if horizontal else 0.8 | |
| bottom = 0.9 if horizontal else 1.12 | |
| top = 1.85 if horizontal else 1.55 | |
| ax = fig.add_axes((left / 11.8, bottom / height, (11.35 - left) / 11.8, | |
| (height - bottom - top) / height)) | |
| color = "#2563a6" | |
| fig.text(0.035, 1 - 0.27 / height, "Shape distribution", fontsize=16, weight="bold", color="#142c44") | |
| fig.text(0.035, 1 - 0.52 / height, definition["name"], fontsize=10, family="monospace", color="#334155") | |
| fig.text(0.035, 1 - 0.78 / height, | |
| f"{sum(frequencies)} captured workloads | {len(shapes)} distinct shapes", | |
| fontsize=11, color=color, weight="bold") | |
| fixed = ", ".join(f"{name}={spec['value']}" for name, spec in definition["axes"].items() | |
| if spec["type"] == "const") | |
| fig.text(0.035, 1 - 1.02 / height, textwrap.fill("Fixed dimensions: " + fixed, width=125), | |
| fontsize=9, va="top", color="#526171") | |
| if horizontal: | |
| bars = ax.barh(range(len(shapes)), frequencies, height=0.68, color=color) | |
| ax.set_yticks(range(len(shapes)), labels, fontfamily="monospace", fontsize=9) | |
| ax.invert_yaxis() | |
| ax.set_xlabel("Captured workloads (count)", labelpad=10) | |
| fig.text(left / 11.8, 1 - 1.55 / height, "Runtime shape: (" + ", ".join(axes) + ")", | |
| fontsize=10, weight="bold", color="#334155") | |
| ax.set_xlim(0, max(frequencies) * 1.13) | |
| ax.xaxis.set_major_locator(MaxNLocator(integer=True, nbins=8)) | |
| ax.grid(axis="x", color="#e3e9ef", linewidth=0.8) | |
| else: | |
| bars = ax.bar(range(len(shapes)), frequencies, width=0.72, color=color) | |
| ax.set_xticks(range(len(shapes)), labels, rotation=35, ha="right", fontsize=10) | |
| description = definition["axes"][axes[0]].get("description", axes[0]).rstrip(".") | |
| ax.set_xlabel(f"{axes[0]} — {description}", labelpad=12) | |
| ax.set_ylabel("Captured workloads (count)", labelpad=10) | |
| ax.set_ylim(0, max(frequencies) * 1.17) | |
| ax.yaxis.set_major_locator(MaxNLocator(integer=True, nbins=7)) | |
| ax.grid(axis="y", color="#e3e9ef", linewidth=0.8) | |
| ax.bar_label(bars, padding=4, fontsize=9, color="#243c52") | |
| ax.set_axisbelow(True) | |
| ax.spines[["top", "right"]].set_visible(False) | |
| ax.spines[["left", "bottom"]].set_color("#b8c5d1") | |
| ax.tick_params(axis="both", length=0, pad=7, colors="#334155") | |
| fig.text(0.035, 0.10 / height, | |
| "One bin per exact runtime shape; equal spacing. Counts describe this dataset, not production traffic.", | |
| fontsize=8.5, color="#526171") | |
| return fig | |
| def write_gallery(distributions, output): | |
| total = sum(sum(counts.values()) for _, _, _, _, counts in distributions) | |
| lines = [ | |
| "# Kernel shape distributions", "", | |
| f"**{len(distributions)} kernels, {total} captured workloads.** Each histogram counts the workload records " | |
| "in one kernel definition's JSONL file. Every bar is one exact combination of its runtime dimensions; " | |
| "identical shapes are combined. The labels retain all runtime dimensions, including dimensions that " | |
| "happen to have one observed value. Model constants appear above each plot.", "", | |
| "Read bar height (or length in horizontal plots) as the number of captured workloads with that shape. " | |
| "Bins are equally spaced categories, sorted by the dimension values, not continuous numeric intervals. " | |
| "A bar of 1 means one published example; a bar of 6 means six. These are capture counts, " | |
| "not request probabilities, runtime invocation frequencies, or AgentX traffic weights.", "", | |
| "Multi-dimensional shapes use horizontal bars to keep every dimension readable. " | |
| "Dimension names are explained below each plot; the linked definition specifies complete tensor layouts.", "", | |
| f"Regenerate from the repository root with Python and Matplotlib (rendered with {matplotlib.__version__}):", "", | |
| "```bash", "python scripts/plot_shape_distributions.py", "```", "", | |
| "Only definition and workload metadata are needed; tensor snapshots and a GPU are unnecessary.", "", | |
| "| Kernel definition | Workloads | Distinct shapes |", "|---|---:|---:|", | |
| ] | |
| for _, _, definition, _, counts in distributions: | |
| name = definition["name"] | |
| lines.append(f"| [{name}](#{name}) | {sum(counts.values())} | {len(counts)} |") | |
| for path, workload_path, definition, axes, counts in distributions: | |
| name = definition["name"] | |
| lines.extend([ | |
| "", f"## {name}", "", | |
| f"[Definition](../../{path.relative_to(ROOT)}) · " | |
| f"[Workloads](../../{workload_path.relative_to(ROOT)}) · " | |
| f"[SVG]({name}.svg)", "", | |
| f"", "", | |
| "**Runtime dimensions:** " + " ".join( | |
| f"`{axis}`: {definition['axes'][axis].get('description', axis)}" for axis in axes), | |
| ]) | |
| (output / "README.md").write_text("\n".join(lines) + "\n") | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--preview-dir", type=Path, help="Optionally save PNG previews outside the published gallery.") | |
| args = parser.parse_args() | |
| distributions = load_distributions() | |
| output = ROOT / "docs/shape-distributions" | |
| output.mkdir(parents=True, exist_ok=True) | |
| if args.preview_dir: | |
| args.preview_dir.mkdir(parents=True, exist_ok=True) | |
| plt.rcParams.update({"font.family": "DejaVu Sans", "svg.fonttype": "none", "svg.hashsalt": "kernel-shapes"}) | |
| for _, _, definition, axes, counts in distributions: | |
| fig = plot_distribution(definition, axes, counts) | |
| name = definition["name"] | |
| svg_path = output / f"{name}.svg" | |
| fig.savefig(svg_path, metadata={"Date": None, "Title": f"Shape distribution: {name}"}) | |
| # Matplotlib adds trailing spaces to path coordinates; keep generated diffs clean. | |
| svg_path.write_text("\n".join(line.rstrip() for line in svg_path.read_text().splitlines()) + "\n") | |
| if args.preview_dir: | |
| fig.savefig(args.preview_dir / f"{name}.png", dpi=120) | |
| plt.close(fig) | |
| write_gallery(distributions, output) | |
| total = sum(sum(counts.values()) for _, _, _, _, counts in distributions) | |
| print(f"Wrote {len(distributions)} histograms covering {total} workloads to {output}") | |
| if __name__ == "__main__": | |
| main() | |