Datasets:
Download plots.py from tesraghavan/agent-trace: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/plots.py
- Command line
-
hf download hf://datasets/tesraghavan/agent-trace/plots.py
-
curl -L -o plots.py https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/plots.py
18.4 kB
| """Generate figures from trace JSONL files. | |
| Usage: | |
| uv run python plots.py # auto-detect datasets/ | |
| uv run python plots.py mbpp.jsonl nl2bash.jsonl # explicit files | |
| uv run python plots.py --outdir figures # custom output dir | |
| """ | |
| import argparse | |
| import json | |
| from collections import Counter | |
| from pathlib import Path | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import matplotlib.ticker as ticker | |
| # ── Style ────────────────────────────────────────────────────────────── | |
| plt.rcParams.update({ | |
| "figure.figsize": (6, 3.5), | |
| "figure.dpi": 150, | |
| "savefig.dpi": 300, | |
| "savefig.bbox": "tight", | |
| "font.size": 10, | |
| "axes.titlesize": 11, | |
| "axes.labelsize": 10, | |
| "legend.fontsize": 9, | |
| "axes.grid": True, | |
| "grid.alpha": 0.3, | |
| }) | |
| # Color by (dataset, model_size) — hue = dataset, saturation = model size | |
| PALETTE = { | |
| ("mbpp", "0.6B"): {"color": "#7ABAED", "linestyle": "--", "marker": "o", "hatch": "////"}, # light blue, dashed | |
| ("mbpp", "1.7B"): {"color": "#1A5276", "linestyle": "-", "marker": "s", "hatch": ""}, # dark blue, solid | |
| ("nl2bash", "0.6B"): {"color": "#F5A623", "linestyle": ":", "marker": "^", "hatch": "\\\\\\\\"}, # light orange, dotted | |
| ("nl2bash", "1.7B"): {"color": "#C0392B", "linestyle": "-.", "marker": "D", "hatch": "xx"}, # dark red, dash-dot | |
| } | |
| MONO_PALETTE = { | |
| ("mbpp", "0.6B"): {"color": "#111111", "linestyle": "--", "marker": "o", "hatch": "////", "facecolor": "#FFFFFF"}, | |
| ("mbpp", "1.7B"): {"color": "#111111", "linestyle": "-", "marker": "s", "hatch": "", "facecolor": "#808080"}, | |
| ("nl2bash", "0.6B"): {"color": "#111111", "linestyle": ":", "marker": "^", "hatch": "\\\\\\\\", "facecolor": "#D9D9D9"}, | |
| ("nl2bash", "1.7B"): {"color": "#111111", "linestyle": "-.", "marker": "D", "hatch": "xx", "facecolor": "#4D4D4D"}, | |
| } | |
| MODEL_MONO_PALETTE = { | |
| "0.6B": {"color": "#111111", "linestyle": "--", "marker": "o", "hatch": "////", "facecolor": "#FFFFFF"}, | |
| "1.7B": {"color": "#111111", "linestyle": "-", "marker": "s", "hatch": "", "facecolor": "#808080"}, | |
| } | |
| MONOCHROME = False | |
| def _style(traces: list[dict]) -> dict: | |
| """Get color + linestyle for a dataset based on source and model size.""" | |
| src = detect_source(traces) | |
| model = model_label(traces) | |
| palette = MONO_PALETTE if MONOCHROME else PALETTE | |
| return palette.get((src, model), {"color": "#666666", "linestyle": "-", "marker": "o", "hatch": "", "facecolor": "#FFFFFF"}) | |
| def _bar_color(traces: list[dict]) -> str: | |
| s = _style(traces) | |
| return s.get("facecolor", s["color"]) if MONOCHROME else s["color"] | |
| def _model_style(model: str, traces: list[dict]) -> dict: | |
| """Style for panel plots where the legend encodes only model size.""" | |
| if MONOCHROME: | |
| return MODEL_MONO_PALETTE.get(model, MODEL_MONO_PALETTE["0.6B"]) | |
| return _style(traces) | |
| # ── Helpers ──────────────────────────────────────────────────────────── | |
| def load_traces(path: str) -> list[dict]: | |
| traces = [] | |
| with open(path) as f: | |
| for line in f: | |
| line = line.strip() | |
| if line: | |
| traces.append(json.loads(line)) | |
| return traces | |
| def detect_source(traces: list[dict]) -> str: | |
| """Guess dataset name from metadata or filename.""" | |
| for t in traces[:5]: | |
| src = (t.get("metadata") or {}).get("source", "") | |
| if src: | |
| return src.lower() | |
| return "unknown" | |
| def model_label(traces: list[dict]) -> str: | |
| """Extract short model label like '0.6B' from traces.""" | |
| for t in traces[:5]: | |
| m = t.get("model", "") | |
| for token in m.split("-"): | |
| if token.endswith("B") and token[0].isdigit(): | |
| return token | |
| return "unknown" | |
| def _group_datasets(datasets: dict[str, list[dict]]) -> dict[str, dict[str, list[dict]]]: | |
| """Group traces by source and then by model label.""" | |
| grouped: dict[str, dict[str, list[dict]]] = {} | |
| for traces in datasets.values(): | |
| grouped.setdefault(detect_source(traces), {})[model_label(traces)] = traces | |
| return grouped | |
| def _format_percent_tick(value: float, _position: float) -> str: | |
| """Readable tick formatter for percentages on log-scaled axes.""" | |
| if value >= 1: | |
| return f"{value:.0f}" | |
| if value >= 0.1: | |
| return f"{value:.1f}" | |
| if value >= 0.01: | |
| return f"{value:.2f}" | |
| return f"{value:.3f}".rstrip("0").rstrip(".") | |
| # ── Plot 1: CDF of trace durations ──────────────────────────────────── | |
| def plot_duration_cdf(datasets: dict[str, list[dict]], outdir: Path): | |
| """CDF of total trace duration, one line per dataset.""" | |
| fig, ax = plt.subplots() | |
| for label, traces in datasets.items(): | |
| durations = sorted(t["total_duration_ms"] / 1000 for t in traces) | |
| n = len(durations) | |
| cdf = [(i + 1) / n for i in range(n)] | |
| s = _style(traces) | |
| ax.plot(durations, cdf, label=f"{label} (n={n})", | |
| color=s["color"], linestyle=s["linestyle"], linewidth=1.7, | |
| marker=s["marker"], markersize=3.2, markevery=max(1, n // 12), | |
| markerfacecolor=s.get("facecolor", "white"), | |
| markeredgecolor=s["color"], markeredgewidth=0.8) | |
| ax.set_xlabel("Trace duration (seconds)") | |
| ax.set_ylabel("Cumulative fraction") | |
| ax.set_xscale("log") | |
| ax.xaxis.set_major_formatter(ticker.ScalarFormatter()) | |
| ax.legend() | |
| out = outdir / "duration_cdf.png" | |
| fig.savefig(out) | |
| plt.close(fig) | |
| print(f" {out}") | |
| # ── Plot 1b: Histogram of trace durations ───────────────────────────── | |
| def plot_duration_histogram(datasets: dict[str, list[dict]], outdir: Path): | |
| """Histogram of trace durations with log-scale bins. | |
| In monochrome mode this uses separate panels per source dataset so hatches | |
| do not collapse into an unreadable four-way overlay. | |
| """ | |
| import numpy as np | |
| # Log-spaced bins covering the range of all durations | |
| all_durations = [] | |
| for traces in datasets.values(): | |
| all_durations.extend(t["total_duration_ms"] / 1000 for t in traces) | |
| lo = max(1, min(all_durations)) | |
| hi = max(all_durations) | |
| bins = np.logspace(np.log10(lo), np.log10(hi), 30) | |
| if MONOCHROME: | |
| grouped = _group_datasets(datasets) | |
| sources = [src for src in ("mbpp", "nl2bash") if src in grouped] or sorted(grouped) | |
| fig, axes = plt.subplots(1, len(sources), figsize=(5 * len(sources), 3.8), sharey=True) | |
| if len(sources) == 1: | |
| axes = [axes] | |
| for ax, src in zip(axes, sources): | |
| for model in [model for model in ("0.6B", "1.7B") if model in grouped[src]]: | |
| traces = grouped[src][model] | |
| durations = [t["total_duration_ms"] / 1000 for t in traces] | |
| s = _model_style(model, traces) | |
| ax.hist( | |
| durations, | |
| bins=bins, | |
| label=f"{model} (n={len(durations)})", | |
| color=s.get("facecolor", s["color"]) if MONOCHROME else _bar_color(traces), | |
| alpha=0.95, | |
| edgecolor="black", | |
| linewidth=0.6, | |
| hatch=s.get("hatch", ""), | |
| ) | |
| ax.set_title("MBPP" if src == "mbpp" else "NL2Bash") | |
| ax.set_xlabel("Trace duration (seconds)") | |
| ax.set_xscale("log") | |
| ax.xaxis.set_major_formatter(ticker.ScalarFormatter()) | |
| ax.grid(axis="y", alpha=0.3) | |
| ax.legend() | |
| axes[0].set_ylabel("Number of traces") | |
| fig.tight_layout() | |
| else: | |
| fig, ax = plt.subplots() | |
| for label, traces in datasets.items(): | |
| durations = [t["total_duration_ms"] / 1000 for t in traces] | |
| s = _style(traces) | |
| ax.hist(durations, bins=bins, label=f"{label} (n={len(durations)})", | |
| color=_bar_color(traces), alpha=0.6, | |
| edgecolor="white", linewidth=0.5, | |
| hatch=s.get("hatch", "")) | |
| ax.set_xlabel("Trace duration (seconds)") | |
| ax.set_ylabel("Number of traces") | |
| ax.set_xscale("log") | |
| ax.xaxis.set_major_formatter(ticker.ScalarFormatter()) | |
| ax.legend() | |
| out = outdir / "duration_histogram.png" | |
| fig.savefig(out) | |
| plt.close(fig) | |
| print(f" {out}") | |
| # ── Plot 2: Steps-per-trace histogram ───────────────────────────────── | |
| def plot_steps_histogram(datasets: dict[str, list[dict]], outdir: Path): | |
| """Plot step-count histograms in separate panels per source dataset.""" | |
| grouped = _group_datasets(datasets) | |
| sources = [src for src in ("mbpp", "nl2bash") if src in grouped] or sorted(grouped) | |
| max_steps = max( | |
| (len(t.get("llm_steps", [])) for traces in datasets.values() for t in traces), | |
| default=10, | |
| ) | |
| fig, axes = plt.subplots(1, len(sources), figsize=(5 * len(sources), 3.8), sharey=True) | |
| if len(sources) == 1: | |
| axes = [axes] | |
| for ax, src in zip(axes, sources): | |
| model_order = [model for model in ("0.6B", "1.7B") if model in grouped[src]] | |
| width = 0.75 / max(1, len(model_order)) | |
| xs = list(range(0, max_steps + 1)) | |
| for idx, model in enumerate(model_order): | |
| traces = grouped[src][model] | |
| counts = Counter(len(t.get("llm_steps", [])) for t in traces) | |
| ys = [counts.get(x, 0) for x in xs] | |
| offset = (idx - (len(model_order) - 1) / 2) * width | |
| s = _model_style(model, traces) | |
| ax.bar( | |
| [x + offset for x in xs], | |
| ys, | |
| width=width * 0.9, | |
| label=model, | |
| color=s.get("facecolor", s["color"]) if MONOCHROME else _bar_color(traces), | |
| edgecolor="black" if MONOCHROME else None, | |
| linewidth=0.6, | |
| hatch=s.get("hatch", ""), | |
| alpha=0.95 if MONOCHROME else 0.9, | |
| ) | |
| ax.set_title("MBPP" if src == "mbpp" else "NL2Bash") | |
| ax.set_xlabel("LLM steps per trace") | |
| ax.set_xticks(xs) | |
| ax.grid(axis="y", alpha=0.3) | |
| axes[0].set_ylabel("Number of traces") | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="upper center", bbox_to_anchor=(0.5, 1.02), ncol=max(1, len(labels))) | |
| fig.tight_layout(rect=(0, 0, 1, 0.95)) | |
| out = outdir / "steps_histogram.png" | |
| fig.savefig(out) | |
| plt.close(fig) | |
| print(f" {out}") | |
| # ── Plot 3: Bash wall-clock vs CPU time scatter ────────────────────── | |
| def plot_bash_cpu_scatter(datasets: dict[str, list[dict]], outdir: Path): | |
| """Scatter plot of wall-clock vs CPU time for bash tool spans.""" | |
| fig, ax = plt.subplots() | |
| has_data = False | |
| all_wall_ms = [] | |
| all_cpu_ms = [] | |
| for label, traces in datasets.items(): | |
| src = detect_source(traces) | |
| if src != "nl2bash": | |
| continue | |
| wall_ms = [] | |
| cpu_ms = [] | |
| for t in traces: | |
| for s in t.get("spans", []): | |
| if s.get("tool_name") != "bash": | |
| continue | |
| tel = s.get("telemetry") or {} | |
| cpu = (tel.get("user_time_s", 0) or 0) + (tel.get("system_time_s", 0) or 0) | |
| if cpu > 0: | |
| wall_ms.append(s["duration_ms"]) | |
| cpu_ms.append(cpu * 1000) | |
| if wall_ms: | |
| s = _style(traces) | |
| ax.scatter( | |
| wall_ms, | |
| cpu_ms, | |
| alpha=0.7 if MONOCHROME else 0.4, | |
| s=22 if MONOCHROME else 15, | |
| marker=s["marker"], | |
| facecolors=s.get("facecolor", s["color"]) if MONOCHROME else s["color"], | |
| edgecolors="black" if MONOCHROME else "none", | |
| linewidths=0.5 if MONOCHROME else 0, | |
| label=label, | |
| ) | |
| has_data = True | |
| all_wall_ms.extend(wall_ms) | |
| all_cpu_ms.extend(cpu_ms) | |
| if not has_data: | |
| print(" (no bash spans with CPU telemetry, skipping scatter)") | |
| plt.close(fig) | |
| return | |
| # Reference line: CPU = Wall (100% utilization) | |
| lo = min(min(all_wall_ms), min(all_cpu_ms)) | |
| hi = max(max(all_wall_ms), max(all_cpu_ms)) | |
| ax.plot([lo, hi], [lo, hi], "--", color="#111111" if MONOCHROME else "#999999", linewidth=1, label="CPU = Wall (100%)") | |
| ax.set_xlabel("Wall-clock time (ms)") | |
| ax.set_ylabel("CPU time (ms)") | |
| ax.set_xscale("log") | |
| ax.set_yscale("log") | |
| ax.legend() | |
| out = outdir / "bash_cpu_scatter.png" | |
| fig.savefig(out) | |
| plt.close(fig) | |
| print(f" {out}") | |
| # ── Plot 4: Tool time fraction per trace ────────────────────────────── | |
| def plot_tool_time_fraction(datasets: dict[str, list[dict]], outdir: Path): | |
| """CDF of tool-execution-time fraction, with separate panels per source.""" | |
| grouped = _group_datasets(datasets) | |
| sources = [src for src in ("mbpp", "nl2bash") if src in grouped] or sorted(grouped) | |
| fig, axes = plt.subplots(1, len(sources), figsize=(5 * len(sources), 3.8), sharey=True) | |
| if len(sources) == 1: | |
| axes = [axes] | |
| global_max_fraction = 0.001 | |
| for ax, src in zip(axes, sources): | |
| model_order = [model for model in ("0.6B", "1.7B") if model in grouped[src]] | |
| for model in model_order: | |
| traces = grouped[src][model] | |
| fractions = [] | |
| for t in traces: | |
| total = t.get("total_duration_ms", 0) | |
| if total <= 0: | |
| continue | |
| tool_time = sum( | |
| s.get("duration_ms", 0) | |
| for s in t.get("spans", []) | |
| if s.get("tool_name") not in ("final_answer",) | |
| ) | |
| frac = max(tool_time / total * 100, 0.001) | |
| fractions.append(frac) | |
| fractions.sort() | |
| if not fractions: | |
| continue | |
| n = len(fractions) | |
| cdf = [(i + 1) / n for i in range(n)] | |
| s = _model_style(model, traces) | |
| ax.plot( | |
| fractions, | |
| cdf, | |
| label=model, | |
| color=s["color"], | |
| linestyle=s["linestyle"], | |
| linewidth=1.7, | |
| marker=s["marker"], | |
| markersize=3.2, | |
| markevery=max(1, n // 12), | |
| markerfacecolor=s.get("facecolor", "white"), | |
| markeredgecolor=s["color"], | |
| markeredgewidth=0.8, | |
| ) | |
| global_max_fraction = max(global_max_fraction, max(fractions)) | |
| ax.set_title("MBPP" if src == "mbpp" else "NL2Bash") | |
| ax.set_xlabel("Tool time (% of trace duration)") | |
| ax.set_xscale("log") | |
| ax.xaxis.set_major_formatter(ticker.FuncFormatter(_format_percent_tick)) | |
| ax.grid(alpha=0.3) | |
| axes[0].set_ylabel("Cumulative fraction") | |
| for ax in axes: | |
| ax.set_xlim(0.001, global_max_fraction * 1.15) | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="upper center", bbox_to_anchor=(0.5, 1.02), ncol=max(1, len(labels))) | |
| fig.tight_layout(rect=(0, 0, 1, 0.95)) | |
| out = outdir / "tool_time_fraction_cdf.png" | |
| fig.savefig(out) | |
| plt.close(fig) | |
| print(f" {out}") | |
| # ── Auto-detect datasets ────────────────────────────────────────────── | |
| def find_datasets(directory: str = "datasets") -> list[Path]: | |
| """Find timestamped JSONL files, preferring the most recent per dataset+model.""" | |
| p = Path(directory) | |
| if not p.exists(): | |
| return [] | |
| files = sorted(p.glob("*_*_*.jsonl"), key=lambda f: f.stat().st_mtime, reverse=True) | |
| seen = set() | |
| result = [] | |
| for f in files: | |
| # Key by dataset prefix (e.g., "mbpp_0_6B" or "nl2bash_1_7B") | |
| parts = f.stem.rsplit("_", 1) # split off timestamp | |
| key = parts[0] if len(parts) == 2 else f.stem | |
| if key not in seen: | |
| seen.add(key) | |
| result.append(f) | |
| return sorted(result) | |
| # ── Main ────────────────────────────────────────────────────────────── | |
| def main(): | |
| global MONOCHROME | |
| parser = argparse.ArgumentParser(description="Generate figures from trace data") | |
| parser.add_argument("files", nargs="*", help="JSONL trace files (auto-detects if omitted)") | |
| parser.add_argument("--outdir", default="figures", help="Output directory for plots") | |
| parser.add_argument("--monochrome", action="store_true", help="Use print-safe black-and-white styles") | |
| args = parser.parse_args() | |
| MONOCHROME = args.monochrome | |
| files = args.files or [str(f) for f in find_datasets()] | |
| if not files: | |
| print("No trace files found. Pass files explicitly or run from project root.") | |
| return | |
| outdir = Path(args.outdir) | |
| outdir.mkdir(parents=True, exist_ok=True) | |
| # Load and label datasets | |
| datasets = {} | |
| for path in files: | |
| traces = load_traces(path) | |
| if not traces: | |
| print(f" Skipping {path} (empty)") | |
| continue | |
| src = detect_source(traces) | |
| model = model_label(traces) | |
| label = f"{src.upper()} {model}" | |
| datasets[label] = traces | |
| print(f" Loaded {path}: {len(traces)} traces → {label}") | |
| print(f"\nGenerating plots in {outdir}/") | |
| plot_duration_cdf(datasets, outdir) | |
| plot_duration_histogram(datasets, outdir) | |
| plot_steps_histogram(datasets, outdir) | |
| plot_bash_cpu_scatter(datasets, outdir) | |
| plot_tool_time_fraction(datasets, outdir) | |
| print("\nDone.") | |
| if __name__ == "__main__": | |
| main() | |