KeremTT's picture
Update code
73f7e6f verified
Raw History Blame Contribute Delete
16.2 kB
"""Render the dataset-card charts from out/stats/*.json into out/assets/*.png.
Measured charts use real numbers produced by build.py / train/*.py. Projection charts
are computed from published scaling laws and are labelled as projections.
"""
import json
import math
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import matplotlib.ticker # noqa: E402
import numpy as np # noqa: E402
OUT = os.environ.get("OPUSDB_OUT", "out")
ST = os.path.join(OUT, "stats")
AS = os.path.join(OUT, "assets")
os.makedirs(AS, exist_ok=True)
# Validated categorical palette (fixed order), light surface.
C = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948"]
SURFACE, INK, INK2, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e6e5e0"
plt.rcParams.update({
"figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE,
"axes.edgecolor": GRID, "axes.labelcolor": INK2, "xtick.color": INK2, "ytick.color": INK2,
"text.color": INK, "axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.8,
"axes.spines.top": False, "axes.spines.right": False, "font.size": 10.5,
"axes.titlesize": 13, "axes.titleweight": "bold", "axes.titlelocation": "left", "figure.dpi": 150,
})
def load(name):
p = os.path.join(ST, name + ".json")
return json.load(open(p)) if os.path.exists(p) else None
def save(fig, name):
fig.tight_layout()
fig.savefig(os.path.join(AS, name), bbox_inches="tight")
plt.close(fig)
print("chart", name)
def human(n):
for unit, k in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
if n >= k:
return f"{n / k:.1f}{unit}" if n / k < 100 else f"{n / k:.0f}{unit}"
return str(int(n))
# ------------------------------------------------------------------ 1. token composition per config
def composition():
sft, pref, pre = load("sft_sources"), load("preference_sources"), load("pretrain_tokens")
tools = load("tools_sources")
panels = [("pretrain", {k: {"tokens": v} for k, v in (pre or {}).items()}), ("sft", sft or {}),
("preference", pref or {}), ("tools", tools or {})]
panels = [p for p in panels if p[1]]
fig, axes = plt.subplots(2, 2, figsize=(15, 9.5))
axes = axes.flatten()
for ax in axes[len(panels):]:
ax.axis("off")
for ax, (title, data) in zip(axes, panels):
items = sorted(data.items(), key=lambda kv: -kv[1]["tokens"])
names = [k for k, _ in items]
vals = [v["tokens"] for _, v in items]
y = np.arange(len(names))[::-1]
ax.barh(y, vals, color=C[0], height=0.62)
for yi, v in zip(y, vals):
ax.text(v, yi, " " + human(v), va="center", fontsize=9, color=INK2)
ax.set_yticks(y, names)
ax.set_title(f"{title}: {human(sum(vals))} tokens")
ax.set_xlabel("tokens (SmolLM2 tokenizer)")
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v, _: human(v) if v else "0"))
ax.grid(axis="y", visible=False)
ax.set_xlim(0, max(vals or [1]) * 1.25)
fig.suptitle("OPUS-5.5-DATABASE — token composition by config and source (measured)", x=0.01, ha="left",
fontweight="bold", fontsize=14)
save(fig, "composition.png")
# ------------------------------------------------------------------ 2. SFT domain + language mix
def sft_mix():
sft = load("sft_sources")
if not sft:
return
domains = {}
from collections import Counter
langs = Counter()
dom_map = {"smol-magpie-ultra": "general chat", "smol-constraints": "instruction following",
"smol-rewrite": "rewriting", "smol-summarize": "summarization", "oasst2": "human-written chat",
"metamathqa": "math", "openmathinstruct2": "math", "gsm8k": "math", "magicoder-oss": "code",
"codealpaca": "code", "opus-synth": "verified synthetic (EN/TR)"}
for k, v in sft.items():
d = dom_map.get(k, k)
domains[d] = domains.get(d, 0) + v["rows"]
for kk, vv in v.items():
if kk.startswith("lang_"):
langs[kk[5:]] += vv
fig, (a1, a2) = plt.subplots(1, 2, figsize=(14, 4.8), gridspec_kw={"width_ratios": [1.5, 1]})
items = sorted(domains.items(), key=lambda kv: -kv[1])
y = np.arange(len(items))[::-1]
tot = sum(v for _, v in items)
a1.barh(y, [v for _, v in items], color=C[0], height=0.62)
for yi, (_, v) in zip(y, items):
a1.text(v, yi, f" {v:,} ({100 * v / tot:.1f}%)", va="center", fontsize=9, color=INK2)
a1.set_yticks(y, [k for k, _ in items])
a1.set_xlim(0, items[0][1] * 1.35)
a1.grid(axis="y", visible=False)
a1.set_title(f"SFT conversations by capability ({tot:,} total)")
top = langs.most_common(6)
other = sum(langs.values()) - sum(v for _, v in top)
labels = [k for k, _ in top] + (["all remaining"] if other else [])
vals = [v for _, v in top] + ([other] if other else [])
y2 = np.arange(len(labels))[::-1]
a2.barh(y2, vals, color=C[2], height=0.62)
for yi, v in zip(y2, vals):
a2.text(v, yi, f" {v:,}", va="center", fontsize=9, color=INK2)
a2.set_yticks(y2, labels)
a2.set_xscale("log")
a2.set_xlim(min(vals) / 2, max(vals) * 8)
a2.grid(axis="y", visible=False)
a2.set_title("SFT conversations by language (log scale)")
save(fig, "sft_mix.png")
# ------------------------------------------------------------------ 3. length distribution
def lengths():
sl = load("sft_lengths")
pl = load("pretrain_lengths")
fig, (a1, a2) = plt.subplots(1, 2, figsize=(14, 4.6))
if sl:
bins = np.logspace(1, math.log10(8192), 50)
groups = {"chat & instruction": ("smol-magpie-ultra", "smol-constraints", "smol-rewrite", "smol-summarize", "oasst2"),
"math": ("metamathqa", "openmathinstruct2", "gsm8k"),
"code": ("magicoder-oss", "codealpaca"), "verified synthetic": ("opus-synth",)}
arr, src = np.array(sl["num_tokens"]), np.array(sl["source"])
for i, (g, srcs) in enumerate(groups.items()):
vals = arr[np.isin(src, srcs)]
a1.hist(vals, bins=bins, histtype="step", linewidth=2, color=C[i], label=f"{g} (median {int(np.median(vals))})")
a1.set_xscale("log")
a1.set_xlabel("tokens per conversation")
a1.set_ylabel("conversations")
a1.set_title("SFT conversation length")
a1.legend(frameon=False, fontsize=9)
if pl:
bins = np.logspace(1.5, 5, 50)
for i, (k, v) in enumerate(pl.items()):
a2.hist(v, bins=bins, histtype="step", linewidth=2, color=C[i], label=f"{k} (median {int(np.median(v))})")
a2.set_xscale("log")
a2.set_xlabel("tokens per document")
a2.set_ylabel("documents (sample)")
a2.set_title("Pretraining document length")
a2.legend(frameon=False, fontsize=9)
save(fig, "lengths.png")
# ------------------------------------------------------------------ 4. filtering funnel
def funnel():
parts = [("sft", load("sft_funnel")), ("preference", load("preference_funnel")), ("pretrain", load("pretrain_funnel"))]
rows = []
for cfg, f in parts:
if not f:
continue
for src, c in f.items():
if not isinstance(c, dict):
continue
read = c.get("read", 0)
kept = c.get("kept", 0)
q = sum(v for k, v in c.items() if k.startswith(("quality", "bad_", "empty", "boiler", "low_", "incomplete",
"no_margin", "identical", "argilla")))
dup = c.get("exact_duplicate", 0) + c.get("near_duplicate", 0)
con = c.get("benchmark_contaminated", 0)
cap = c.get("over_cap", 0)
rows.append((f"{cfg}/{src}", read, kept, q, dup, con, cap))
if not rows:
return
fig, ax = plt.subplots(figsize=(13, 0.42 * len(rows) + 1.6))
y = np.arange(len(rows))[::-1]
labels = ["kept", "quality / format filter", "duplicate (exact + MinHash)", "benchmark-contaminated", "subsampled (cap)"]
cols = [C[2], C[3], C[0], C[7], "#c9c8c2"]
for yi, r in zip(y, rows):
left = 0
read = max(1, r[1])
for j, v in enumerate([r[2], r[3], r[4], r[5], r[6]]):
w = 100 * v / read
ax.barh(yi, w, left=left, color=cols[j], height=0.62, edgecolor=SURFACE, linewidth=1.5,
label=labels[j] if yi == y[0] else None)
left += w
ax.text(101, yi, f"{r[2]:,} / {r[1]:,}", va="center", fontsize=8.5, color=INK2)
ax.set_yticks(y, [r[0] for r in rows], fontsize=9)
ax.set_xlim(0, 125)
ax.set_xticks([0, 20, 40, 60, 80, 100])
ax.set_xlabel("% of rows read")
ax.grid(axis="y", visible=False)
ax.legend(ncol=5, frameon=False, fontsize=9, loc="upper left", bbox_to_anchor=(0, -0.08))
ax.set_title("Filtering funnel per source (measured): kept rows / rows read")
save(fig, "funnel.png")
# ------------------------------------------------------------------ 5. measured scaling ladder
def ladder():
lad = load("ladder")
if not lad or not lad.get("runs"):
return
runs = sorted(lad["runs"], key=lambda r: r["total_params"])
fig, (a1, a2) = plt.subplots(1, 2, figsize=(14, 4.8))
for i, r in enumerate(runs):
xs = [p["tokens"] for p in r["curve"]]
ys = [p["val_loss"] for p in r["curve"]]
a1.plot(xs, ys, color=C[i], linewidth=2, label=f"{human(r['total_params'])} params")
a1.set_xscale("log")
a1.set_xlabel("training tokens")
a1.set_ylabel("validation loss (nats/token)")
a1.set_title("Measured: validation loss during training")
a1.legend(frameon=False, fontsize=9)
N = np.array([r["total_params"] for r in runs], float)
L = np.array([r["val_loss"] for r in runs])
a2.plot(N, L, "o", color=C[0], markersize=9, label="measured (final val loss)")
fit = lad.get("fit")
if fit:
xs = np.logspace(math.log10(N.min() / 2), math.log10(N.max() * 30), 100)
a2.plot(xs, fit["E"] + fit["A"] / xs ** fit["alpha"], "--", color=C[1], linewidth=2,
label=f"fit L = {fit['E']:.2f} + {fit['A']:.3g}/N^{fit['alpha']:.2f}")
for n, l in zip(N, L):
a2.annotate(f"{l:.2f}", (n, l), textcoords="offset points", xytext=(6, 6), fontsize=9, color=INK2)
a2.set_xscale("log")
a2.set_xlabel("model parameters (N)")
a2.set_ylabel("final validation loss")
a2.set_title("Measured: loss vs model size on OPUS pretrain")
a2.legend(frameon=False, fontsize=9)
save(fig, "ladder.png")
# ------------------------------------------------------------------ 6. projections (published scaling laws)
SIZES = [0.135, 0.5, 1, 4, 8, 14, 27, 70] # billions
def chinchilla(N, D, E=1.69, A=406.4, B=410.7, a=0.34, b=0.28):
return E + A / N ** a + B / D ** b
def effective_data(U, D, r_star=15.4):
"""Muennighoff et al. (2023) data-constrained scaling: value of repeated tokens decays."""
if D <= U:
return D
R = D / U - 1
return U + U * r_star * (1 - math.exp(-R / r_star))
def projections():
pre = load("pretrain_tokens")
sft = load("sft_sources")
tools = load("tools_sources") or {}
if not pre:
return
U = sum(pre.values())
fig, (a1, a2) = plt.subplots(1, 2, figsize=(14, 5))
Ns = np.array(SIZES) * 1e9
ideal = [chinchilla(n, 20 * n) for n in Ns]
opus = [chinchilla(n, effective_data(U, 20 * n)) for n in Ns]
opus1 = [chinchilla(n, U) for n in Ns]
a1.plot(Ns, ideal, "-o", color=C[0], lw=2, ms=6, label="unlimited unique data, 20 tok/param (Chinchilla optimum)")
a1.plot(Ns, opus, "-o", color=C[1], lw=2, ms=6, label=f"OPUS pretrain only ({human(U)} unique), repeated to 20 tok/param")
a1.plot(Ns, opus1, "--", color=C[6], lw=2, label="OPUS pretrain only, single epoch")
a1.set_xscale("log")
a1.set_xticks(Ns, [f"{s:g}B" for s in SIZES], rotation=45)
a1.minorticks_off()
a1.set_ylabel("projected loss (Chinchilla units, nats)")
a1.set_title("PROJECTION: pretraining from scratch")
a1.legend(frameon=False, fontsize=8.5)
# compute to fine-tune on SFT config (2 epochs) — arithmetic, not a measurement
if sft:
T = sum(v["tokens"] for v in sft.values()) + sum(v["tokens"] for v in tools.values())
flops = 6 * Ns * T * 2
h100 = flops / (989e12 * 0.40) / 3600
lora = h100 / 3 # LoRA skips weight-gradient matmuls for frozen weights (~2/3 of backward)
a2.plot(Ns, h100, "-o", color=C[0], lw=2, ms=6, label="full fine-tune")
a2.plot(Ns, lora, "-o", color=C[2], lw=2, ms=6, label="LoRA (approx.)")
for n, h in zip(Ns, h100):
if n / 1e9 in (0.5, 4, 8, 14, 27, 70):
a2.annotate(f"{h:,.1f} h", (n, h), textcoords="offset points", xytext=(-10, 8), fontsize=9, color=INK2)
a2.set_xscale("log")
a2.set_yscale("log")
a2.set_xticks(Ns, [f"{s:g}B" for s in SIZES], rotation=45)
a2.minorticks_off()
a2.set_ylabel("H100 GPU-hours (40% MFU)")
a2.set_title(f"ESTIMATE: 2 epochs on sft + tools ({human(T)} tokens)")
a2.legend(frameon=False, fontsize=9)
save(fig, "projections.png")
out = {"unique_pretrain_tokens": U,
"rows": [{"params_b": s, "chinchilla_optimal_tokens_b": 20 * s, "epochs_needed_on_opus": 20 * s * 1e9 / U,
"loss_unlimited": ideal[i], "loss_opus_repeated": opus[i], "loss_opus_1epoch": opus1[i]}
for i, s in enumerate(SIZES)]}
json.dump(out, open(os.path.join(ST, "projections.json"), "w"), indent=2)
# ------------------------------------------------------------------ 7. measured model evals on synth_eval
def evals():
ev = load("evals")
if not ev:
return
base = [r for r in ev if r.get("kind") == "baseline"]
tuned = [r for r in ev if r.get("kind") == "opus-sft"]
fig, (a1, a2) = plt.subplots(1, 2, figsize=(14, 4.8), gridspec_kw={"width_ratios": [1.2, 1]})
if base:
base = sorted(base, key=lambda r: r["params_b"])
x = np.arange(len(base))
a1.bar(x - 0.2, [100 * r["by_language"]["en"] for r in base], 0.38, color=C[0], label="English items")
a1.bar(x + 0.2, [100 * r["by_language"]["tr"] for r in base], 0.38, color=C[1], label="Turkish items")
for xi, r in zip(x, base):
a1.text(xi, 100 * max(r["by_language"].values()) + 2, f"{100 * r['accuracy']:.0f}%", ha="center",
fontsize=9, color=INK)
a1.set_xticks(x, [f"{r['label']}\n{r['params_b']:g}B" for r in base], fontsize=9)
a1.set_ylim(0, 100)
a1.set_ylabel("exact-match accuracy (%)")
a1.set_title(f"Measured: off-the-shelf models on OPUS synth_eval (n={base[0]['n']})")
a1.grid(axis="x", visible=False)
a1.legend(frameon=False, fontsize=9)
if tuned:
pairs = []
for t in tuned:
b = next((r for r in ev if r["model"] == t["base_model"]), None)
if b:
pairs.append((b, t))
fams = sorted(pairs[0][1]["by_family"]) if pairs else []
if pairs:
b, t = pairs[0]
y = np.arange(len(fams) + 1)[::-1]
bv = [100 * b["accuracy"]] + [100 * b["by_family"].get(f, 0) for f in fams]
tv = [100 * t["accuracy"]] + [100 * t["by_family"].get(f, 0) for f in fams]
a2.barh(y + 0.2, bv, 0.38, color="#c9c8c2", label=f"{b['label']} (before)")
a2.barh(y - 0.2, tv, 0.38, color=C[2], label=f"after OPUS-SFT ({t['train_examples']:,} ex.)")
a2.set_yticks(y, ["OVERALL"] + fams, fontsize=9)
a2.set_xlim(0, 100)
a2.set_xlabel("exact-match accuracy (%)")
a2.set_title("Measured: fine-tuning a small model on OPUS-SFT")
a2.grid(axis="y", visible=False)
a2.legend(frameon=False, fontsize=9, loc="lower right")
else:
a2.axis("off")
save(fig, "evals.png")
if __name__ == "__main__":
for f in (composition, sft_mix, lengths, funnel, ladder, projections, evals):
f()