lsv / lsvbench /plots.py
smerkd's picture
Initial commit
f91d9a0 verified
Raw
History Blame Contribute Delete
11.6 kB
"""Standard matplotlib plots for benchmark reports."""
from __future__ import annotations
from pathlib import Path
from typing import Any
import matplotlib.pyplot as plt
TASK_METRICS = {
"monitoring_step": {
"source_task": "monitoring_step",
"label": "Step Prediction",
"balanced_accuracy": "step_balanced_accuracy",
"f1": "step_macro_f1",
"precision": "step_macro_precision",
"recall": "step_macro_recall",
"accuracy": "step_identification_accuracy",
"parse_success": "parse_success_rate",
},
"monitor_next_step": {
"source_task": "monitor_next_step",
"label": "Advance Prediction",
"balanced_accuracy": "advance_step_balanced_accuracy",
"f1": "advance_step_macro_f1",
"precision": "advance_step_macro_precision",
"recall": "advance_step_macro_recall",
"accuracy": "advance_step_accuracy",
"parse_success": "parse_success_rate",
},
"pmd_detection": {
"source_task": "pmd",
"label": "Error Detection",
"balanced_accuracy": "binary_balanced_accuracy",
"f1": "binary_macro_f1",
"precision": "binary_macro_precision",
"recall": "binary_macro_recall",
"accuracy": "binary_accuracy",
"parse_success": "parse_success_rate",
},
}
TASK_LABELS = {
"monitoring_step": "Step Prediction",
"monitor_next_step": "Advance Prediction",
"pmd": "Error Detection",
"pmd_detection": "Error Detection",
}
LSV_BALANCED_PANELS = [
("monitoring_step", "step_balanced_accuracy", "Protocol Monitoring Step\nPrediction Accuracy"),
("monitor_next_step", "advance_step_balanced_accuracy", "Protocol Monitoring Step\nAdvanced Prediction Accuracy"),
("pmd", "binary_balanced_accuracy", "Error Detection"),
]
MODEL_STYLE = {
"cosmos_reason": ("Cosmos\nReason", "#6B7280"),
"qwen25vl_7b": ("Qwen2.5\n7B", "#8C6D31"),
"labos7b_lora750": ("LabOS\nVLM 7B", "#2A7F62"),
"qwen25vl_32b": ("Qwen2.5\n32B", "#B08A3C"),
"labos32b_lora750": ("LabOS\nVLM 32B", "#1F6B53"),
"labos7b_lora750_hf": ("LabOS\nVLM 7B HF", "#2A7F62"),
}
def _value(summary: dict[str, Any], metric: str) -> float:
value = summary.get(metric)
return float(value) * 100.0 if isinstance(value, (int, float)) else 0.0
def _sem(summary: dict[str, Any], metric: str) -> float:
value = summary.get(f"{metric}_sem")
return float(value) * 100.0 if isinstance(value, (int, float)) else 0.0
def _model_style(row: dict[str, Any]) -> tuple[str, str]:
key = str(row.get("model_key") or row.get("model_label") or "")
label = str(row.get("model_label") or key)
if key in MODEL_STYLE:
return MODEL_STYLE[key]
if label in MODEL_STYLE:
return MODEL_STYLE[label]
pretty = label.replace("_", "\n")
return pretty, "#4F9B7B"
def _paper_x_positions(labels: list[str]) -> list[float]:
positions: list[float] = []
current = 0.0
previous = ""
for idx, label in enumerate(labels):
flat_label = label.replace("\n", " ")
if idx == 0:
current = 0.0
elif "Cosmos" in previous:
current += 1.25
elif "32B" in flat_label and "32B" not in previous:
current += 1.02
else:
current += 0.68
positions.append(current)
previous = flat_label
return positions
def _paper_group_separators(labels: list[str], x: list[float]) -> list[float]:
separators: list[float] = []
for idx in range(len(labels) - 1):
left = labels[idx].replace("\n", " ")
right = labels[idx + 1].replace("\n", " ")
if "Cosmos" in left or ("32B" in right and "32B" not in left):
separators.append((x[idx] + x[idx + 1]) / 2.0)
return separators
def plot_lsv_balanced_accuracy(model_results: list[dict[str, Any]], output_path: Path) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
labels: list[str] = []
colors: list[str] = []
for row in model_results:
label, color = _model_style(row)
labels.append(label)
colors.append(color)
x = _paper_x_positions(labels)
fig, axes = plt.subplots(1, 3, figsize=(9.4, 3.25), sharey=True)
for ax, (task_name, metric, title) in zip(axes, LSV_BALANCED_PANELS, strict=True):
values = []
errors = []
for row in model_results:
summary = row["tasks"].get(task_name, {})
values.append(_value(summary, metric))
errors.append(_sem(summary, metric))
bars = ax.bar(
x,
values,
width=0.66,
color=colors,
edgecolor="#2F2F2F",
linewidth=0.5,
yerr=errors,
capsize=2.5,
error_kw={"elinewidth": 0.8, "capthick": 0.8, "ecolor": "#333333"},
)
for bar, value, error in zip(bars, values, errors, strict=True):
ax.text(
bar.get_x() + bar.get_width() / 2,
value + error + 1.2,
f"{value:.0f}",
ha="center",
va="bottom",
fontsize=7,
clip_on=False,
)
ax.set_title(title, fontsize=10)
ax.set_ylim(0, 80)
ax.set_xticks(x)
ax.set_xticklabels(labels, fontsize=7)
for tick in ax.get_xticklabels():
if "LabOS" in tick.get_text():
tick.set_fontweight("bold")
for separator in _paper_group_separators(labels, x):
ax.axvline(separator, color="#6B7280", linewidth=0.6, alpha=0.35)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
axes[0].set_ylabel(r"Accuracy (%) $\pm$ SEM")
fig.suptitle("LSV Benchmark v1", y=0.98, fontsize=11)
fig.tight_layout(pad=0.7, rect=(0, 0, 1, 0.95))
fig.savefig(output_path, dpi=220, bbox_inches="tight")
plt.close(fig)
def plot_grouped_metric(
model_results: list[dict[str, Any]],
*,
metric_kind: str,
output_path: Path,
ylabel: str,
) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
models = [row["model_label"] for row in model_results]
tasks = [
task
for task, metrics in TASK_METRICS.items()
if any(metrics["source_task"] in row["tasks"] for row in model_results)
]
x = list(range(len(tasks)))
width = min(0.8 / max(len(models), 1), 0.22)
fig, ax = plt.subplots(figsize=(max(6.5, 1.2 * len(tasks) + 0.8 * len(models)), 3.8))
for model_idx, row in enumerate(model_results):
offsets = [pos + (model_idx - (len(models) - 1) / 2) * width for pos in x]
values = []
errors = []
for task in tasks:
task_metrics = TASK_METRICS[task]
summary = row["tasks"].get(task_metrics["source_task"], {})
metric = TASK_METRICS[task][metric_kind]
values.append(_value(summary, metric))
errors.append(_sem(summary, metric))
ax.bar(offsets, values, width=width, label=row["model_label"], yerr=errors, capsize=2)
ax.set_title(f"{metric_kind.replace('_', ' ').title()} Across Tasks")
ax.set_ylabel(ylabel)
ax.set_ylim(0, 105)
ax.set_xticks(x)
ax.set_xticklabels([TASK_METRICS[task]["label"] for task in tasks])
ax.legend(fontsize=7)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
fig.tight_layout()
fig.savefig(output_path, dpi=220, bbox_inches="tight")
plt.close(fig)
def plot_composite(model_results: list[dict[str, Any]], output_path: Path) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
labels = [row["model_label"] for row in model_results]
values = []
for row in model_results:
task_values = []
for _, metrics in TASK_METRICS.items():
source_task = metrics["source_task"]
if source_task in row["tasks"]:
value = row["tasks"][source_task].get(metrics["balanced_accuracy"])
if isinstance(value, (int, float)):
task_values.append(float(value))
values.append((sum(task_values) / len(task_values) * 100.0) if task_values else 0.0)
fig, ax = plt.subplots(figsize=(max(5.5, 0.8 * len(labels)), 3.4))
bars = ax.bar(range(len(labels)), values, color="#4F9B7B", edgecolor="#2F2F2F", linewidth=0.5)
for bar, value in zip(bars, values, strict=True):
ax.text(bar.get_x() + bar.get_width() / 2, value + 1, f"{value:.0f}", ha="center", va="bottom", fontsize=8)
ax.set_title("Composite Balanced Accuracy")
ax.set_ylabel("Score (%)")
ax.set_ylim(0, 105)
ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels, rotation=25, ha="right")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
fig.tight_layout()
fig.savefig(output_path, dpi=220, bbox_inches="tight")
plt.close(fig)
def plot_confusion(confusion: dict[str, int], output_path: Path, title: str) -> None:
if not confusion:
return
labels = sorted({part for key in confusion for part in key.split("->", 1)})
matrix = [[confusion.get(f"{target}->{pred}", 0) for pred in labels] for target in labels]
output_path.parent.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(max(4.2, 0.55 * len(labels)), max(3.8, 0.45 * len(labels))))
image = ax.imshow(matrix, cmap="Blues")
ax.set_title(title)
ax.set_xlabel("Predicted")
ax.set_ylabel("Target")
ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels, rotation=45, ha="right", fontsize=7)
ax.set_yticks(range(len(labels)))
ax.set_yticklabels(labels, fontsize=7)
for row_idx, row in enumerate(matrix):
for col_idx, value in enumerate(row):
ax.text(col_idx, row_idx, str(value), ha="center", va="center", fontsize=7)
fig.colorbar(image, ax=ax, fraction=0.046, pad=0.04)
fig.tight_layout()
fig.savefig(output_path, dpi=220, bbox_inches="tight")
plt.close(fig)
def write_standard_plots(model_results: list[dict[str, Any]], output_dir: Path) -> list[Path]:
plots_dir = output_dir / "plots"
paths: list[Path] = []
plot_composite(model_results, plots_dir / "composite_balanced_accuracy.png")
paths.append(plots_dir / "composite_balanced_accuracy.png")
plot_lsv_balanced_accuracy(model_results, plots_dir / "lsv_benchmark_v1_balanced_accuracy.png")
paths.append(plots_dir / "lsv_benchmark_v1_balanced_accuracy.png")
for metric_kind, ylabel in (
("balanced_accuracy", "Balanced Accuracy (%)"),
("f1", "F1 (%)"),
("precision", "Macro Precision (%)"),
("recall", "Macro Recall (%)"),
("parse_success", "Parse Success (%)"),
):
path = plots_dir / f"{metric_kind}.png"
plot_grouped_metric(model_results, metric_kind=metric_kind, output_path=path, ylabel=ylabel)
paths.append(path)
for row in model_results:
safe_model = row["model_label"].replace("/", "_")
for task, summary in row["tasks"].items():
confusion = (
summary.get("step_confusion")
or summary.get("advance_step_confusion")
or summary.get("binary_confusion")
or {}
)
path = plots_dir / f"{safe_model}_{task}_confusion.png"
plot_confusion(confusion, path, f"{row['model_label']} - {TASK_LABELS.get(task, task)} Confusion")
if path.exists():
paths.append(path)
return paths