repro-sigma-bundle / scripts /make_figures.py
kpshinnik's picture
SigMa reproduction bundle (mechanism verification)
ceac1e4 verified
Raw
History Blame Contribute Delete
5.82 kB
#!/usr/bin/env python3
"""Render figures for the SigMa reproduction (PNG bundle + interactive Plotly HTML)."""
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
d = np.load("outputs/arrays.npz")
tg = d["tgrid"]; tf = d["ts_fine"]
heat = d["heat"]; base = d["base_freqs"]
cs = d["centroids_sigma"]; cy = d["centroids_yarn"]; ms = d["mscales"]
# ---------- Figure 1: alpha(t) scale-adaptive schedule ----------
fig, ax = plt.subplots(figsize=(6.4, 4.2))
for px, s, col in [(2048, 2.0, "#2563eb"), (4096, 4.0, "#dc2626")]:
a = d[f"alpha_{px}"]
ax.plot(tg, a, color=col, lw=2.4, label=f"{px}px s={s:.0f} (16 MP)" if px==4096 else f"{px}px s={s:.0f} (4 MP)")
ax.axvline(1.0/s, color=col, ls=":", lw=1.2, alpha=.8)
ax.scatter([1.0/s], [0.5], color=col, zorder=5, s=36)
ax.axhline(0.5, color="#888", ls="--", lw=.8)
ax.set_xlabel("denoising timestep t (1 = noise → 0 = image)")
ax.set_ylabel(r"modulation $\alpha(t)$")
ax.set_title(r"SigMa sigmoid schedule: $\alpha(t)=\sigma(\sqrt{s}\,(\mathrm{logit}\,t-\mathrm{logit}\,\frac{1}{s}))$"
"\ncenter $t_c=1/s$ (dotted), sharpness $\\gamma=\\sqrt{s}$ — scale-adaptive")
ax.text(0.72, 0.9, "early: α→1\n(YaRN, structure)", fontsize=8, color="#444")
ax.text(0.02, 0.08, "late: α→0\n(base RoPE, texture)", fontsize=8, color="#444")
ax.legend(loc="center right", fontsize=9); ax.grid(alpha=.25)
fig.tight_layout(); fig.savefig("outputs/fig_alpha_schedule.png", dpi=130); plt.close(fig)
# ---------- Figure 2: 16 MP stability (max|embed| vs MP) ----------
import csv
rows = list(csv.DictReader(open("outputs/stability_16mp.csv")))
mps = [float(r["megapixels"]) for r in rows]
mab = [float(r["max_abs_embed"]) for r in rows]
fig, ax = plt.subplots(figsize=(6.4, 4.2))
ax.plot(mps, mab, "o-", color="#059669", lw=2.2)
ax.axvline(16.78, color="#dc2626", ls="--", lw=1.4)
ax.text(16.78, min(mab)+0.02, " 16 MP\n (4096²)", color="#dc2626", fontsize=9, va="bottom", ha="right")
for r in rows:
ax.annotate(f'{r["px"]}²', (float(r["megapixels"]), float(r["max_abs_embed"])),
textcoords="offset points", xytext=(4,-9), fontsize=7, color="#333")
ax.set_xlabel("output resolution (megapixels)")
ax.set_ylabel("max |rotary embedding| (finite & bounded)")
ax.set_title("Claim 1: training-free RoPE stays finite & bounded up to 16 MP\n"
"FluxPosEmbed has 0 learnable parameters (no retraining)")
ax.grid(alpha=.25); fig.tight_layout()
fig.savefig("outputs/fig_stability.png", dpi=130); plt.close(fig)
# ---------- Figure 3: spectral bandwidth structure->texture ----------
fig, ax = plt.subplots(figsize=(6.4, 4.2))
ax.plot(tf, cs, "o-", color="#dc2626", lw=2.2, label="SigMa (adaptive)")
ax.plot(tf, cy, "s--", color="#2563eb", lw=1.8, label="plain YaRN (static)")
ax.set_xlabel("denoising timestep t (1 = noise → 0 = image)")
ax.set_ylabel("effective RoPE bandwidth (norm. to base)")
ax.invert_xaxis()
ax.set_title("Claim 2 @ 16 MP (s=4): SigMa sweeps low→high frequency\n"
"(structure early → texture late); plain YaRN is frozen")
ax.annotate("texture\n(high freq)", (tf[-1], cs[-1]), textcoords="offset points",
xytext=(10,-4), fontsize=8, color="#dc2626")
ax.annotate("structure\n(low freq)", (tf[0], cs[0]), textcoords="offset points",
xytext=(-6,14), fontsize=8, color="#dc2626")
ax.legend(fontsize=9); ax.grid(alpha=.25); fig.tight_layout()
fig.savefig("outputs/fig_spectrum.png", dpi=130); plt.close(fig)
# ---------- Figure 4: per-channel spectrum heatmap ----------
fig, ax = plt.subplots(figsize=(6.4, 4.2))
im = ax.imshow(heat.T, aspect="auto", origin="lower", cmap="magma",
extent=[tf[0], tf[-1], 0, heat.shape[1]])
ax.set_xlabel("denoising timestep t"); ax.set_ylabel("RoPE channel index (low→high freq)")
ax.set_title("Claim 2 @ 16 MP: effective per-channel angular frequency\nacross denoising (SigMa)")
fig.colorbar(im, ax=ax, label="angular freq (rad/patch)")
fig.tight_layout(); fig.savefig("outputs/fig_heatmap.png", dpi=130); plt.close(fig)
print("wrote outputs/fig_{alpha_schedule,stability,spectrum,heatmap}.png")
# ---------- Interactive Plotly HTML for the logbook figure cell ----------
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=2, subplot_titles=(
"α(t) sigmoid schedule (scale-adaptive)",
"Claim 1: RoPE bounded & finite up to 16 MP",
"Claim 2: effective bandwidth, structure→texture",
"SigMa vs plain-YaRN pos-embed cost"))
for px, s, col in [(2048, 2.0, "#2563eb"), (4096, 4.0, "#dc2626")]:
fig.add_trace(go.Scatter(x=tg, y=d[f"alpha_{px}"], name=f"s={s:.0f}",
line=dict(color=col, width=3)), 1, 1)
fig.add_trace(go.Scatter(x=mps, y=mab, mode="lines+markers", name="max|embed|",
line=dict(color="#059669", width=3)), 1, 2)
fig.add_trace(go.Scatter(x=tf, y=cs, name="SigMa", line=dict(color="#dc2626", width=3)), 2, 1)
fig.add_trace(go.Scatter(x=tf, y=cy, name="plain YaRN", line=dict(color="#2563eb", dash="dash")), 2, 1)
fig.add_trace(go.Bar(x=["SigMa", "plain YaRN"], y=[36.08, 41.31],
marker_color=["#dc2626", "#2563eb"], name="ms/step"), 2, 2)
fig.update_xaxes(title_text="t", row=1, col=1); fig.update_yaxes(title_text="α", row=1, col=1)
fig.update_xaxes(title_text="megapixels", row=1, col=2)
fig.update_xaxes(title_text="t", row=2, col=1, autorange="reversed")
fig.update_yaxes(title_text="ms/step", row=2, col=2)
fig.update_layout(height=720, width=1000, showlegend=True,
title_text="SigMa reproduction — real released FluxPosEmbed at FLUX grids (16 MP)")
fig.write_html("outputs/sigma_figure.html", include_plotlyjs="cdn", full_html=True)
print("wrote outputs/sigma_figure.html")