MoS-DFlash-Evidence / recipes /plotting /v1 /plot_qwen3_4b_matched.py
ryan-0608's picture
Add extended public-safe evidence bundle v1 (#2)
ba0faed
Raw
History Blame Contribute Delete
5.85 kB
#!/usr/bin/env python3
"""Render the Qwen3-4B matched-volume trajectory for the AAAI supplement."""
from __future__ import annotations
import argparse
import csv
from pathlib import Path
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
GENERALIST_COLOR = "#5B5B5B"
MOS_COLOR = "#6F5AA8"
GRID_COLOR = "#D9D9D9"
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument(
"--input",
type=Path,
default=Path(
"paper/submission/evidence/b5_qwen3_4b/"
"matched_volume_trajectory.csv"
),
)
parser.add_argument(
"--output",
type=Path,
default=Path("paper/submission/figures/fig_qwen3_4b_matched"),
help="Output stem; both PDF and PNG are written.",
)
return parser.parse_args()
def load_rows(path: Path) -> dict[str, np.ndarray]:
with path.open(newline="") as handle:
rows = list(csv.DictReader(handle))
if len(rows) != 29:
raise ValueError(f"expected 29 matched points, found {len(rows)}")
keys = (
"training_samples",
"generalist_overall_al",
"arm_a_overall_al",
"delta_overall_al",
)
arrays = {
key: np.asarray([float(row[key]) for row in rows], dtype=np.float64)
for key in keys
}
if not np.all(np.diff(arrays["training_samples"]) > 0):
raise ValueError("training_samples must be strictly increasing")
recomputed = arrays["arm_a_overall_al"] - arrays["generalist_overall_al"]
if not np.allclose(recomputed, arrays["delta_overall_al"], atol=5e-5):
raise ValueError("stored deltas disagree with trajectory values")
if not np.all(arrays["delta_overall_al"] > 0):
raise ValueError("the publication annotation assumes 29/29 positive deltas")
return arrays
def configure_style() -> None:
mpl.rcParams.update(
{
"font.family": "serif",
"font.serif": ["Times New Roman", "Times", "Nimbus Roman", "DejaVu Serif"],
"font.size": 8.0,
"axes.labelsize": 8.0,
"axes.titlesize": 8.0,
"xtick.labelsize": 7.2,
"ytick.labelsize": 7.2,
"legend.fontsize": 7.1,
"axes.linewidth": 0.7,
"lines.linewidth": 1.5,
"lines.markersize": 3.4,
"pdf.fonttype": 42,
"ps.fonttype": 42,
"savefig.bbox": "tight",
"savefig.pad_inches": 0.02,
}
)
def render(data: dict[str, np.ndarray], output: Path) -> None:
configure_style()
samples_m = data["training_samples"] / 1_000_000.0
generalist = data["generalist_overall_al"]
mos = data["arm_a_overall_al"]
delta = data["delta_overall_al"]
median_delta = float(np.median(delta))
fig, (ax_curve, ax_delta) = plt.subplots(
1,
2,
figsize=(7.0, 2.42),
gridspec_kw={"width_ratios": [1.16, 0.84], "wspace": 0.31},
)
ax_curve.plot(
samples_m,
generalist,
color=GENERALIST_COLOR,
linestyle="--",
marker="o",
markerfacecolor="white",
markeredgewidth=0.75,
markevery=2,
label="Generalist",
zorder=2,
)
ax_curve.plot(
samples_m,
mos,
color=MOS_COLOR,
linestyle="-",
marker="s",
markerfacecolor=MOS_COLOR,
markeredgewidth=0.0,
markevery=2,
label="D0-MoS (5 groups)",
zorder=3,
)
ax_curve.set_xlabel("Training samples (millions)")
ax_curve.set_ylabel("Five-domain mean AL")
ax_curve.set_xlim(0.0, 2.4)
ymin = min(float(generalist.min()), float(mos.min())) - 0.025
ymax = max(float(generalist.max()), float(mos.max())) + 0.025
ax_curve.set_ylim(ymin, ymax)
ax_curve.grid(axis="y", color=GRID_COLOR, linewidth=0.55, alpha=0.8)
ax_curve.legend(loc="lower right", frameon=False, handlelength=2.2)
ax_delta.axhline(0.0, color=GENERALIST_COLOR, linewidth=0.75, linestyle=":")
ax_delta.plot(
samples_m,
delta,
color=MOS_COLOR,
linestyle="-",
marker="D",
markerfacecolor="white",
markeredgewidth=0.75,
markevery=2,
zorder=3,
)
ax_delta.axhline(
median_delta,
color=MOS_COLOR,
linewidth=0.9,
linestyle="--",
alpha=0.8,
)
ax_delta.text(
0.98,
0.08,
f"29/29 matched points > 0\nmedian $\\Delta$ = {median_delta:.3f}",
transform=ax_delta.transAxes,
ha="right",
va="bottom",
fontsize=7.0,
)
ax_delta.set_xlabel("Training samples (millions)")
ax_delta.set_ylabel(r"$\Delta$ AL (MoS $-$ generalist)")
ax_delta.set_xlim(0.0, 2.4)
ax_delta.set_ylim(0.0, max(0.12, float(delta.max()) + 0.01))
ax_delta.grid(axis="y", color=GRID_COLOR, linewidth=0.55, alpha=0.8)
for label, axis in (("(a)", ax_curve), ("(b)", ax_delta)):
axis.text(
-0.14,
1.03,
label,
transform=axis.transAxes,
ha="left",
va="bottom",
fontweight="bold",
)
axis.spines["top"].set_visible(False)
axis.spines["right"].set_visible(False)
axis.tick_params(width=0.7, length=3.0)
output.parent.mkdir(parents=True, exist_ok=True)
metadata = {
"Title": "Qwen3-4B matched-volume MoS replication",
"Subject": "Five-domain acceptance length over matched training volume",
}
fig.savefig(output.with_suffix(".pdf"), metadata=metadata)
fig.savefig(output.with_suffix(".png"), dpi=450)
plt.close(fig)
def main() -> None:
args = parse_args()
render(load_rows(args.input), args.output)
if __name__ == "__main__":
main()