File size: 11,602 Bytes
f91d9a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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