g-vendi-base-proxy / make_heatmap.py
ratishsp's picture
G-Vendi base-model proxy analysis (data, scripts, figure)
990ca06 verified
Raw
History Blame Contribute Delete
13 kB
"""Render the correlation heatmap (FinePhrase Figure 22 style).
Columns are the 20 downstream metrics grouped into 7 families. Rows are four
predictor blocks: DCLM, Edu, and embedding-based diversity (the playbook's own
predictors, for reference), then the G-Vendi block (Published, Reproduced, Base
model, and Base model scored within-prompt). Every row but the last is the
raw-pooled Spearman; the last is the within-prompt z-scored version. Cell colour
is the correlation, the star is significance. All rows are computed on the same
83-cell grid (joined by run), so they are directly comparable.
Inputs (relative to the artifact root):
data/pub.json, data/{repro,prx06bb}/*.json
data/reference_predictors.json (per-run DCLM / Edu / diversity values)
data/downstream_scores.json (per-run downstream scores, Figure 22 source)
Writes correlation_heatmap.png. Needs matplotlib + numpy + scipy.
Run: python make_heatmap.py
"""
import glob, json, math
from collections import defaultdict
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch
from scipy.stats import spearmanr
# ---------------------------------------------------------------- column layout
COLUMN_GROUPS = [
("OVERALL", [("macro", "Macro Avg", True), ("micro", "Micro Avg", True)]),
("KNOWLEDGE", [
("GK", "GK Agg", True), ("arc", "ARC Easy", False), ("mmlu", "MMLU Redux", False)]),
("READING", [
("RC", "RC Agg", True), ("squad", "SQuAD v2", False), ("drop", "DROP", False)]),
("REASONING", [
("RES", "RES Agg", True), ("obqa", "OpenBookQA", False), ("xcsqa", "XCSQA", False)]),
("NLU", [
("NLU", "NLU Agg", True), ("wino", "WinoGrande", False),
("piqa", "PIQA", False), ("hella", "HellaSwag", False)]),
("MATH", [("MATH", "Math Agg", True), ("gsm8k", "GSM8K", False)]),
("TABLE", [
("TABLE", "Table Agg", True), ("wikitab", "WikiTableQ", False), ("treb", "TriviaQA", False)]),
]
SHORT_TO_COL = {
"macro": "agg_score_macro", "micro": "agg_score_micro", "RC": "agg_score_RC",
"GK": "agg_score_GK", "NLU": "agg_score_NLU", "MATH": "agg_score_MATH",
"TABLE": "agg_score_TABLE", "RES": "agg_score_RES",
"arc": "lighteval|arc_cf:easy|3/prob_norm_token",
"drop": "lighteval|drop|3/prob_norm_token",
"gsm8k": "lighteval|gsm8k|3/prob_norm_token",
"hella": "lighteval|hellaswag_cf|3/prob_norm_token",
"obqa": "lighteval|openbookqa_cf|3/prob_norm_token",
"piqa": "lighteval|piqa_cf|3/prob_norm_token",
"squad": "lighteval|squad_v2|3/prob_norm_token",
"treb": "lighteval|treb_qa|3/prob_norm_token",
"wikitab": "lighteval|wikitablequestions|3/prob_norm_token",
"wino": "lighteval|winogrande_cf|3/prob_norm_token",
"xcsqa": "lighteval|xcsqa_cf|3/prob_norm_token",
"mmlu": "lighteval|mmlu_redux_cf:_average|3/prob_norm_token",
}
EXCLUDED_FOOTNOTE1 = {
"format/article:1b-hq", "format/commentary:1b-hq", "format/discussion:1b-hq",
"format/tutorial:1b-hq", "format/tutorial:12b-hq", "format/faq:1b-lq", "format/faq:12b-lq",
}
# ---------------------------------------------------------------- load the grid
# Downstream scores from the playbook's Figure 22 source (rephrasing_metadata.json),
# keyed by run = "bucket/prompt-suffix". Stored under CSV-style column names, so we
# translate to our short names via SHORT_TO_COL.
_downstream = json.load(open("data/downstream_scores.json"))
def lookup_scores(bucket, prompt, suffix):
run = f"{bucket}/{prompt}-{suffix}"
if run in _downstream:
return {short: _downstream[run][col] for short, col in SHORT_TO_COL.items()}
return None
def load_by_cell(globpat):
out = {}
for fp in glob.glob(globpat):
d = json.load(open(fp))
out[d["cell"]] = float(d["g_vendi"])
return out
pub_gv = json.load(open("data/pub.json"))
ref = json.load(open("data/reference_predictors.json"))
gv = {
"repro": load_by_cell("data/repro/*.json"),
"prx06bb": load_by_cell("data/prx06bb/*.json"),
}
rows = [] # (bucket, prompt, {row_id: value}, {short: score})
for cell_full in sorted(gv["repro"]):
if cell_full in EXCLUDED_FOOTNOTE1:
continue
bucket_prompt, suffix = cell_full.rsplit(":", 1)
bucket, prompt = bucket_prompt.split("/", 1)
pub_key = f"{bucket}/{prompt}-{suffix}"
if pub_key not in pub_gv or pub_key not in ref:
continue
scores = lookup_scores(bucket, prompt, suffix)
if scores is None:
continue
vals = {"pub": float(pub_gv[pub_key]["g_vendi_score"])}
vals.update({p: gv[p][cell_full] for p in gv})
vals.update({k: (float(v) if v is not None else float("nan")) for k, v in ref[pub_key].items()})
rows.append((bucket, prompt, vals, scores))
print(f"matched cells: {len(rows)}")
# ---------------------------------------------------------------- correlations
def raw_corr(row_id, short):
g = np.array([r[2][row_id] for r in rows], float)
m = np.array([r[3][short] for r in rows], float)
ok = ~(np.isnan(g) | np.isnan(m))
res = spearmanr(g[ok], m[ok])
return float(res.statistic), float(res.pvalue)
def zwithin_corr(row_id, short):
byp = defaultdict(list)
for r in rows:
a, b = r[2][row_id], r[3][short]
if not (math.isnan(a) or math.isnan(b)):
byp[f"{r[0]}/{r[1]}"].append((a, b))
zg, zm = [], []
for v in byp.values():
n = len(v)
if n < 3:
continue
gs = [x[0] for x in v]; ms = [x[1] for x in v]
mg, mm = sum(gs) / n, sum(ms) / n
sg = math.sqrt(sum((x - mg) ** 2 for x in gs) / n)
sm = math.sqrt(sum((x - mm) ** 2 for x in ms) / n)
for a, b in v:
zg.append((a - mg) / sg if sg else 0.0)
zm.append((b - mm) / sm if sm else 0.0)
res = spearmanr(zg, zm)
return float(res.statistic), float(res.pvalue)
def stars(p):
if p < 0.001: return "***"
if p < 0.01: return "**"
if p < 0.05: return "*"
return ""
# ---------------------------------------------------------------- draw (mirrors the playbook's D3 embed)
flat_cols = [(s, lbl, agg) for _, members in COLUMN_GROUPS for (s, lbl, agg) in members]
N_COL = len(flat_cols)
CELL_W, CELL_H = 1.0, 0.82
ROUND = 0.085
GROUP_GAP = 0.34 # gap between row-groups
def col_x(i):
return i * CELL_W
col_group_spans, _c = [], 0
for _t, _members in COLUMN_GROUPS:
col_group_spans.append((_t, _c, len(_members)))
_c += len(_members)
total_w = N_COL * CELL_W
# colours: d3.scaleDiverging([-0.85,0,0.85], interpolateRdBu) on cellColor(-r),
# then alpha-faded toward the white page near rho=0.
RdBu = plt.get_cmap("RdBu")
def cell_rgb(r):
cval = float(np.clip((0.85 - r) / 1.7, 0.0, 1.0))
rgb = np.array(RdBu(cval)[:3])
alpha = float(np.clip(abs(r) / 0.85 * 1.8, 0.12, 1.0))
return tuple(rgb * alpha + (1.0 - alpha))
DARK, MUTED, DIV = "#4d4d4d", "#a6a6a6", "#8c8c8c"
# Rows for the figure: reference predictors (raw) for context, then the proxy
# comparison: Published / Reproduced / Base model on raw, and Base model again
# on the within-prompt metric. corr is "raw" or "zw" per row.
CORR = {"raw": raw_corr, "zw": zwithin_corr}
FIG_ROWS = [
("DCLM", [("output_dclm_score", "Output DCLM", "raw"), ("input_dclm_score", "Input DCLM", "raw"),
("dclm_score_difference", "DCLM Δ", "raw"), ("dclm_score_improvement", "DCLM Improv %", "raw")]),
("Edu", [("output_edu_score", "Output Edu", "raw"), ("input_edu_score", "Input Edu", "raw"),
("edu_score_difference", "Edu Δ", "raw"), ("edu_score_improvement", "Edu Improv %", "raw")]),
("Diversity", [("vendi_score", "Vendi Score", "raw"), ("mean_intra_cos_sim", "Mean cos sim", "raw"),
("near_dup_rate", "Near-dup rate", "raw")]),
("G-Vendi", [("pub", "Published", "raw"), ("repro", "Reproduced", "raw"),
("prx06bb", "Base model", "raw"), ("prx06bb", "Base (within-prompt)", "zw")]),
]
def render(row_groups, outfile, title):
"""One heatmap: predictor rows (each with its own metric) vs the 20 benchmarks."""
placed, spans, y = [], [], 0.0
for gi, (gname, members) in enumerate(row_groups):
gstart = y
for row_id, label, metric in members:
placed.append((row_id, label, metric, y))
y += CELL_H
spans.append((gname, gstart, y))
if gi < len(row_groups) - 1:
y += GROUP_GAP
total_h = y
width_span = total_w + 2.9
height_span = total_h + 6.8
SCALE = 0.42
fig, ax = plt.subplots(figsize=(width_span * SCALE, height_span * SCALE))
for row_id, plabel, metric, yc in placed:
for ci, (short, label, agg) in enumerate(flat_cols):
rho, p = CORR[metric](row_id, short)
xc = col_x(ci)
ax.add_patch(FancyBboxPatch(
(xc + 0.06, yc + 0.06), CELL_W - 0.12, CELL_H - 0.12,
boxstyle=f"round,pad=0,rounding_size={ROUND}",
facecolor=cell_rgb(rho), edgecolor="white", linewidth=0.8))
tcol = "white" if abs(rho) > 0.45 else DARK
ax.text(xc + CELL_W / 2, yc + CELL_H / 2, f"{rho:.2f}", ha="center",
va="center", fontsize=8.3, color=tcol,
fontweight="bold" if abs(rho) > 0.4 else "normal")
st = stars(p)
if st:
ax.text(xc + CELL_W - 0.1, yc + 0.16, st, ha="right", va="center",
fontsize=6.5, fontweight="bold",
color=("white" if abs(rho) > 0.45 else MUTED))
# vertical dividers between column groups
for gi, (t, start, n) in enumerate(col_group_spans):
if gi > 0:
x = col_x(start)
ax.plot([x, x], [-0.04, total_h + 0.02], color=DIV,
linewidth=1.5 if gi == 1 else 0.9,
linestyle="-" if gi == 1 else (0, (4, 3)), zorder=0)
# horizontal dividers between row-groups
for gi, (gname, gs, ge) in enumerate(spans):
if gi > 0:
yd = gs - GROUP_GAP / 2
ax.plot([-0.02, total_w + 0.02], [yd, yd], color="#9a9a9a",
linewidth=1.4, zorder=0)
# column family headers + bracket lines
for t, start, n in col_group_spans:
xmid = col_x(start) + n * CELL_W / 2
ax.text(xmid, -3.30, t, ha="center", va="bottom", fontsize=8.5,
fontweight="bold", color="#555555")
ax.plot([col_x(start) + 0.08, col_x(start) + n * CELL_W - 0.08],
[-3.12, -3.12], color=MUTED, linewidth=0.9)
# column labels (rotated, aggregates bold)
for ci, (short, label, agg) in enumerate(flat_cols):
ax.text(col_x(ci) + CELL_W / 2, -0.12, label, ha="left", va="bottom",
rotation=52, rotation_mode="anchor", fontsize=8, color=DARK,
fontweight="bold" if agg else "normal")
# subtle separator above any within-prompt row (it uses a different metric)
for row_id, plabel, metric, yc in placed:
if metric == "zw":
ax.plot([-0.02, total_w + 0.02], [yc - 0.02, yc - 0.02],
color="#b0b0b0", linewidth=0.9, linestyle=(0, (3, 2)), zorder=0)
# row labels + per-group rotated labels
for row_id, plabel, metric, yc in placed:
ax.text(-0.18, yc + CELL_H / 2, plabel, ha="right", va="center",
fontsize=8.5, fontstyle=("italic" if metric == "zw" else "normal"),
color=("#1a6fb0" if metric == "zw" else "#333333"))
for gname, gs, ge in spans:
ax.text(-3.05, (gs + ge) / 2, gname, ha="center", va="center", rotation=90,
fontsize=8.5, fontweight="bold", color="#777777")
ax.plot([-2.7, -2.7], [gs + 0.04, ge - 0.04], color=MUTED, linewidth=1.0)
# legend
leg_y = total_h + 1.1
ax.text(0, leg_y - 0.6, "Legend", ha="left", va="center", fontsize=9.5,
fontweight="bold", color="#333333")
for i, r in enumerate([-0.6, -0.3, 0.0, 0.3, 0.6]):
lx = i * 2.3
ax.add_patch(FancyBboxPatch((lx, leg_y), 0.62, 0.42,
boxstyle="round,pad=0,rounding_size=0.05",
facecolor=cell_rgb(r), edgecolor="#dddddd", linewidth=0.7))
ax.text(lx + 0.78, leg_y + 0.21, f"ρ = {r:+.1f}".replace("+0.0", "0"),
ha="left", va="center", fontsize=8, color="#444444")
ax.text(0, leg_y + 1.0, "*** p<0.001 ** p<0.01 * p<0.05",
ha="left", va="center", fontsize=8, color="#888888")
ax.set_xlim(-3.5, total_w + 0.15)
ax.set_ylim(leg_y + 1.4, -4.3)
ax.axis("off")
ax.set_aspect("equal")
ax.set_title(title, fontsize=12, fontweight="bold", pad=18, loc="left", x=0.0)
fig.savefig(outfile, dpi=170, bbox_inches="tight", facecolor="white")
plt.close(fig)
print(f"wrote {outfile}")
render(FIG_ROWS, "correlation_heatmap.png",
"Correlation with downstream benchmarks (raw-pooled; last row is within-prompt)")