MoS-DFlash-Evidence / recipes /plotting /v1 /plot_mos_5x5_gains.py
ryan-0608's picture
Add extended public-safe evidence bundle v1 (#2)
ba0faed
Raw
History Blame Contribute Delete
30.9 kB
#!/usr/bin/env python3
"""Render separate 5x5 MoS routing matrices with Generalist gains.
The frozen R1 evidence contains two selected-checkpoint matrices:
1. MoS initialized from the public DFlash drafter (D0-init).
2. MoS warm-started from the trained Generalist (G-init).
The first two figures show all selected-MLP x evaluation-domain AL cells. The
right panel reports the matched-domain diagonal's absolute and relative
improvement over one fixed-seed evaluation of the selected Generalist
checkpoint. A third figure shows that Generalist baseline across the five
evaluation domains.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, Normalize
from matplotlib.patches import Rectangle
REPO_ROOT = Path(__file__).resolve().parents[3]
DEFAULT_EVIDENCE = (
REPO_ROOT
/ "paper"
/ "submission"
/ "evidence"
/ "r1_mainfig_seed20260719_20260721T0602Z_cells_summary.json"
)
DEFAULT_OUTPUT_DIR = REPO_ROOT / "paper" / "submission" / "figures"
DOMAINS = ["code", "math", "factual_qa", "creative_writing", "general"]
DOMAIN_LABELS = ["Code", "Math", "Factual QA", "Creative", "General"]
INK = "#25313B"
MUTED = "#68747E"
RULE = "#D9DFE3"
ROW_FILL = "#F3F5F6"
D0 = "#2F9E44"
WARM = "#9C36B5"
GENERALIST = "#7F8790"
HEATMAP_NORM = Normalize(vmin=-1.30, vmax=0.0)
D0_CMAP = LinearSegmentedColormap.from_list(
"d0_regret", ["#F7FAF7", "#DDEFE1", "#A7D7B1", "#68B97A", D0]
)
WARM_CMAP = LinearSegmentedColormap.from_list(
"ginit_regret", ["#FBF8FC", "#F0E0F4", "#D9B7E2", "#BC79CB", WARM]
)
ABSOLUTE_CMAP = LinearSegmentedColormap.from_list(
"absolute_al", ["#F2F7FB", "#C9DEEE", "#80B7D5", "#3182BD", "#12538A"]
)
ABSOLUTE_NORM = Normalize(vmin=2.25, vmax=5.60)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--evidence", type=Path, default=DEFAULT_EVIDENCE)
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
return parser.parse_args()
def configure_style() -> None:
mpl.rcParams.update(
{
"font.family": "sans-serif",
"font.sans-serif": [
"Arial",
"Helvetica",
"Liberation Sans",
"DejaVu Sans",
],
"font.size": 8.0,
"axes.titlesize": 10.0,
"axes.labelsize": 8.2,
"xtick.labelsize": 7.4,
"ytick.labelsize": 7.4,
"pdf.fonttype": 42,
"ps.fonttype": 42,
"savefig.bbox": "tight",
"savefig.pad_inches": 0.035,
}
)
def load_evidence(path: Path) -> tuple[dict, np.ndarray]:
evidence = json.loads(path.read_text())
if not evidence.get("passed"):
raise ValueError("R1 evidence is not marked passed")
if evidence.get("cells_total") != 52 or evidence.get("cells_passed") != 52:
raise ValueError("R1 evidence is incomplete; expected 52/52 passed cells")
generalist = np.asarray(
[float(evidence["panel_d_generalist"][domain]) for domain in DOMAINS],
dtype=float,
)
return evidence, generalist
def matrix_from_evidence(evidence: dict, key: str) -> np.ndarray:
mapping = evidence[key]
matrix = np.asarray(
[[float(mapping[row][column]) for column in DOMAINS] for row in DOMAINS],
dtype=float,
)
for column, domain in enumerate(DOMAINS):
if int(np.argmax(matrix[:, column])) != column:
raise ValueError(f"{key}: matched MLP is not best for {domain}")
return matrix
def draw_matrix(
ax: plt.Axes,
matrix: np.ndarray,
cmap: LinearSegmentedColormap,
accent: str,
) -> mpl.image.AxesImage:
regret = matrix - np.diag(matrix)[None, :]
image = ax.imshow(regret, cmap=cmap, norm=HEATMAP_NORM, aspect="equal")
ax.set_xticks(range(5), labels=DOMAIN_LABELS)
ax.set_yticks(range(5), labels=DOMAIN_LABELS)
ax.tick_params(axis="x", rotation=28, length=0, pad=3.0)
ax.tick_params(axis="y", length=0, pad=3.0)
ax.xaxis.set_label_position("top")
ax.set_xlabel("Evaluation domain", labelpad=8.5, fontweight="bold")
ax.set_ylabel("Selected MLP", labelpad=6.0, fontweight="bold")
for row in range(5):
for column in range(5):
value = matrix[row, column]
normalized = HEATMAP_NORM(regret[row, column])
text_color = "white" if normalized > 0.66 else INK
ax.text(
column,
row,
f"{value:.3f}",
ha="center",
va="center",
fontsize=7.7,
color=text_color,
fontweight="bold" if row == column else "normal",
)
if row == column:
ax.add_patch(
Rectangle(
(column - 0.48, row - 0.48),
0.96,
0.96,
facecolor="none",
edgecolor=accent,
linewidth=1.7,
)
)
ax.set_xticks(np.arange(-0.5, 5, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 5, 1), minor=True)
ax.grid(which="minor", color="white", linewidth=1.25)
ax.tick_params(which="minor", bottom=False, left=False)
for spine in ax.spines.values():
spine.set_visible(False)
return image
def draw_gain_table(
ax: plt.Axes,
matrix: np.ndarray,
generalist: np.ndarray,
accent: str,
) -> None:
diagonal = np.diag(matrix)
delta = diagonal - generalist
percent = 100.0 * delta / generalist
if not np.all(delta > 0):
raise ValueError("matched-domain MoS does not improve every domain")
mean_generalist = float(np.mean(generalist))
mean_diagonal = float(np.mean(diagonal))
mean_delta = mean_diagonal - mean_generalist
mean_percent = 100.0 * mean_delta / mean_generalist
labels = DOMAIN_LABELS + ["Mean"]
deltas = np.concatenate([delta, [mean_delta]])
percents = np.concatenate([percent, [mean_percent]])
ax.set_xlim(0.0, 1.0)
ax.set_ylim(0.0, 1.0)
ax.axis("off")
ax.text(
0.02,
0.965,
"Matched MLP gain vs Generalist",
ha="left",
va="top",
fontsize=9.1,
fontweight="bold",
color=INK,
)
ax.text(0.02, 0.855, "Domain", ha="left", va="center", color=MUTED, fontweight="bold")
ax.text(0.68, 0.855, "Δ AL", ha="right", va="center", color=MUTED, fontweight="bold")
ax.text(0.98, 0.855, "Δ %", ha="right", va="center", color=MUTED, fontweight="bold")
ax.plot([0.02, 0.98], [0.815, 0.815], color=RULE, lw=0.9)
ys = np.linspace(0.735, 0.175, len(labels))
for index, (label, value, pct, y) in enumerate(zip(labels, deltas, percents, ys)):
if index == len(labels) - 1:
ax.add_patch(
Rectangle(
(0.01, y - 0.050),
0.98,
0.100,
facecolor=ROW_FILL,
edgecolor="none",
zorder=0,
)
)
weight = "bold" if index == len(labels) - 1 else "normal"
ax.text(0.02, y, label, ha="left", va="center", color=INK, fontweight=weight)
ax.text(
0.68,
y,
f"+{value:.3f}",
ha="right",
va="center",
color=accent,
fontweight="bold",
)
ax.text(
0.98,
y,
f"+{pct:.1f}%",
ha="right",
va="center",
color=accent,
fontweight="bold",
)
ax.text(
0.02,
0.045,
"Mean is unweighted across the five domains.",
ha="left",
va="bottom",
fontsize=6.7,
color=MUTED,
)
def render_one(
matrix: np.ndarray,
generalist: np.ndarray,
title: str,
subtitle: str,
cmap: LinearSegmentedColormap,
accent: str,
output: Path,
) -> None:
fig = plt.figure(figsize=(7.15, 3.55), facecolor="white")
grid = fig.add_gridspec(
1,
2,
width_ratios=[1.20, 0.92],
wspace=0.22,
left=0.085,
right=0.985,
top=0.755,
bottom=0.21,
)
ax_matrix = fig.add_subplot(grid[0, 0])
ax_gain = fig.add_subplot(grid[0, 1])
image = draw_matrix(ax_matrix, matrix, cmap, accent)
draw_gain_table(ax_gain, matrix, generalist, accent)
fig.text(0.03, 0.970, title, ha="left", va="top", fontsize=11.2, fontweight="bold", color=INK)
fig.text(0.03, 0.862, subtitle, ha="left", va="top", fontsize=7.2, color=MUTED)
cbar_ax = fig.add_axes([0.137, 0.095, 0.355, 0.018])
cbar = fig.colorbar(image, cax=cbar_ax, orientation="horizontal")
cbar.set_ticks([-1.2, -0.6, 0.0], labels=["−1.2", "−0.6", "0"])
cbar.ax.tick_params(labelsize=6.5, length=2.0, color=RULE, pad=1.5)
cbar.outline.set_visible(False)
fig.text(
0.314,
0.040,
"Cell shade: AL difference from the matched MLP in each column",
ha="center",
va="bottom",
fontsize=6.5,
color=MUTED,
)
output.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(output, dpi=420, facecolor="white")
plt.close(fig)
print(f"saved {output}")
def render_generalist(
generalist: np.ndarray,
subtitle: str,
output: Path,
) -> None:
mean_al = float(np.mean(generalist))
x = np.arange(len(DOMAINS))
fig, ax = plt.subplots(figsize=(7.15, 3.35), facecolor="white")
fig.subplots_adjust(left=0.095, right=0.975, top=0.755, bottom=0.205)
bars = ax.bar(
x,
generalist,
width=0.58,
color=GENERALIST,
edgecolor=INK,
linewidth=0.55,
zorder=3,
)
ax.bar_label(
bars,
labels=[f"{value:.3f}" for value in generalist],
padding=-16,
fontsize=8.1,
fontweight="bold",
color="white",
)
ax.axhline(
mean_al,
color=INK,
lw=1.15,
ls=(0, (4, 2)),
label=f"Five-domain mean = {mean_al:.3f}",
zorder=2,
)
ax.set_xlim(-0.55, len(DOMAINS) - 0.45)
ax.set_ylim(0.0, 5.55)
ax.set_xticks(x, labels=DOMAIN_LABELS)
ax.set_yticks(np.arange(0.0, 5.6, 1.0))
ax.set_ylabel("Acceptance length (AL)", fontweight="bold")
ax.grid(axis="y", color=RULE, linewidth=0.65, zorder=0)
ax.legend(loc="upper right", frameon=False, fontsize=7.4, handlelength=2.8)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_color(RULE)
ax.spines["bottom"].set_color(RULE)
ax.tick_params(color=RULE, labelcolor=INK, width=0.65, length=2.8)
fig.text(
0.03,
0.970,
"Generalist (DFlash baseline): AL across five domains",
ha="left",
va="top",
fontsize=11.2,
fontweight="bold",
color=INK,
)
fig.text(0.03, 0.862, subtitle, ha="left", va="top", fontsize=7.2, color=MUTED)
output.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(output, dpi=420, facecolor="white")
plt.close(fig)
print(f"saved {output}")
def draw_compact_generalist(ax: plt.Axes, generalist: np.ndarray) -> None:
x = np.arange(len(DOMAINS))
bars = ax.bar(
x,
generalist,
width=0.66,
color=GENERALIST,
edgecolor=INK,
linewidth=0.45,
zorder=3,
)
ax.bar_label(
bars,
labels=[f"{value:.3f}" for value in generalist],
padding=-10,
fontsize=5.7,
fontweight="bold",
color="white",
)
ax.axhline(float(np.mean(generalist)), color=INK, lw=0.85, ls=(0, (3, 2)), zorder=2)
ax.set_xlim(-0.55, len(DOMAINS) - 0.45)
ax.set_ylim(0.0, 5.55)
ax.set_xticks(x, labels=["Code", "Math", "FQA", "Creat.", "Gen."])
ax.tick_params(axis="x", rotation=40, labelsize=5.5, pad=1.8)
ax.set_yticks([0, 2, 4], labels=["0", "2", "4"])
ax.tick_params(axis="y", labelsize=5.5)
ax.set_ylabel("AL", fontsize=6.5, fontweight="bold", labelpad=2.0)
ax.grid(axis="y", color=RULE, linewidth=0.5, zorder=0)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_color(RULE)
ax.spines["bottom"].set_color(RULE)
ax.tick_params(color=RULE, labelcolor=INK, width=0.5, length=2.0)
ax.text(
0.98,
0.96,
f"mean {np.mean(generalist):.3f}",
transform=ax.transAxes,
ha="right",
va="top",
fontsize=5.8,
color=INK,
fontweight="bold",
)
def draw_compact_matrix(
ax: plt.Axes,
matrix: np.ndarray,
cmap: LinearSegmentedColormap,
accent: str,
) -> None:
regret = matrix - np.diag(matrix)[None, :]
ax.imshow(regret, cmap=cmap, norm=HEATMAP_NORM, aspect="equal")
short_labels = ["Code", "Math", "FQA", "Creat.", "Gen."]
ax.set_xticks(range(5), labels=short_labels)
ax.set_yticks(range(5), labels=short_labels)
ax.tick_params(axis="x", rotation=40, length=0, pad=1.8, labelsize=5.3)
ax.tick_params(axis="y", length=0, pad=2.0, labelsize=5.3)
ax.set_ylabel("Selected MLP", fontsize=6.1, fontweight="bold", labelpad=2.0)
for row in range(5):
for column in range(5):
normalized = HEATMAP_NORM(regret[row, column])
ax.text(
column,
row,
f"{matrix[row, column]:.2f}",
ha="center",
va="center",
fontsize=5.4,
color="white" if normalized > 0.66 else INK,
fontweight="bold" if row == column else "normal",
)
if row == column:
ax.add_patch(
Rectangle(
(column - 0.47, row - 0.47),
0.94,
0.94,
facecolor="none",
edgecolor=accent,
linewidth=1.15,
)
)
ax.set_xticks(np.arange(-0.5, 5, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 5, 1), minor=True)
ax.grid(which="minor", color="white", linewidth=0.9)
ax.tick_params(which="minor", bottom=False, left=False)
for spine in ax.spines.values():
spine.set_visible(False)
def draw_compact_gains(
ax: plt.Axes,
matrix: np.ndarray,
generalist: np.ndarray,
accent: str,
) -> None:
delta = np.diag(matrix) - generalist
percent = 100.0 * delta / generalist
mean_delta = float(np.mean(np.diag(matrix)) - np.mean(generalist))
mean_percent = 100.0 * mean_delta / float(np.mean(generalist))
ax.set_xlim(0.0, 1.0)
ax.set_ylim(4.5, -0.5)
ax.axis("off")
ax.text(0.43, 1.045, "ΔAL", transform=ax.transAxes, ha="right", va="bottom", fontsize=5.5, color=MUTED, fontweight="bold")
ax.text(0.98, 1.045, "Δ%", transform=ax.transAxes, ha="right", va="bottom", fontsize=5.5, color=MUTED, fontweight="bold")
for row, (value, pct) in enumerate(zip(delta, percent)):
ax.text(0.43, row, f"+{value:.2f}", ha="right", va="center", fontsize=5.4, color=accent, fontweight="bold")
ax.text(0.98, row, f"+{pct:.1f}", ha="right", va="center", fontsize=5.4, color=accent, fontweight="bold")
ax.text(
0.98,
-0.16,
f"mean +{mean_delta:.2f} / +{mean_percent:.1f}%",
transform=ax.transAxes,
ha="right",
va="top",
fontsize=5.1,
color=accent,
fontweight="bold",
)
def render_three_panel(
generalist: np.ndarray,
d0_matrix: np.ndarray,
warm_matrix: np.ndarray,
output: Path,
) -> None:
fig = plt.figure(figsize=(7.15, 2.48), facecolor="white")
outer = fig.add_gridspec(
1,
3,
width_ratios=[0.78, 1.36, 1.36],
wspace=0.30,
left=0.055,
right=0.992,
top=0.78,
bottom=0.23,
)
ax_a = fig.add_subplot(outer[0, 0])
grid_b = outer[0, 1].subgridspec(1, 2, width_ratios=[1.0, 0.42], wspace=0.04)
ax_b = fig.add_subplot(grid_b[0, 0])
ax_b_gain = fig.add_subplot(grid_b[0, 1])
grid_c = outer[0, 2].subgridspec(1, 2, width_ratios=[1.0, 0.42], wspace=0.04)
ax_c = fig.add_subplot(grid_c[0, 0])
ax_c_gain = fig.add_subplot(grid_c[0, 1])
draw_compact_generalist(ax_a, generalist)
draw_compact_matrix(ax_b, d0_matrix, D0_CMAP, D0)
draw_compact_gains(ax_b_gain, d0_matrix, generalist, D0)
draw_compact_matrix(ax_c, warm_matrix, WARM_CMAP, WARM)
draw_compact_gains(ax_c_gain, warm_matrix, generalist, WARM)
panel_titles = (
(0.055, "A", "Generalist (DFlash)"),
(0.305, "B", "DFlash-init MoS"),
(0.661, "C", "Generalist-warm-start MoS"),
)
for x, letter, title in panel_titles:
fig.text(x, 0.935, letter, ha="left", va="top", fontsize=8.8, fontweight="bold", color=INK)
fig.text(x + 0.025, 0.935, title, ha="left", va="top", fontsize=8.0, fontweight="bold", color=INK)
fig.text(
0.63,
0.055,
"Rows select MLPs; columns are evaluation domains. Bold diagonal = matched MLP; gains are vs Generalist.",
ha="center",
va="bottom",
fontsize=5.3,
color=MUTED,
)
fig.text(
0.055,
0.055,
"Qwen3-8B target · fixed seed",
ha="left",
va="bottom",
fontsize=5.3,
color=MUTED,
)
output.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(output, dpi=480, facecolor="white")
plt.close(fig)
print(f"saved {output}")
def draw_baseline_aligned_panel(
ax_matrix: plt.Axes,
ax_gain: plt.Axes,
matrix: np.ndarray,
generalist: np.ndarray,
) -> None:
aligned = np.vstack([generalist, matrix])
row_labels = ["Generalist", "Code MLP", "Math MLP", "FQA MLP", "Creat. MLP", "Gen. MLP"]
column_labels = ["Code", "Math", "FQA", "Creat.", "Gen."]
ax_matrix.imshow(aligned, cmap=ABSOLUTE_CMAP, norm=ABSOLUTE_NORM, aspect="equal")
ax_matrix.set_xticks(range(5), labels=column_labels)
ax_matrix.set_yticks(range(6), labels=row_labels)
ax_matrix.tick_params(axis="x", rotation=37, length=0, pad=2.0, labelsize=5.5)
ax_matrix.tick_params(axis="y", length=0, pad=2.4, labelsize=5.4)
for row in range(6):
for column in range(5):
value = aligned[row, column]
normalized = ABSOLUTE_NORM(value)
is_matched = row > 0 and row - 1 == column
ax_matrix.text(
column,
row,
f"{value:.2f}",
ha="center",
va="center",
fontsize=5.7,
color="white" if normalized > 0.58 else INK,
fontweight="bold" if is_matched else "normal",
)
if is_matched:
ax_matrix.add_patch(
Rectangle(
(column - 0.47, row - 0.47),
0.94,
0.94,
facecolor="none",
edgecolor=INK,
linewidth=1.0,
)
)
ax_matrix.axhline(0.5, color=INK, lw=1.15)
ax_matrix.set_xticks(np.arange(-0.5, 5, 1), minor=True)
ax_matrix.set_yticks(np.arange(-0.5, 6, 1), minor=True)
ax_matrix.grid(which="minor", color="white", linewidth=0.9)
ax_matrix.tick_params(which="minor", bottom=False, left=False)
for spine in ax_matrix.spines.values():
spine.set_visible(False)
delta = np.diag(matrix) - generalist
percent = 100.0 * delta / generalist
mean_delta = float(np.mean(np.diag(matrix)) - np.mean(generalist))
mean_percent = 100.0 * mean_delta / float(np.mean(generalist))
ax_gain.set_xlim(0.0, 1.0)
ax_gain.set_ylim(5.5, -0.5)
ax_gain.axis("off")
ax_gain.text(0.43, 1.04, "ΔAL", transform=ax_gain.transAxes, ha="right", va="bottom", fontsize=5.7, color=MUTED, fontweight="bold")
ax_gain.text(0.98, 1.04, "Δ%", transform=ax_gain.transAxes, ha="right", va="bottom", fontsize=5.7, color=MUTED, fontweight="bold")
ax_gain.text(0.43, 0, "—", ha="right", va="center", fontsize=5.4, color=MUTED)
ax_gain.text(0.98, 0, "—", ha="right", va="center", fontsize=5.4, color=MUTED)
for row, (value, pct) in enumerate(zip(delta, percent), start=1):
ax_gain.text(0.43, row, f"+{value:.2f}", ha="right", va="center", fontsize=5.5, color=INK, fontweight="bold")
ax_gain.text(0.98, row, f"+{pct:.1f}", ha="right", va="center", fontsize=5.5, color=INK, fontweight="bold")
ax_gain.axhline(0.5, color=INK, lw=1.15)
ax_gain.text(
0.98,
-0.14,
f"mean +{mean_delta:.2f} / +{mean_percent:.1f}%",
transform=ax_gain.transAxes,
ha="right",
va="top",
fontsize=5.2,
color=INK,
fontweight="bold",
)
def render_baseline_aligned(
generalist: np.ndarray,
d0_matrix: np.ndarray,
warm_matrix: np.ndarray,
output: Path,
) -> None:
fig = plt.figure(figsize=(7.15, 2.85), facecolor="white")
outer = fig.add_gridspec(
1,
2,
wspace=0.28,
left=0.105,
right=0.992,
top=0.72,
bottom=0.23,
)
grid_a = outer[0, 0].subgridspec(1, 2, width_ratios=[1.0, 0.35], wspace=0.04)
ax_a = fig.add_subplot(grid_a[0, 0])
ax_a_gain = fig.add_subplot(grid_a[0, 1])
grid_b = outer[0, 1].subgridspec(1, 2, width_ratios=[1.0, 0.35], wspace=0.04)
ax_b = fig.add_subplot(grid_b[0, 0])
ax_b_gain = fig.add_subplot(grid_b[0, 1])
draw_baseline_aligned_panel(ax_a, ax_a_gain, d0_matrix, generalist)
draw_baseline_aligned_panel(ax_b, ax_b_gain, warm_matrix, generalist)
fig.text(
0.055,
0.970,
"Generalist-aligned acceptance-length matrices · Qwen3-8B target",
ha="left",
va="top",
fontsize=9.2,
fontweight="bold",
color=INK,
)
fig.text(
0.055,
0.895,
f"Shared DFlash Generalist baseline mean = {np.mean(generalist):.3f}; fixed-seed selected-checkpoint evaluation",
ha="left",
va="top",
fontsize=6.0,
color=MUTED,
)
fig.text(0.105, 0.805, "A DFlash-init MoS", ha="left", va="top", fontsize=7.5, fontweight="bold", color=INK)
fig.text(0.563, 0.805, "B Generalist-warm-start MoS", ha="left", va="top", fontsize=7.5, fontweight="bold", color=INK)
fig.text(
0.50,
0.045,
"The shared Generalist row is repeated for direct comparison; it is one baseline, not five specialists. Bold boxes mark matched MLPs.",
ha="center",
va="bottom",
fontsize=5.2,
color=MUTED,
)
output.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(output, dpi=480, facecolor="white")
plt.close(fig)
print(f"saved {output}")
def draw_summary_matrix(
ax: plt.Axes,
matrix: np.ndarray,
cmap: LinearSegmentedColormap,
accent: str,
) -> None:
regret = matrix - np.diag(matrix)[None, :]
ax.imshow(regret, cmap=cmap, norm=HEATMAP_NORM, aspect="equal")
labels = ["Code", "Math", "FQA", "Creat.", "Gen."]
ax.set_xticks(range(5), labels=labels)
ax.set_yticks(range(5), labels=labels)
ax.tick_params(axis="x", rotation=38, length=0, pad=2.0, labelsize=5.4)
ax.tick_params(axis="y", length=0, pad=2.2, labelsize=5.4)
ax.set_ylabel("Selected MLP", fontsize=6.1, fontweight="bold", labelpad=2.2)
for row in range(5):
for column in range(5):
normalized = HEATMAP_NORM(regret[row, column])
is_matched = row == column
ax.text(
column,
row,
f"{matrix[row, column]:.3f}",
ha="center",
va="center",
fontsize=5.2,
color="white" if normalized > 0.66 else INK,
fontweight="bold" if is_matched else "normal",
)
if is_matched:
ax.add_patch(
Rectangle(
(column - 0.47, row - 0.47),
0.94,
0.94,
facecolor="none",
edgecolor=accent,
linewidth=1.15,
)
)
ax.set_xticks(np.arange(-0.5, 5, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 5, 1), minor=True)
ax.grid(which="minor", color="white", linewidth=0.95)
ax.tick_params(which="minor", bottom=False, left=False)
for spine in ax.spines.values():
spine.set_visible(False)
def draw_three_method_table(
ax: plt.Axes,
generalist: np.ndarray,
d0_matrix: np.ndarray,
warm_matrix: np.ndarray,
) -> None:
d0 = np.diag(d0_matrix)
warm = np.diag(warm_matrix)
labels = DOMAIN_LABELS + ["Mean"]
generalist_values = np.concatenate([generalist, [np.mean(generalist)]])
d0_values = np.concatenate([d0, [np.mean(d0)]])
warm_values = np.concatenate([warm, [np.mean(warm)]])
ax.set_xlim(0.0, 1.0)
ax.set_ylim(0.0, 1.0)
ax.axis("off")
header_y = 0.875
ax.text(0.01, header_y, "Domain", ha="left", va="center", fontsize=5.9, color=MUTED, fontweight="bold")
ax.text(0.48, header_y, "Generalist", ha="right", va="center", fontsize=5.7, color=MUTED, fontweight="bold")
ax.text(0.75, header_y, "D0 MoS", ha="right", va="center", fontsize=5.7, color=D0, fontweight="bold")
ax.text(0.99, header_y, "G-init", ha="right", va="center", fontsize=5.7, color=WARM, fontweight="bold")
ax.plot([0.01, 0.99], [0.825, 0.825], color=RULE, lw=0.8)
ys = np.linspace(0.745, 0.245, len(labels))
for index, (label, gen_value, d0_value, warm_value, y) in enumerate(
zip(labels, generalist_values, d0_values, warm_values, ys)
):
is_mean = index == len(labels) - 1
if is_mean:
ax.add_patch(
Rectangle(
(0.0, y - 0.045),
1.0,
0.090,
facecolor=ROW_FILL,
edgecolor="none",
zorder=0,
)
)
weight = "bold" if is_mean else "normal"
ax.text(0.01, y, label, ha="left", va="center", fontsize=5.8, color=INK, fontweight=weight)
ax.text(0.48, y, f"{gen_value:.3f}", ha="right", va="center", fontsize=5.8, color=MUTED, fontweight=weight)
ax.text(0.75, y, f"{d0_value:.3f}", ha="right", va="center", fontsize=5.8, color=D0, fontweight="bold")
ax.text(0.99, y, f"{warm_value:.3f}", ha="right", va="center", fontsize=5.8, color=WARM, fontweight="bold")
d0_delta = float(np.mean(d0) - np.mean(generalist))
warm_delta = float(np.mean(warm) - np.mean(generalist))
d0_percent = 100.0 * d0_delta / float(np.mean(generalist))
warm_percent = 100.0 * warm_delta / float(np.mean(generalist))
ax.text(
0.99,
0.105,
f"D0 mean gain +{d0_delta:.3f} / +{d0_percent:.1f}%",
ha="right",
va="center",
fontsize=5.4,
color=D0,
fontweight="bold",
)
ax.text(
0.99,
0.035,
f"G-init mean gain +{warm_delta:.3f} / +{warm_percent:.1f}%",
ha="right",
va="center",
fontsize=5.4,
color=WARM,
fontweight="bold",
)
def render_matrices_summary(
generalist: np.ndarray,
d0_matrix: np.ndarray,
warm_matrix: np.ndarray,
output: Path,
) -> None:
fig = plt.figure(figsize=(7.15, 2.52), facecolor="white")
grid = fig.add_gridspec(
1,
3,
width_ratios=[1.0, 1.0, 1.18],
wspace=0.28,
left=0.065,
right=0.992,
top=0.77,
bottom=0.22,
)
ax_d0 = fig.add_subplot(grid[0, 0])
ax_warm = fig.add_subplot(grid[0, 1])
ax_table = fig.add_subplot(grid[0, 2])
draw_summary_matrix(ax_d0, d0_matrix, D0_CMAP, D0)
draw_summary_matrix(ax_warm, warm_matrix, WARM_CMAP, WARM)
draw_three_method_table(ax_table, generalist, d0_matrix, warm_matrix)
titles = (
(0.065, "A", "DFlash-init MoS"),
(0.360, "B", "Generalist-warm-start MoS"),
(0.670, "C", "Matched-domain AL"),
)
for x, letter, title in titles:
fig.text(x, 0.940, letter, ha="left", va="top", fontsize=8.7, fontweight="bold", color=INK)
fig.text(x + 0.025, 0.940, title, ha="left", va="top", fontsize=7.5, fontweight="bold", color=INK)
fig.text(
0.50,
0.045,
"Qwen3-8B target · fixed-seed selected checkpoints · matrix columns are evaluation domains; bold diagonal cells select the matched MLP.",
ha="center",
va="bottom",
fontsize=5.2,
color=MUTED,
)
output.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(output, dpi=480, facecolor="white")
plt.close(fig)
print(f"saved {output}")
def main() -> None:
args = parse_args()
configure_style()
evidence, generalist = load_evidence(args.evidence)
d0_matrix = matrix_from_evidence(evidence, "panel_b_matrix_dflash_init")
warm_matrix = matrix_from_evidence(evidence, "panel_c_matrix_warm_start")
subtitle = (
"Qwen3-8B target · selected-checkpoint, fixed-seed evaluation · "
"rows: selected MLP; columns: evaluation domain"
)
render_one(
d0_matrix,
generalist,
"DFlash-initialized MoS: 5×5 routing matrix",
subtitle,
D0_CMAP,
D0,
args.output_dir / "fig_mos_d0_matrix_gains.png",
)
render_one(
warm_matrix,
generalist,
"Generalist-warm-started MoS: 5×5 routing matrix",
subtitle,
WARM_CMAP,
WARM,
args.output_dir / "fig_mos_ginit_matrix_gains.png",
)
render_generalist(
generalist,
"Qwen3-8B target · selected-checkpoint, fixed-seed evaluation · standard single-model DFlash",
args.output_dir / "fig_generalist_domain_al.png",
)
render_three_panel(
generalist,
d0_matrix,
warm_matrix,
args.output_dir / "fig_mos_three_panel.png",
)
render_baseline_aligned(
generalist,
d0_matrix,
warm_matrix,
args.output_dir / "fig_mos_baseline_aligned.png",
)
render_matrices_summary(
generalist,
d0_matrix,
warm_matrix,
args.output_dir / "fig_mos_matrices_summary.png",
)
if __name__ == "__main__":
main()