File size: 8,638 Bytes
65e1c10 86b22af 65e1c10 86b22af 65e1c10 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | """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()
|