Datasets:
Download analyze_deep.py from tesraghavan/agent-trace: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/analyze_deep.py
- Command line
-
hf download hf://datasets/tesraghavan/agent-trace/analyze_deep.py
-
curl -L -o analyze_deep.py https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/analyze_deep.py
11.3 kB
| """Deeper analysis for paper Section 4 — duration breakdowns, correlations, etc.""" | |
| import argparse | |
| import json | |
| import sys | |
| from collections import Counter | |
| from pathlib import Path | |
| 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 percentile(values: list[float], p: int) -> float: | |
| if not values: | |
| return 0.0 | |
| s = sorted(values) | |
| k = (len(s) - 1) * p / 100 | |
| f = int(k) | |
| c = min(f + 1, len(s) - 1) | |
| return s[f] + (k - f) * (s[c] - s[f]) | |
| def section(title: str): | |
| print(f"\n{'=' * 70}") | |
| print(f" {title}") | |
| print(f"{'=' * 70}") | |
| def analyze_time_breakdown(traces: list[dict]): | |
| """Where does the time go? LLM generation vs tool execution.""" | |
| section("Time Breakdown: LLM Generation vs Tool Execution") | |
| for trace in traces: | |
| tool_time_ms = sum(s["duration_ms"] for s in trace.get("spans", [])) | |
| total = trace.get("total_duration_ms", 0) | |
| trace["_tool_time_ms"] = tool_time_ms | |
| trace["_llm_time_ms"] = total - tool_time_ms # approximate | |
| tool_times = [t["_tool_time_ms"] for t in traces if t.get("total_duration_ms")] | |
| llm_times = [t["_llm_time_ms"] for t in traces if t.get("total_duration_ms")] | |
| totals = [t["total_duration_ms"] for t in traces if t.get("total_duration_ms")] | |
| tool_total = sum(tool_times) | |
| llm_total = sum(llm_times) | |
| grand_total = sum(totals) | |
| print(f" Total wall-clock: {grand_total/1000:>10.1f}s") | |
| print(f" Tool execution: {tool_total/1000:>10.1f}s ({100*tool_total/grand_total:.1f}%)") | |
| print(f" LLM generation (est): {llm_total/1000:>10.1f}s ({100*llm_total/grand_total:.1f}%)") | |
| print() | |
| # Per-trace ratios | |
| tool_fracs = [t["_tool_time_ms"] / t["total_duration_ms"] * 100 | |
| for t in traces if t.get("total_duration_ms", 0) > 0] | |
| print(f" Tool time as % of trace:") | |
| print(f" Min: {min(tool_fracs):>6.2f}%") | |
| print(f" Median: {percentile(tool_fracs, 50):>6.2f}%") | |
| print(f" P95: {percentile(tool_fracs, 95):>6.2f}%") | |
| print(f" Max: {max(tool_fracs):>6.2f}%") | |
| def analyze_reasoning_vs_tokens(traces: list[dict]): | |
| """Relationship between reasoning effort and output.""" | |
| section("Reasoning Effort Analysis") | |
| steps_with = [] | |
| steps_without = [] | |
| for t in traces: | |
| for s in t.get("llm_steps", []): | |
| rc = s.get("reasoning_content") | |
| out_tok = s.get("output_tokens", 0) or 0 | |
| in_tok = s.get("input_tokens", 0) or 0 | |
| if rc: | |
| steps_with.append({ | |
| "reasoning_chars": len(rc), | |
| "output_tokens": out_tok, | |
| "input_tokens": in_tok, | |
| "has_tool_call": bool(s.get("tool_calls")), | |
| }) | |
| else: | |
| steps_without.append({"output_tokens": out_tok}) | |
| print(f" Steps with reasoning: {len(steps_with)}") | |
| print(f" Steps without reasoning: {len(steps_without)}") | |
| if steps_with: | |
| rc_lens = [s["reasoning_chars"] for s in steps_with] | |
| out_toks = [s["output_tokens"] for s in steps_with] | |
| in_toks = [s["input_tokens"] for s in steps_with] | |
| # Estimate reasoning tokens (~4 chars per token for English) | |
| reasoning_toks_est = [s["reasoning_chars"] / 4 for s in steps_with] | |
| content_toks = [s["output_tokens"] - r for s, r in zip(steps_with, reasoning_toks_est)] | |
| print(f"\n Reasoning length (chars):") | |
| print(f" Median: {percentile(rc_lens, 50):,.0f}") | |
| print(f" P95: {percentile(rc_lens, 95):,.0f}") | |
| print(f"\n Output tokens (includes reasoning):") | |
| print(f" Median: {percentile(out_toks, 50):,.0f}") | |
| print(f" Total: {sum(out_toks):,}") | |
| print(f"\n Estimated reasoning tokens (~chars/4):") | |
| print(f" Total: {sum(reasoning_toks_est):,.0f}") | |
| print(f" As % of output tokens: {100*sum(reasoning_toks_est)/max(sum(out_toks),1):.1f}%") | |
| # Tool-calling steps vs final-answer steps | |
| tc_steps = [s for s in steps_with if s["has_tool_call"]] | |
| fa_steps = [s for s in steps_with if not s["has_tool_call"]] | |
| if tc_steps and fa_steps: | |
| tc_reason = [s["reasoning_chars"] for s in tc_steps] | |
| fa_reason = [s["reasoning_chars"] for s in fa_steps] | |
| print(f"\n Reasoning by step type:") | |
| print(f" Tool-calling steps: median {percentile(tc_reason, 50):,.0f} chars ({len(tc_steps)} steps)") | |
| print(f" Final-answer steps: median {percentile(fa_reason, 50):,.0f} chars ({len(fa_steps)} steps)") | |
| def analyze_error_recovery(traces: list[dict]): | |
| """How do multi-step traces with errors behave?""" | |
| section("Error Recovery Patterns") | |
| error_traces = [] | |
| clean_traces = [] | |
| for t in traces: | |
| spans = t.get("spans", []) | |
| has_error = any(s.get("exit_code", 0) != 0 for s in spans) | |
| n_steps = len(t.get("llm_steps", [])) | |
| if has_error: | |
| error_traces.append(t) | |
| elif n_steps > 1: | |
| clean_traces.append(t) | |
| print(f" Traces with tool errors: {len(error_traces)}") | |
| print(f" Clean multi-step traces: {len(clean_traces)}") | |
| if error_traces: | |
| error_steps = [len(t.get("llm_steps", [])) for t in error_traces] | |
| clean_steps = [len(t.get("llm_steps", [])) for t in clean_traces] if clean_traces else [0] | |
| print(f"\n Steps in error traces: median={percentile(error_steps, 50):.0f}, max={max(error_steps)}") | |
| if clean_traces: | |
| print(f" Steps in clean traces: median={percentile(clean_steps, 50):.0f}, max={max(clean_steps)}") | |
| error_durations = [t["total_duration_ms"] for t in error_traces] | |
| clean_durations = [t["total_duration_ms"] for t in clean_traces] if clean_traces else [0] | |
| print(f"\n Duration of error traces: median={percentile(error_durations, 50)/1000:.1f}s") | |
| if clean_traces: | |
| print(f" Duration of clean traces: median={percentile(clean_durations, 50)/1000:.1f}s") | |
| def analyze_bash_telemetry(traces: list[dict]): | |
| """Detailed telemetry breakdown for bash spans.""" | |
| section("Bash Telemetry Detail") | |
| bash_spans = [] | |
| for t in traces: | |
| for s in t.get("spans", []): | |
| if s.get("tool_name") == "bash": | |
| bash_spans.append(s) | |
| if not bash_spans: | |
| print(" No bash spans found.") | |
| return | |
| print(f" Total bash spans: {len(bash_spans)}") | |
| wall = [s["duration_ms"] for s in bash_spans] | |
| cpu = [s["telemetry"]["user_time_s"] + s["telemetry"]["system_time_s"] | |
| for s in bash_spans if s["telemetry"]["user_time_s"] > 0] | |
| rss = [s["telemetry"]["max_rss_bytes"] / 1024 / 1024 for s in bash_spans | |
| if s["telemetry"]["max_rss_bytes"] > 0] | |
| read_b = [s["telemetry"]["read_bytes"] for s in bash_spans | |
| if s["telemetry"]["read_bytes"] > 0] | |
| print(f"\n Wall-clock (ms): median={percentile(wall, 50):.1f}, P95={percentile(wall, 95):.1f}, max={max(wall):.1f}") | |
| if cpu: | |
| print(f" CPU time (ms): median={percentile(cpu, 50)*1000:.1f}, P95={percentile(cpu, 95)*1000:.1f}, max={max(cpu)*1000:.1f}") | |
| # CPU efficiency: cpu_time / wall_time | |
| efficiencies = [] | |
| for s in bash_spans: | |
| ct = s["telemetry"]["user_time_s"] + s["telemetry"]["system_time_s"] | |
| wt = s["duration_ms"] / 1000 | |
| if ct > 0 and wt > 0: | |
| efficiencies.append(ct / wt * 100) | |
| if efficiencies: | |
| print(f" CPU/Wall ratio: median={percentile(efficiencies, 50):.1f}%, max={max(efficiencies):.1f}%") | |
| if rss: | |
| print(f" Peak RSS (MB): median={percentile(rss, 50):.1f}, max={max(rss):.1f}") | |
| if read_b: | |
| print(f" Read bytes: median={percentile(read_b, 50):,.0f}, max={max(read_b):,}") | |
| def analyze_comparison_table(all_traces: dict[str, list[dict]]): | |
| """Side-by-side comparison for the paper.""" | |
| section("Comparison Table (for paper)") | |
| print(f" {'':30s} ", end="") | |
| for name in all_traces: | |
| print(f"{name:>20s} ", end="") | |
| print() | |
| print(f" {'─'*30} ", end="") | |
| for _ in all_traces: | |
| print(f"{'─'*20} ", end="") | |
| print() | |
| def row(label, fn): | |
| print(f" {label:30s} ", end="") | |
| for name, traces in all_traces.items(): | |
| val = fn(traces) | |
| print(f"{val:>20s} ", end="") | |
| print() | |
| row("Traces", lambda t: str(len(t))) | |
| row("Tool spans", lambda t: str(sum(len(x.get("spans", [])) for x in t))) | |
| row("LLM steps", lambda t: str(sum(len(x.get("llm_steps", [])) for x in t))) | |
| row("Median duration (s)", lambda t: f"{percentile([x['total_duration_ms'] for x in t], 50)/1000:.1f}") | |
| row("Median steps/trace", lambda t: f"{percentile([len(x.get('llm_steps',[])) for x in t], 50):.0f}") | |
| def tool_names(traces): | |
| tools = Counter() | |
| for t in traces: | |
| for s in t.get("spans", []): | |
| if s["tool_name"] != "final_answer": | |
| tools[s["tool_name"]] += 1 | |
| return ", ".join(f"{n}({c})" for n, c in tools.most_common(3)) or "none" | |
| row("Tools used", tool_names) | |
| def error_rate(traces): | |
| spans = [s for t in traces for s in t.get("spans", []) if s["tool_name"] != "final_answer"] | |
| errors = [s for s in spans if s.get("exit_code", 0) != 0] | |
| if not spans: | |
| return "n/a" | |
| return f"{100*len(errors)/len(spans):.0f}%" | |
| row("Tool error rate", error_rate) | |
| def reasoning_pct(traces): | |
| steps = [s for t in traces for s in t.get("llm_steps", [])] | |
| with_r = [s for s in steps if s.get("reasoning_content")] | |
| if not steps: | |
| return "n/a" | |
| return f"{100*len(with_r)/len(steps):.0f}%" | |
| row("Reasoning coverage", reasoning_pct) | |
| def cpu_spans(traces): | |
| spans = [s for t in traces for s in t.get("spans", [])] | |
| with_cpu = [s for s in spans if s.get("telemetry", {}).get("user_time_s", 0) > 0] | |
| return f"{len(with_cpu)}/{len(spans)}" | |
| row("Spans with CPU telemetry", cpu_spans) | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Deep analysis for paper") | |
| parser.add_argument("inputs", nargs="+", help="Input JSONL files") | |
| args = parser.parse_args() | |
| all_traces = {} | |
| for path in args.inputs: | |
| p = Path(path) | |
| if not p.exists(): | |
| print(f"Skipping {path} (not found)", file=sys.stderr) | |
| continue | |
| traces = load_traces(str(p)) | |
| label = p.stem # e.g. "mbpp_0_6B" | |
| all_traces[label] = traces | |
| print(f"Loaded {path}: {len(traces)} traces") | |
| # Per-file analysis | |
| for name, traces in all_traces.items(): | |
| print(f"\n{'#' * 70}") | |
| print(f"# {name}") | |
| print(f"{'#' * 70}") | |
| analyze_time_breakdown(traces) | |
| analyze_reasoning_vs_tokens(traces) | |
| analyze_error_recovery(traces) | |
| analyze_bash_telemetry(traces) | |
| # Cross-file comparison | |
| if len(all_traces) > 1: | |
| analyze_comparison_table(all_traces) | |
| print() | |
| if __name__ == "__main__": | |
| main() | |