File size: 13,928 Bytes
8c10cf2 | 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | #!/usr/bin/env python3
"""Plot per-model non-LLM overhead breakdown across models for *mix projects.
Usage:
python plot_model_overhead_bars_mix.py
This script scans all direct subdirectories under the current "Part2" folder
whose names end with "mix" (e.g. RecruitmentAssistant-H_A2A).
If a subdirectory contains a "performance_breakdown_summary_by_model.csv",
we read that file and, for that project, generate one stacked bar chart:
- One figure per project (per CSV).
- In each figure there are up to 7 bars, one per model, with fixed
left-to-right order:
GPT-5, GPT-4o-mini, DeepSeek-V3-1, DeepSeek-R1,
Gemini-2.5-flash, Gemini-2.5-flash-nothinking, Qwen3-235b.
- Each bar is stacked by the following components (ms totals over all runs):
total_Tool_OVERHEAD,
total_A2A_OVERHEAD,
total_LangGraph_Framework_OVERHEAD,
total_CrewAI_Framework_OVERHEAD,
total_AutoGen_Framework_OVERHEAD,
total_Server_OVERHEAD.
- Within a bar, these 6 components are normalized so that the total bar
height is 1.0 (Latency Breakdown from 0 to 1).
- Each segment is annotated with its absolute time in ms.
The resulting PNG is written into each project folder as
"model_overhead_bars_mix.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 (mix) names on the x-axis
PROJECT_LABELS: Dict[str, str] = {
"SQLAssistant-H_A2A": "SQL Asst.",
"RecruitmentAssistant-H_A2A": "Recruitment",
"LandingPageGenerator-H_A2A": "Landing Pg.",
"SocialMediaManager-H_A2A": "Social M. M.",
"BookWriter-H_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(root: Path) -> List[Path]:
"""Find all performance_breakdown_summary_by_model.csv under *mix subdirs."""
csv_paths: List[Path] = []
for sub in root.iterdir():
if not sub.is_dir():
continue
if not sub.name.endswith("mix"):
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_mix_component_shares(
model_to_components: Dict[str, Dict[str, float]],
) -> Dict[str, float]:
"""Compute average component shares across models for one mix project."""
# Weighted by absolute non-LLM time (sum of the four components) so that
# models with more total non-LLM overhead contribute proportionally more.
sums = {k: 0.0 for k in COMPONENT_KEYS}
total_ms_sum = 0.0
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(" all models have zero non-LLM overhead; leaving empty placeholder")
return {k: 0.0 for k in COMPONENT_KEYS}, 0.0
shares = {k: v / total_ms_sum for k, v in sums.items()}
return shares, total_ms_sum
def plot_model_overhead_bars(
project_names: List[str],
mix_shares: Dict[str, Dict[str, float]],
out_dir: Path,
) -> None:
"""Plot stacked bars for one project across all models.
- One bar per model (7 bars total, some may be missing if no data).
- 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 absolute ms value.
"""
x = list(range(len(project_names)))
# Prepare per-component shares per mix (already normalized)
shares_by_comp: Dict[str, List[float]] = {k: [] for k in COMPONENT_KEYS}
for name in project_names:
shares = mix_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)), 5))
# 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)
for idx, name in enumerate(project_names):
shares = [
float(mix_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)
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]
# Explicitly compute the horizontal center of the bar segment
x_center = bar.get_x() + bar.get_width() / 2.0
y_center = bar.get_y() + bar.get_height() / 2.0
ax.text(
x_center,
y_center,
f"{percent:.2f}",
ha="center",
va="center",
fontsize=16,
)
# X axis labels: one per mix 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="both", labelsize=14)
ax.set_ylim(0.0, 1.0)
ax.set_ylabel("Latency Breakdown (%)", fontsize=18)
# Show y-axis ticks as percentages (0-100), using a formatter to avoid warnings
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y * 100:.2f}"))
# 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=14,
loc="upper left",
# Keep Component near the y-axis label, but avoid extending the
# legend too far left, which would create extra whitespace on the
# right after tight cropping.
bbox_to_anchor=(-0.08, 1.12),
ncol=len(labels), # all legend items in a single horizontal row
frameon=False,
columnspacing=0.8,
handletextpad=0.5,
)
# Make only the "Component" label in the legend match the y-axis label size
legend_texts = legend.get_texts()
if legend_texts:
legend_texts[0].set_fontsize(18)
# Tighten layout and crop extra whitespace (especially left/right)
fig.tight_layout(pad=0.0)
out_file = out_dir / "model_overhead_bars_mix.pdf"
# Use bbox_inches="tight" and a very small pad so that the figure
# boundary fully contains the axes spines (including the right border)
# without introducing visible extra whitespace.
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 *mix subdirectories under Part2 (whether they have data or not)
mix_dirs = [
sub for sub in part2_dir.iterdir() if sub.is_dir() and sub.name.endswith("mix")
]
mix_dirs.sort(key=lambda p: p.name)
if not mix_dirs:
print("no *mix subdirs found under Part2")
return
mix_shares: Dict[str, Dict[str, float]] = {}
project_weights: Dict[str, float] = {}
any_data = False
for mix_dir in mix_dirs:
project_name = mix_dir.name
csv_path = mix_dir / "performance_breakdown_summary_by_model.csv"
if not csv_path.exists():
print(
f"no performance_breakdown_summary_by_model.csv in {mix_dir}, "
"leaving empty placeholder"
)
mix_shares[project_name] = {k: 0.0 for k in COMPONENT_KEYS}
continue
print(f"processing {csv_path} (project={project_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")
mix_shares[project_name] = {k: 0.0 for k in COMPONENT_KEYS}
continue
shares, weight = compute_mix_component_shares(model_to_components)
mix_shares[project_name] = shares
project_weights[project_name] = weight
any_data = True
if not any_data:
print("no model data in any *mix project; nothing to plot")
return
project_names = [d.name for d in mix_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 = mix_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
mix_shares["__overall__"] = overall
project_names_with_overall = project_names + ["__overall__"]
else:
project_names_with_overall = project_names
plot_model_overhead_bars(project_names_with_overall, mix_shares, part2_dir)
if __name__ == "__main__":
main()
|