Download data/processed/RQ2/plot_model_overhead_bars_a2a.py from AINativeOps/AINativeBench: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/datasets/AINativeOps/AINativeBench/resolve/main/data/processed/RQ2/plot_model_overhead_bars_a2a.py
- Command line
-
hf download hf://datasets/AINativeOps/AINativeBench/data/processed/RQ2/plot_model_overhead_bars_a2a.py
-
curl -L -o plot_model_overhead_bars_a2a.py https://huggingface.co/datasets/AINativeOps/AINativeBench/resolve/main/data/processed/RQ2/plot_model_overhead_bars_a2a.py
15.1 kB
| #!/usr/bin/env python3 | |
| """Plot per-model non-LLM overhead breakdown across models for *A2A projects. | |
| Usage: | |
| python plot_model_overhead_bars_a2a.py | |
| This script scans all direct subdirectories under the current "Part2" folder | |
| whose names end with "-A2A" (e.g. RecruitmentAssistant-A2A). | |
| If a subdirectory contains a "performance_breakdown_summary_by_model.csv", | |
| we read that file and, for that project, contribute one stacked bar in a | |
| combined figure: | |
| - One figure aggregating all A2A projects. | |
| - On the x-axis, each A2A project is one bar group (same order as mix version): | |
| SQLAssistant-A2A, | |
| RecruitmentAssistant-A2A, | |
| LandingPageGenerator-A2A, | |
| SocialMediaManager-A2A, | |
| BookWriter-A2A. | |
| - For each project, the bar is stacked by the following components (ms totals | |
| over all runs and all models in that project, then normalized within the bar): | |
| total_Tool_OVERHEAD, | |
| total_Framework_OVERHEAD, | |
| total_A2A_OVERHEAD, | |
| total_Server_OVERHEAD. | |
| - Within a bar, these 4 components are normalized so that the total bar | |
| height is 1.0 (Latency Breakdown from 0 to 1). | |
| - Each segment is annotated with its percentage of the bar (two decimals). | |
| The resulting PDF is written into the Part2 folder as | |
| "model_overhead_bars_a2a.pdf". | |
| """ | |
| import csv | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Dict, List | |
| import math | |
| import matplotlib.pyplot as plt | |
| from matplotlib.ticker import FuncFormatter | |
| # Use a serif font similar to "New Roma time" for all text | |
| plt.rcParams["font.family"] = "Times New Roman" | |
| # Fixed model order (must match the names used in the CSV files) | |
| MODEL_ORDER: List[str] = [ | |
| "GPT-5", | |
| "GPT-4o-mini", | |
| "DeepSeek-V3-1", | |
| "DeepSeek-R1", | |
| "Gemini-2.5-flash", | |
| "Gemini-2.5-flash-nothinking", | |
| "Qwen3-235b", | |
| ] | |
| # Optional display labels | |
| MODEL_LABELS: Dict[str, str] = { | |
| "GPT-5": "GPT-5", | |
| "GPT-4o-mini": "GPT-4o-mini", | |
| "DeepSeek-V3-1": "DeepSeek-V3.1", | |
| "DeepSeek-R1": "DeepSeek-R1", | |
| "Gemini-2.5-flash": "Gemini-2.5", | |
| "Gemini-2.5-flash-nothinking": "Gemini-2.5-NT", | |
| "Qwen3-235b": "Qwen3-235b", | |
| } | |
| # Short labels for project (A2A) names on the x-axis | |
| PROJECT_LABELS: Dict[str, str] = { | |
| "SQLAssistant-A2A": "SQL Asst.", | |
| "RecruitmentAssistant-A2A": "Recruitment", | |
| "LandingPageGenerator-A2A": "Landing Pg.", | |
| "SocialMediaManager-A2A": "Social M. M.", | |
| "BookWriter-A2A": "Write Book", | |
| "__overall__": "Overall", | |
| } | |
| # Components to visualize (key in CSV -> logical name -> color) | |
| COMPONENT_KEYS: List[str] = [ | |
| "total_Tool_OVERHEAD", | |
| "total_Framework_OVERHEAD", | |
| "total_A2A_OVERHEAD", | |
| "total_Server_OVERHEAD", | |
| ] | |
| COMPONENT_LABELS: Dict[str, str] = { | |
| "total_Tool_OVERHEAD": "Tool", | |
| "total_Framework_OVERHEAD": "Framework", | |
| "total_A2A_OVERHEAD": "A2A", | |
| "total_Server_OVERHEAD": "Server", | |
| } | |
| COMPONENT_COLORS: Dict[str, str] = { | |
| # Custom conference-style palette (low saturation, easily distinguishable) | |
| "total_Tool_OVERHEAD": "#88a4c9", | |
| "total_Framework_OVERHEAD": "#ff8696", | |
| "total_A2A_OVERHEAD": "#bbe6dd", | |
| "total_Server_OVERHEAD": "#fde8b2", | |
| } | |
| def find_model_summary_csvs_for_a2a(root: Path) -> List[Path]: | |
| """Find all performance_breakdown_summary_by_model.csv under *-A2A subdirs.""" | |
| csv_paths: List[Path] = [] | |
| for sub in root.iterdir(): | |
| if not sub.is_dir(): | |
| continue | |
| if not sub.name.endswith("-A2A"): | |
| continue | |
| candidate = sub / "performance_breakdown_summary_by_model.csv" | |
| if candidate.exists(): | |
| csv_paths.append(candidate) | |
| csv_paths.sort() | |
| return csv_paths | |
| def load_model_components(csv_path: Path) -> Dict[str, Dict[str, float]]: | |
| """Load per-model component times from a summary CSV. | |
| Returns: | |
| data[model][component_key] = value_ms | |
| """ | |
| data: Dict[str, Dict[str, float]] = defaultdict(dict) | |
| with csv_path.open("r", encoding="utf-8", newline="") as f: | |
| reader = csv.DictReader(f) | |
| for row in reader: | |
| model = (row.get("model") or "").strip() | |
| if not model: | |
| continue | |
| for key in COMPONENT_KEYS: | |
| try: | |
| val = float(row.get(key, "0") or 0) | |
| except ValueError: | |
| val = 0.0 | |
| data[model][key] = val | |
| return data | |
| def compute_percent_labels(shares: List[float]) -> List[float]: | |
| total = sum(shares) | |
| if total <= 0.0: | |
| return [0.0 for _ in shares] | |
| raw = [(s / total) * 10000.0 for s in shares] | |
| floors = [int(math.floor(r)) for r in raw] | |
| floor_sum = sum(floors) | |
| diff = 10000 - floor_sum | |
| remainders = [r - f for r, f in zip(raw, floors)] | |
| order = sorted(range(len(shares)), key=lambda i: remainders[i], reverse=True) | |
| if diff > 0: | |
| for k in range(min(diff, len(order))): | |
| floors[order[k]] += 1 | |
| elif diff < 0: | |
| for k in range(min(-diff, len(order))): | |
| floors[order[-1 - k]] -= 1 | |
| return [v / 100.0 for v in floors] | |
| def compute_a2a_component_shares( | |
| csv_paths: List[Path], | |
| ) -> Dict[str, Dict[str, float]]: | |
| """Compute component shares for each A2A project. | |
| For each project, we first sum the component times across all models, | |
| then normalize by the total non-LLM overhead (sum of 4 components). | |
| """ | |
| project_shares: Dict[str, Dict[str, float]] = {} | |
| project_weights: Dict[str, float] = {} | |
| for csv_path in csv_paths: | |
| project_name = csv_path.parent.name | |
| model_to_components = load_model_components(csv_path) | |
| if not model_to_components: | |
| print(f" no model data in {csv_path}, leaving empty placeholder") | |
| project_shares[project_name] = {k: 0.0 for k in COMPONENT_KEYS} | |
| continue | |
| sums = {k: 0.0 for k in COMPONENT_KEYS} | |
| total_ms_sum = 0.0 | |
| # Aggregate over models | |
| for model in MODEL_ORDER: | |
| comps = model_to_components.get(model) | |
| if not comps: | |
| continue | |
| ms_vals = [float(comps.get(k, 0.0) or 0.0) for k in COMPONENT_KEYS] | |
| total_ms = sum(ms_vals) | |
| if total_ms <= 0.0: | |
| continue | |
| total_ms_sum += total_ms | |
| for key, val in zip(COMPONENT_KEYS, ms_vals): | |
| sums[key] += val | |
| if total_ms_sum <= 0.0: | |
| print( | |
| f" all models have zero non-LLM overhead for {project_name}; " | |
| "leaving empty placeholder" | |
| ) | |
| project_shares[project_name] = {k: 0.0 for k in COMPONENT_KEYS} | |
| project_weights[project_name] = 0.0 | |
| continue | |
| project_shares[project_name] = {k: (v / total_ms_sum) for k, v in sums.items()} | |
| project_weights[project_name] = total_ms_sum | |
| return project_shares, project_weights | |
| def plot_model_overhead_bars_a2a( | |
| project_names: List[str], | |
| project_shares: Dict[str, Dict[str, float]], | |
| out_dir: Path, | |
| ) -> None: | |
| """Plot stacked bars for all A2A projects (one bar per project). | |
| - Each bar corresponds to one A2A project. | |
| - Each bar is stacked by the four non-LLM overhead components listed | |
| in COMPONENT_KEYS, normalized to height 1.0. | |
| - Each segment is annotated with its percentage value. | |
| """ | |
| x = list(range(len(project_names))) | |
| # Prepare per-component shares per project (already normalized) | |
| shares_by_comp: Dict[str, List[float]] = {k: [] for k in COMPONENT_KEYS} | |
| for name in project_names: | |
| shares = project_shares.get(name, {}) | |
| for key in COMPONENT_KEYS: | |
| shares_by_comp[key].append(float(shares.get(key, 0.0) or 0.0)) | |
| fig, ax = plt.subplots(figsize=(max(7.5, 1.0 * len(project_names)), 7)) | |
| # Build stacked bars | |
| bottoms = [0.0 for _ in x] | |
| bar_handles = {} | |
| bar_width = 0.98 | |
| for key in COMPONENT_KEYS: | |
| heights = shares_by_comp[key] | |
| color = COMPONENT_COLORS[key] | |
| bars = ax.bar( | |
| x, | |
| heights, | |
| bottom=bottoms, | |
| color=color, | |
| edgecolor="none", # no bar borders | |
| width=bar_width, | |
| ) | |
| bar_handles[key] = bars | |
| # Update bottoms for next component | |
| bottoms = [b + h for b, h in zip(bottoms, heights)] | |
| # Reduce inner left/right whitespace inside the axes: make the outer | |
| # bars almost touch the plot boundaries. | |
| margin = (1.0 - bar_width) / 2.0 | |
| ax.set_xlim(-0.5 + margin, len(project_names) - 0.5 - margin) | |
| # Annotate percentage values for each segment (skip zeros) | |
| min_gap = 0.04 # minimum vertical gap between labels (in data coords 0-1) | |
| for idx, name in enumerate(project_names): | |
| shares = [ | |
| float(project_shares.get(name, {}).get(k, 0.0) or 0.0) | |
| for k in COMPONENT_KEYS | |
| ] | |
| active_indices = [i for i, s in enumerate(shares) if s > 0.0] | |
| if not active_indices: | |
| continue | |
| active_shares = [shares[i] for i in active_indices] | |
| active_percents = compute_percent_labels(active_shares) | |
| # Build label entries: [y_center, x_center, text] | |
| label_entries = [] | |
| for local_pos, comp_idx in enumerate(active_indices): | |
| key = COMPONENT_KEYS[comp_idx] | |
| share = shares[comp_idx] | |
| percent = active_percents[local_pos] | |
| if share <= 0.0: | |
| continue | |
| bars = bar_handles[key] | |
| bar = bars[idx] | |
| x_center = bar.get_x() + bar.get_width() / 2.0 | |
| y_center = bar.get_y() + bar.get_height() / 2.0 | |
| label_entries.append([y_center, x_center, f"{percent:.2f}"]) | |
| # Nudge overlapping labels apart | |
| if len(label_entries) > 1: | |
| for _ in range(50): | |
| label_entries.sort(key=lambda e: e[0]) | |
| changed = False | |
| for i in range(1, len(label_entries)): | |
| y_prev = label_entries[i - 1][0] | |
| y_curr = label_entries[i][0] | |
| if y_curr - y_prev < min_gap: | |
| needed = min_gap - (y_curr - y_prev) | |
| label_entries[i - 1][0] = y_prev - needed / 2.0 | |
| label_entries[i][0] = y_curr + needed / 2.0 | |
| changed = True | |
| if not changed: | |
| break | |
| for y_center, x_center, text in label_entries: | |
| ax.text( | |
| x_center, | |
| y_center, | |
| text, | |
| ha="center", | |
| va="center", | |
| fontsize=22, | |
| fontweight="bold", | |
| ) | |
| # X axis labels: one per A2A project (use short labels where available) | |
| tick_labels = [PROJECT_LABELS.get(name, name) for name in project_names] | |
| ax.set_xticks(x) | |
| ax.set_xticklabels(tick_labels, rotation=30, ha="right") | |
| # Enlarge tick label fonts on both axes | |
| ax.tick_params(axis="x", labelsize=18, pad=6) | |
| ax.tick_params(axis="y", labelsize=24) | |
| for label in ax.get_xticklabels(): | |
| label.set_fontweight("bold") | |
| for label in ax.get_yticklabels(): | |
| label.set_fontweight("bold") | |
| ax.set_ylim(0.0, 1.0) | |
| ax.set_ylabel("(%)", fontsize=21, fontweight="bold", labelpad=-10) | |
| # Show y-axis ticks as plain integers | |
| ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y * 100:.0f}")) | |
| # Legend at top, horizontal, with inline "Component" label. | |
| # Use border-free patches in the legend as well. | |
| handles = [ | |
| plt.Rectangle((0, 0), 1, 1, facecolor="none", edgecolor="none"), | |
| ] | |
| labels = ["Component"] | |
| # Legend order follows bar stack order from top to bottom: | |
| # Server (top), A2A, Framework, Tool (bottom). | |
| legend_order_keys = list(reversed(COMPONENT_KEYS)) | |
| for key in legend_order_keys: | |
| handles.append( | |
| plt.Rectangle( | |
| (0, 0), | |
| 1, | |
| 1, | |
| facecolor=COMPONENT_COLORS[key], | |
| edgecolor="none", | |
| ) | |
| ) | |
| labels.append(COMPONENT_LABELS[key]) | |
| legend = ax.legend( | |
| handles, | |
| labels, | |
| fontsize=19, | |
| loc="upper left", | |
| bbox_to_anchor=(-0.06, 1.09), | |
| ncol=len(labels), # all legend items in a single horizontal row | |
| frameon=False, | |
| columnspacing=0.8, | |
| handletextpad=0.5, | |
| handlelength=0.3, | |
| prop={"weight": "bold", "size": 19}, | |
| ) | |
| # Make the heading label slightly larger | |
| legend_texts = legend.get_texts() | |
| if legend_texts: | |
| legend_texts[0].set_fontsize(20) | |
| legend_texts[0].set_fontweight("bold") | |
| # Tighten layout and crop extra whitespace (especially left/right) | |
| fig.tight_layout(pad=0.0) | |
| out_file = out_dir / "model_overhead_bars_a2a.pdf" | |
| fig.savefig(out_file, dpi=200, bbox_inches="tight", pad_inches=0.02) | |
| plt.close(fig) | |
| print(f"saved figure: {out_file}") | |
| def main() -> None: | |
| # Assume this script is placed in Part2 directory | |
| part2_dir = Path(__file__).resolve().parent | |
| # Collect all *-A2A subdirectories under Part2 (whether they have data or not) | |
| a2a_dirs = [ | |
| sub for sub in part2_dir.iterdir() if sub.is_dir() and sub.name.endswith("-A2A") | |
| ] | |
| a2a_dirs.sort(key=lambda p: p.name) | |
| if not a2a_dirs: | |
| print("no *-A2A subdirs found under Part2") | |
| return | |
| csv_paths = [] | |
| for d in a2a_dirs: | |
| csv_path = d / "performance_breakdown_summary_by_model.csv" | |
| if not csv_path.exists(): | |
| print( | |
| f"no performance_breakdown_summary_by_model.csv in {d}, " | |
| "leaving empty placeholder" | |
| ) | |
| csv_paths.append(csv_path) | |
| # Filter out those without actual CSV files for computing shares | |
| existing_csv_paths = [p for p in csv_paths if p.exists()] | |
| if not existing_csv_paths: | |
| print("no model data in any *-A2A project; nothing to plot") | |
| return | |
| project_shares, project_weights = compute_a2a_component_shares(existing_csv_paths) | |
| project_names = [d.name for d in a2a_dirs] | |
| total_weight = 0.0 | |
| for name in project_names: | |
| total_weight += float(project_weights.get(name, 0.0) or 0.0) | |
| if total_weight > 0.0: | |
| overall = {k: 0.0 for k in COMPONENT_KEYS} | |
| for name in project_names: | |
| weight = float(project_weights.get(name, 0.0) or 0.0) | |
| if weight <= 0.0: | |
| continue | |
| shares = project_shares.get(name, {}) | |
| for key in COMPONENT_KEYS: | |
| overall[key] += float(shares.get(key, 0.0) or 0.0) * weight | |
| for key in COMPONENT_KEYS: | |
| overall[key] = overall[key] / total_weight | |
| project_shares["__overall__"] = overall | |
| project_names_with_overall = project_names + ["__overall__"] | |
| else: | |
| project_names_with_overall = project_names | |
| plot_model_overhead_bars_a2a(project_names_with_overall, project_shares, part2_dir) | |
| if __name__ == "__main__": | |
| main() | |