aziz9788's picture
Initial commit
cf8c8d4
Raw History Blame Contribute Delete
23.4 kB
r"""Run a fine-tuning experiment end to end from one YAML file, resumably, and rank the results.
python -m common.experiment experiments/arabic_mdpbench/quick.yaml # everything
python -m common.experiment experiments/arabic_mdpbench/quick.yaml --dry-run # print the commands only
python -m common.experiment experiments/arabic_mdpbench/full.yaml --only sft # one run (+ what it needs)
python -m common.experiment experiments/arabic_mdpbench/full.yaml --leaderboard # just rebuild the table
Stages (each writes a .done marker under <OCR_RUNS_DIR>/experiments/<name>/ and is skipped when present):
prepare target-language data -> sieve -> balance -> photo augmentation; replay pages (+ self-labels)
baseline the base model on the dev pages
<run> train (sft | selfplay | grpo | self_distill, chained), then score each adapter scale on dev
leaderboard per run: target-language change and change on the other languages against the base model,
each with a 95% paired-bootstrap interval over documents; limits and collapse checks; selection
test the base model and the selected run on held-out test documents (disjoint from dev)
Model selection uses dev only; the test table is the number to report. manifest.json records the config,
git commit, package versions, GPU and data revisions of the experiment.
Replay is set per run (`replay_share`): SFT learns from labels the model did not write and needs it most;
self-play only trains where its own reading is wrong; GRPO and self-distillation learn from their own
outputs and are anchored by --kl / --sft-weight instead. Every run is scored on all languages anyway,
and the adapter-scale sweep (merging, arXiv 2610.05872) trades a little target gain for less forgetting.
"""
import argparse
import json
import os
import random
import re
import subprocess
import sys
from pathlib import Path
import yaml
from .paths import MODELS_DIR, REPO_ROOT, RUNS_DIR
DRY = False
def expand(obj):
if isinstance(obj, str):
return os.path.expandvars(obj)
if isinstance(obj, dict):
return {k: expand(v) for k, v in obj.items()}
if isinstance(obj, list):
return [expand(v) for v in obj]
return obj
def load(path):
cfg = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
for k, v in (cfg.get("env") or {}).items(): # defaults for ${VARS}; the real environment wins
os.environ.setdefault(k, str(v))
os.environ.setdefault("OCR_MODELS_DIR", str(MODELS_DIR))
cfg = expand(cfg)
cfg["_dir"] = RUNS_DIR / "experiments" / cfg["name"]
cfg["_cfg_dir"] = Path(path).resolve().parent
return cfg
def py(*args):
cmd = [sys.executable, "-m", *map(str, args)]
print("$ " + " ".join(f'"{c}"' if " " in c else c for c in cmd), flush=True)
if not DRY:
subprocess.run(cmd, check=True, cwd=REPO_ROOT)
def stage(cfg, name, fn):
marker = cfg["_dir"] / "done" / f"{name}.done"
if marker.exists():
print(f"[skip] {name} (done)")
return
print(f"\n=== {name} ===", flush=True)
fn()
if not DRY:
marker.parent.mkdir(parents=True, exist_ok=True)
marker.write_text("ok", encoding="utf-8")
def read_jsonl(p):
return [json.loads(l) for l in open(p, encoding="utf-8-sig") if l.strip()]
def write_jsonl(p, rows):
Path(p).parent.mkdir(parents=True, exist_ok=True)
with open(p, "w", encoding="utf-8") as fh:
for r in rows:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
# ---------------------------------------------------------------- data
def data_paths(cfg):
d = cfg["_dir"] / "data"
replay = d / "replay" / ("replay.self.jsonl" if cfg["data"]["replay"].get("labels", "self") == "self" else "replay.jsonl")
return {"prepared": d / "prepared", "clean": d / "clean.jsonl", "balanced": d / "balanced.jsonl",
"train": d / "target_train.jsonl", "replay": replay, "replay_dir": d / "replay"}
def prepare(cfg):
D, dc = data_paths(cfg), cfg["data"]
sources = (cfg["_cfg_dir"] / dc["sources"]) if not Path(dc["sources"]).is_absolute() else Path(dc["sources"])
py("common.data_prep", "--sources", sources, "--out", D["prepared"], "--formats", "hf",
*(["--limit", dc["limit_per_source"]] if dc.get("limit_per_source") else []))
py("common.select_data", "sieve", "--input", D["prepared"] / "canonical" / "train.jsonl", "--out", D["clean"])
py("common.select_data", "balance", "--input", D["clean"], "--per-source", dc.get("per_source", 4000),
"--out", D["balanced"])
py("common.photo_aug", "--input", D["balanced"], "--out", D["train"], "--share", dc.get("photo_share", 0.5),
"--mode", "add", "--img-dir", D["prepared"] / "photo_aug")
rp = dc["replay"]
if rp.get("per_lang", 0) > 0:
py("common.replay", "build", "--per-lang", rp["per_lang"], "--out", D["replay_dir"],
"--langs", *rp.get("langs", ["en", "zh_hans", "zh_hant", "ja", "ko", "ru"]))
if rp.get("labels", "self") == "self":
py("common.replay", "self-label", "--input", D["replay_dir"] / "replay.jsonl", "--model", base(cfg),
*pf_args(cfg), "--max-pixels", cfg["train"].get("max_pixels", 589824) * 2)
def mix(cfg, run):
"""Target-language training records + a share of replay records (seeded)."""
D = data_paths(cfg)
out = cfg["_dir"] / "data" / f"{run['name']}_train.jsonl"
if DRY:
return out
rows = read_jsonl(D["train"])
if run.get("levels"): # e.g. [page]: only full pages, no line images
rows = [r for r in rows if r.get("level") in run["levels"]]
share = float(run.get("replay_share", 0))
if share > 0 and D["replay"].exists():
replay = read_jsonl(D["replay"])
k = min(len(replay), round(share / (1 - share) * len(rows)))
rows += random.Random(cfg.get("seed", 0)).sample(replay, k)
random.Random(cfg.get("seed", 0)).shuffle(rows)
write_jsonl(out, rows)
print(f"{run['name']}: {len(rows)} training records (replay share {share})")
return out
# ---------------------------------------------------------------- model helpers
def base(cfg):
return cfg["base_model"]
def prompt_file(cfg):
p = cfg.get("prompt_file")
return str(Path(base(cfg)) / p) if p and not Path(p).is_absolute() else p
def pf_args(cfg):
pf = prompt_file(cfg)
return ["--prompt-file", pf] if pf else []
def bench_args(cfg, subset):
b = cfg["benchmark"]
return ["--subset", subset, "--max-pixels", b.get("max_pixels", 8294400), "--max-new", b.get("max_new", 8192),
*pf_args(cfg)]
def ensure_subset(cfg, which="dev"):
"""dev = benchmark.subset (used to choose a model); test = benchmark.test (documents disjoint from dev,
used once, for the final report)."""
from . import mdpbench
b = cfg["benchmark"]
spec = b if which == "dev" else b["test"]
if not (mdpbench.BENCH_DIR / "subsets" / spec["subset"] / "items.jsonl").exists():
py("common.mdpbench", "subset", "--name", spec["subset"], "--per-lang", spec["per_lang"],
"--seed", cfg.get("seed", 0), *(["--exclude", b["subset"]] if which == "test" else []))
return spec["subset"]
def btag(cfg, tag):
"""Benchmark result name, unique per experiment so two experiments never read each other's results."""
return f"{cfg['name']}__{tag}"
def last_round(folder, prefix):
found = sorted((p for p in Path(folder).glob(f"{prefix}*") if p.is_dir()),
key=lambda p: int(re.sub(r"\D", "", p.name) or 0))
return found[-1] if found else Path(folder) / f"{prefix}1"
STEP_DEFAULTS = { # every key of a run's step block becomes a flag: nora: true -> --nora, max_new: 2048 -> --max-new 2048
"sft": {"lora": 16, "lr": 1e-4, "epochs": 1, "grad_accum": 8, "max_length": 2048, "save_steps": 500},
"selfplay": {"rounds": 2, "limit": 0, "max_new": 2048, "lr": 5e-5},
"grpo": {"limit": 400, "group": 4, "kl": 0.02, "max_new": 2048},
"self_distill": {"epochs": 1, "limit": 0, "max_new": 2048},
}
def flags(opts):
"""{"max_new": 2048, "nora": True, "x": False} -> ["--max-new", 2048, "--nora"] (False/None are left out)."""
out = []
for k, v in opts.items():
if v is False or v is None:
continue
out.append("--" + k.replace("_", "-"))
if v is not True:
out.append(v)
return out
def train_run(cfg, run):
"""Run the run's steps in order; each step starts from the previous step's adapter. Returns the adapter."""
out = cfg["_dir"] / "runs" / run["name"]
adapter = adapter_of(cfg, run["from"]) if run.get("from") else None
data = mix(cfg, run)
t = {**cfg.get("train", {}), **run.get("train", {})}
common = ["--max-pixels", t.get("max_pixels", 589824), "--seed", cfg.get("seed", 0), *pf_args(cfg)]
gc = ["--gradient-checkpointing"] if t.get("gradient_checkpointing", True) else []
for step in run["steps"]:
if step not in STEP_DEFAULTS:
raise SystemExit(f"unknown step {step}")
s = {**STEP_DEFAULTS[step], **run.get(step, {})}
start = ["--adapter", adapter] if adapter else []
if step == "sft":
if adapter:
raise SystemExit(f"{run['name']}: sft starts from the base model; put it first, without 'from'")
py("common.vlm_sft", "--model", base(cfg), "--train", data, "--output", out / "sft", *flags(s), *common, *gc)
adapter = out / "sft"
elif step == "selfplay":
py("common.selfplay", "--model", base(cfg), *start, "--train", data, "--output", out / "selfplay",
*flags(s), *common, *gc)
adapter = last_round(out / "selfplay", "round")
elif step == "grpo":
pool = cfg["_dir"] / "data" / f"{run['name']}_grpo.jsonl"
cand = cfg["_dir"] / "data" / f"{run['name']}_grpo_candidates.jsonl"
if not DRY: # score 2x the kept count for uncertainty (FD-RL keeps the top half), not the whole set
rows = read_jsonl(data)
write_jsonl(cand, random.Random(cfg.get("seed", 0)).sample(rows, min(len(rows), 2 * int(s["limit"]))))
py("common.select_data", "entropy", "--input", cand, "--model", base(cfg), *start, "--keep", s["limit"],
"--out", pool, "--max-pixels", t.get("max_pixels", 589824), *pf_args(cfg))
py("common.grpo", "--model", base(cfg), *start, "--train", pool, "--output", out / "grpo",
*flags(s), *common, *gc)
adapter = out / "grpo" / "final"
elif step == "self_distill":
py("common.self_distill", "--model", base(cfg), *start, "--train", data, "--output", out / "self_distill",
*flags(s), *common, *gc)
adapter = last_round(out / "self_distill", "epoch")
return adapter
def adapter_of(cfg, run_name):
p = cfg["_dir"] / "runs" / run_name / "adapter.txt"
if DRY and not p.exists():
return cfg["_dir"] / "runs" / run_name / "<adapter>"
if not p.exists():
raise SystemExit(f"run '{run_name}' has not finished training (needed as 'from')")
return Path(p.read_text(encoding="utf-8").strip())
def tag_of(run, scale):
return run["name"] if float(scale) == 1.0 else f"{run['name']}@{scale}"
def do_run(cfg, run):
out = cfg["_dir"] / "runs" / run["name"]
def train():
adapter = train_run(cfg, run)
if not DRY:
out.mkdir(parents=True, exist_ok=True)
(out / "adapter.txt").write_text(str(adapter), encoding="utf-8")
stage(cfg, f"{run['name']}.train", train)
dev = ensure_subset(cfg)
for scale in run.get("eval_scales", [1.0]):
stage(cfg, f"{run['name']}.eval.{scale}", lambda s=scale: evaluate(cfg, run, s, dev))
def evaluate(cfg, run, scale, subset):
py("common.mdpbench", "run", "--tag", btag(cfg, tag_of(run, scale)), "--model", base(cfg),
"--adapter", adapter_of(cfg, run["name"]), "--adapter-scale", scale, *bench_args(cfg, subset))
# ---------------------------------------------------------------- leaderboard
SUMMARY_KEYS = [("Overall", "Overall_All"), ("Digital", "Overall_Digit"), ("Photo", "Overall_Photo"),
("Latin", "Latin_Avg"), ("Non-Latin", "Non-Latin_Avg")]
def page_lang(key):
"""Leaderboard key ('AR', 'ZH-T') -> page id prefix ('ar', 'zh-cht')."""
return "zh-cht" if key == "ZH-T" else key.lower()
def paired_bootstrap(base_pages, new_pages, keep, n=2000, seed=0):
"""Mean change in page score (points) over the pages `keep` selects, with a 95% interval from a paired
bootstrap that resamples documents, not pages: the 4 pages of a document (1 digital + 3 photographs)
are correlated, so resampling pages would make the interval too narrow. Returns (mean, lo, hi, pages)."""
from .mdpbench import doc_of
docs = {}
for pid, b in base_pages.items():
v = new_pages.get(pid)
if keep(pid) and b is not None and v is not None:
docs.setdefault(doc_of(pid), []).append(100.0 * (v - b))
if not docs:
return None
groups = list(docs.values())
flat = [d for g in groups for d in g]
rng = random.Random(seed)
means = []
for _ in range(n):
sample = [d for g in rng.choices(groups, k=len(groups)) for d in g]
means.append(sum(sample) / len(sample))
means.sort()
return sum(flat) / len(flat), means[int(0.025 * n)], means[int(0.975 * n) - 1], len(flat)
def load_results(cfg, subset, tags):
from . import mdpbench
root, res = mdpbench.RUNS_DIR / "mdpbench" / subset, {}
for t in tags:
d = root / btag(cfg, t)
if (d / "summary.json").exists() and (d / "pages.json").exists():
res[t] = {**json.loads((d / "summary.json").read_text(encoding="utf-8")),
"pages": json.loads((d / "pages.json").read_text(encoding="utf-8"))}
return res
def leaderboard(cfg, subset=None, tags=None, title="dev", write=True):
"""Rank runs on a benchmark subset. Returns the best tag (or None: keep the base model)."""
from .mdpbench import lang_of
b, sel = cfg["benchmark"], cfg.get("selection", {})
subset = subset or b["subset"]
target = sel.get("target", "AR")
max_drop = float(sel.get("max_drop", 3.0)) # any single other language, points
max_others = float(sel.get("max_others_drop", 1.0)) # all other languages pooled, points
tags = tags or ["base"] + [tag_of(r, s) for r in cfg["runs"] for s in r.get("eval_scales", [1.0])]
res = load_results(cfg, subset, tags)
if "base" not in res:
print(f"[{title}] no baseline result yet")
return None
base_r = res["base"]
tl = page_lang(target)
langs = sorted(k for k, v in base_r["scores"].items() if re.fullmatch(r"[A-Z]{2}(-T)?", k) and v is not None)
base_loops = sum(h["loops"] for h in base_r["health"].values())
rows = []
for t, r in res.items():
s = r["scores"]
tgt = paired_bootstrap(base_r["pages"], r["pages"], lambda p: lang_of(p) == tl, seed=cfg.get("seed", 0))
oth = paired_bootstrap(base_r["pages"], r["pages"], lambda p: lang_of(p) != tl, seed=cfg.get("seed", 0))
drops = {l: s[l] - base_r["scores"][l] for l in langs if l != target and s.get(l) is not None}
worst = min(drops.items(), key=lambda kv: kv[1]) if drops else None
loops = sum(h["loops"] for h in r["health"].values())
drift = max((h["arabic_share"] for l, h in r["health"].items() if l != tl), default=0.0)
reasons = []
if t != "base":
if worst and worst[1] < -max_drop:
reasons.append(f"{worst[0]} {worst[1]:+.1f}")
if oth and oth[0] < -max_others:
reasons.append(f"others {oth[0]:+.1f}")
if loops > base_loops + 2:
reasons.append(f"loops {loops}")
if target == "AR" and drift >= 0.2:
reasons.append(f"script drift {drift:.2f}")
rows.append({"tag": t, "target": s.get(target), "d_target": tgt, "d_others": oth, "worst": worst,
**{k: s.get(v) for k, v in SUMMARY_KEYS}, "loops": loops, "drift": drift,
"rejected": reasons, "gain": bool(tgt and tgt[0] > 0), "significant": bool(tgt and tgt[1] > 0)})
cands = [r for r in rows if r["tag"] != "base" and not r["rejected"] and r["gain"]]
best = max(cands, key=lambda r: (r["d_target"][0], r["d_others"][0] if r["d_others"] else 0), default=None)
def ci(x):
return "-" if not x else f"{x[0]:+.1f} [{x[1]:+.1f}, {x[2]:+.1f}]"
def num(v):
return "-" if v is None else f"{v:.1f}"
def status(r):
if r["tag"] == "base":
return "baseline"
if r["rejected"]:
return "rejected: " + ", ".join(r["rejected"])
if not r["gain"]:
return "no gain"
return "gain, significant" if r["significant"] else "gain, within noise"
hdr = ["Model", target, f"Δ{target} [95% CI]", "Δ other langs [95% CI]", "worst other lang", "Overall",
"Digital", "Photo", "loops", "status"]
lines = ["| " + " | ".join(hdr) + " |", "|" + "---|" * len(hdr)]
for r in sorted(rows, key=lambda r: (r["tag"] != "base", -(r["d_target"][0] if r["d_target"] else -1e9))):
is_base = r["tag"] == "base"
name = f"**{r['tag']}**" if best and r["tag"] == best["tag"] else r["tag"]
lines.append("| " + " | ".join([
name, num(r["target"]), "-" if is_base else ci(r["d_target"]), "-" if is_base else ci(r["d_others"]),
"-" if is_base or not r["worst"] else f"{r['worst'][0]} {r['worst'][1]:+.1f}",
num(r["Overall"]), num(r["Digital"]), num(r["Photo"]), str(r["loops"]), status(r)]) + " |")
n_t = next((r["d_target"][3] for r in rows if r["d_target"]), 0)
n_o = next((r["d_others"][3] for r in rows if r["d_others"]), 0)
if not best:
verdict = f"keep the base model: no run improved {target} within the limits"
elif best["significant"]:
verdict = best["tag"]
else:
verdict = f"{best['tag']} (its {target} gain is within noise on this subset: confirm on more pages)"
text = (f"# {cfg['name']} — {title} ({subset}: {n_t} {target} pages, {n_o} pages in other languages)\n\n"
+ "\n".join(lines) + "\n\n"
f"Scores: official MDPBench scorer, 0-100. Δ = mean change in page score against the base model on the "
f"same pages; interval = paired bootstrap over documents (2,000 resamples). A gain is significant when "
f"its interval excludes 0.\n"
f"Limits: no other language loses more than {max_drop} points, the other languages pooled lose at most "
f"{max_others}, decoding loops stay within baseline + 2, and no drift to the target script on other "
f"languages' pages.\n\nSelected: {verdict}\n")
if write and not DRY:
stem = "leaderboard" if title == "dev" else f"leaderboard_{title}"
(cfg["_dir"] / f"{stem}.md").write_text(text, encoding="utf-8")
(cfg["_dir"] / f"{stem}.json").write_text(json.dumps({"rows": rows, "best": best and best["tag"]}, indent=2),
encoding="utf-8")
print(text)
return best and best["tag"]
def final_test(cfg, best):
"""Score the base model and the selected run once on the held-out test documents."""
if not cfg["benchmark"].get("test"):
print("no benchmark.test in the config: dev scores are optimistic for the selected run")
return
test = ensure_subset(cfg, "test")
stage(cfg, "test.base", lambda: py("common.mdpbench", "run", "--tag", btag(cfg, "base"), "--model", base(cfg),
*bench_args(cfg, test)))
if not best:
return
name, _, scale = best.partition("@")
run = next(r for r in cfg["runs"] if r["name"] == name)
stage(cfg, f"test.{best}", lambda: evaluate(cfg, run, float(scale or 1.0), test))
if not DRY:
leaderboard(cfg, subset=test, tags=["base", best], title="test")
def manifest(cfg, config_path):
"""What produced these results: config, code version, package versions, hardware, data revisions."""
import platform
from importlib.metadata import PackageNotFoundError, version
from . import mdpbench, replay
def git(*args):
try:
return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True).stdout.strip()
except OSError:
return ""
def ver(pkg):
try:
return version(pkg)
except PackageNotFoundError:
return None
gpu = None
try:
import torch
if torch.cuda.is_available():
gpu = {"name": torch.cuda.get_device_name(0), "capability": list(torch.cuda.get_device_capability(0)),
"memory_gb": round(torch.cuda.get_device_properties(0).total_memory / 1e9, 1)}
except ImportError:
pass
m = {"experiment": cfg["name"], "config_file": str(config_path),
"config": yaml.safe_load(Path(config_path).read_text(encoding="utf-8")),
"seed": cfg.get("seed", 0), "git_commit": git("rev-parse", "HEAD"),
"git_dirty": bool(git("status", "--porcelain")), "python": platform.python_version(),
"platform": platform.platform(),
"packages": {p: ver(p) for p in ("torch", "transformers", "peft", "accelerate", "huggingface_hub", "pillow")},
"gpu": gpu,
"data_revisions": {"MDPBench": mdpbench.REVISION, "olmOCR-mix-1025": replay.OLMOCR[1],
"OCR-Synthetic-Multilingual-v1": replay.NVIDIA[1]},
"upstream_lock": json.loads((REPO_ROOT / "upstream.lock.json").read_text(encoding="utf-8")).get("MultimodalOCR")}
cfg["_dir"].mkdir(parents=True, exist_ok=True)
(cfg["_dir"] / "manifest.json").write_text(json.dumps(m, indent=2, ensure_ascii=False), encoding="utf-8")
def main(argv=None):
global DRY
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("config")
ap.add_argument("--only", nargs="*", help="run names to do (their 'from' runs must be done)")
ap.add_argument("--leaderboard", action="store_true", help="only rebuild the dev leaderboard")
ap.add_argument("--no-test", action="store_true", help="skip the final held-out test evaluation")
ap.add_argument("--dry-run", action="store_true", help="print the commands without running them")
a = ap.parse_args(argv)
DRY = a.dry_run
cfg = load(a.config)
if a.leaderboard:
leaderboard(cfg)
return
if not DRY:
manifest(cfg, a.config)
stage(cfg, "prepare", lambda: prepare(cfg))
dev = ensure_subset(cfg)
stage(cfg, "baseline", lambda: py("common.mdpbench", "run", "--tag", btag(cfg, "base"), "--model", base(cfg),
*bench_args(cfg, dev)))
for run in cfg["runs"]:
if not a.only or run["name"] in a.only:
do_run(cfg, run)
best = None if DRY else leaderboard(cfg)
if not a.no_test and not a.only:
final_test(cfg, best)
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
main()