Run r3: recipe comparison, keep-the-better rule, extra measurements
Browse files- control/reset.txt +1 -0
- control/run.env +19 -7
- emcdraft/ablate.py +83 -0
- emcdraft/train.py +60 -15
- scripts/bench.py +190 -0
- scripts/choose.py +55 -0
- scripts/collect.py +2 -1
- scripts/pipeline.sh +48 -7
- scripts/sync.py +6 -1
- tests/test_head.py +69 -0
control/reset.txt
CHANGED
|
@@ -2,3 +2,4 @@
|
|
| 2 |
# One per line: <unique id> [kill] <stage> [<stage> ...] - each id is applied once;
|
| 3 |
# "kill" stops a running pipeline first. Example: r1-2 train eval_main
|
| 4 |
r2 generate extract train eval_main report_main eval_alt report
|
|
|
|
|
|
| 2 |
# One per line: <unique id> [kill] <stage> [<stage> ...] - each id is applied once;
|
| 3 |
# "kill" stops a running pipeline first. Example: r1-2 train eval_main
|
| 4 |
r2 generate extract train eval_main report_main eval_alt report
|
| 5 |
+
r3 generate extract ablate train eval_main report_main eval_alt eval_prev choose report bench_draft bench_baseline bench_target report_bench
|
control/run.env
CHANGED
|
@@ -1,9 +1,21 @@
|
|
| 1 |
# KEY=VALUE settings passed to scripts/pipeline.sh by scripts/supervise.py
|
| 2 |
-
# run
|
| 3 |
-
#
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
EVAL_ALT=0
|
|
|
|
|
|
| 1 |
# KEY=VALUE settings passed to scripts/pipeline.sh by scripts/supervise.py
|
| 2 |
+
# run r3: 50% more data (earlier answers and features kept), four training recipes compared in
|
| 3 |
+
# short runs, the best one trained from the r2 head; the new draft replaces r2's only if it
|
| 4 |
+
# scores higher on this machine; then the batch / long-context / draft-length measurements
|
| 5 |
+
RUN_ID_FORCE=r3
|
| 6 |
+
GEN_TOKENS=6000000
|
| 7 |
+
GEN_MINUTES=75
|
| 8 |
+
GEN_APPEND=1
|
| 9 |
+
EXTRACT_MINUTES=50
|
| 10 |
+
EXTRACT_APPEND=1
|
| 11 |
+
ABLATE=1
|
| 12 |
+
ABLATE_STEPS=300
|
| 13 |
+
TRAIN_MINUTES=60
|
| 14 |
+
RUN_NAME=main3
|
| 15 |
+
TRAIN_INIT=runs/main/sub_bf16
|
| 16 |
+
TRAIN_INIT_HF=mudassiruddin21/EMC:submissions/r2/main-bf16
|
| 17 |
+
PREV_TAG=eval_draft_fp8
|
| 18 |
+
PREV_SUB=runs/main/sub_fp8
|
| 19 |
+
PREV_SUB_HF=mudassiruddin21/EMC:submissions/r2/main-fp8
|
| 20 |
EVAL_ALT=0
|
| 21 |
+
BENCH=1
|
emcdraft/ablate.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Short training runs that compare training recipes before the full run.
|
| 2 |
+
|
| 3 |
+
Every run starts from the same weights, sees the same data in the same order for the same
|
| 4 |
+
number of steps, and is scored by the offline simulator on the held-out validation set
|
| 5 |
+
(through FP8 rounding when --qat is given). The recipe with the highest validation
|
| 6 |
+
acceptance length is written to <state>/train_args for the full training run.
|
| 7 |
+
|
| 8 |
+
Recipes (each adds one published idea to the one before it):
|
| 9 |
+
control the recipe of the previous run (fixed step weights 1 / 0.7 / 0.5,
|
| 10 |
+
full-distribution distillation)
|
| 11 |
+
accw_topk acceptance-aware step weights - each step weighted by the derivative of
|
| 12 |
+
the acceptance length with respect to its accuracy, which favours early
|
| 13 |
+
steps (cf. Gumiho; FastMTP's decaying step weights) - plus distillation of
|
| 14 |
+
the target's top-10 tokens only (HASS, harmonized objective distillation)
|
| 15 |
+
accw_topk_mask + later steps trained almost only where the engine reaches them
|
| 16 |
+
(token-alignable training, GRIFFIN): floor 0.3 -> 0.1
|
| 17 |
+
accw_topk_lr2 accw_topk with twice the learning rate
|
| 18 |
+
|
| 19 |
+
python -m emcdraft.ablate --target DIR --init DIR --data DIR --out runs/ablate --results results --state state
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import subprocess
|
| 26 |
+
import sys
|
| 27 |
+
import time
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
RECIPES = [
|
| 31 |
+
("control", "previous recipe", ["--step-w", "1", "0.7", "0.5", "--topk", "0", "--floor", "0.3", "--rel-lr", "1e-3"]),
|
| 32 |
+
("accw_topk", "acceptance-aware step weights + top-10 distillation",
|
| 33 |
+
["--step-w", "auto", "--topk", "10", "--floor", "0.3", "--rel-lr", "1e-3"]),
|
| 34 |
+
("accw_topk_mask", "accw_topk + stricter masking of unreachable later steps",
|
| 35 |
+
["--step-w", "auto", "--topk", "10", "--floor", "0.1", "--rel-lr", "1e-3"]),
|
| 36 |
+
("accw_topk_lr2", "accw_topk + twice the learning rate",
|
| 37 |
+
["--step-w", "auto", "--topk", "10", "--floor", "0.3", "--rel-lr", "2e-3"]),
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def log(msg):
|
| 42 |
+
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
ap = argparse.ArgumentParser()
|
| 47 |
+
for k in ("--target", "--init", "--data", "--out", "--results", "--state"):
|
| 48 |
+
ap.add_argument(k, required=True)
|
| 49 |
+
ap.add_argument("--dev", default=None)
|
| 50 |
+
ap.add_argument("--qat", action="store_true")
|
| 51 |
+
ap.add_argument("--steps", type=int, default=300)
|
| 52 |
+
a = ap.parse_args()
|
| 53 |
+
out = Path(a.out)
|
| 54 |
+
report = {"steps": a.steps, "recipes": {}}
|
| 55 |
+
for name, desc, flags in RECIPES:
|
| 56 |
+
run = out / name
|
| 57 |
+
summary = run / "train_summary.json"
|
| 58 |
+
if not summary.exists(): # finished runs are reused after an interruption
|
| 59 |
+
cmd = [sys.executable, "-m", "emcdraft.train", "--target", a.target, "--init", a.init,
|
| 60 |
+
"--data", a.data, "--out", str(run), "--max-steps", str(a.steps), "--eval-every", "100",
|
| 61 |
+
"--no-export", "--quick", "--max-minutes", "600", *flags]
|
| 62 |
+
if a.dev:
|
| 63 |
+
cmd += ["--dev", a.dev]
|
| 64 |
+
if a.qat:
|
| 65 |
+
cmd.append("--qat")
|
| 66 |
+
log(f"recipe {name}: {desc}")
|
| 67 |
+
subprocess.run(cmd, check=True)
|
| 68 |
+
s = json.loads(summary.read_text())
|
| 69 |
+
start = s["sim"]["fp8_untrained" if a.qat else "init"]["val"]["acceptance_length"]
|
| 70 |
+
report["recipes"][name] = {"description": desc, "flags": flags, "val_tau_start": start,
|
| 71 |
+
"val_tau_best": s["best_val_tau"],
|
| 72 |
+
"history": s["history"], "seconds": s.get("total_seconds")}
|
| 73 |
+
log(f"recipe {name}: validation tau {start:.4f} -> {s['best_val_tau']:.4f}")
|
| 74 |
+
best = max(report["recipes"], key=lambda n: report["recipes"][n]["val_tau_best"])
|
| 75 |
+
report["chosen"] = best
|
| 76 |
+
Path(a.results).mkdir(parents=True, exist_ok=True)
|
| 77 |
+
(Path(a.results) / "ablation.json").write_text(json.dumps(report, indent=2))
|
| 78 |
+
(Path(a.state) / "train_args").write_text(" ".join(report["recipes"][best]["flags"]) + "\n")
|
| 79 |
+
log(f"chosen recipe: {best} ({report['recipes'][best]['description']})")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
main()
|
emcdraft/train.py
CHANGED
|
@@ -32,9 +32,12 @@ def log(msg):
|
|
| 32 |
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
| 33 |
|
| 34 |
|
| 35 |
-
def head_loss(o, W, y, w, teach, beta, chunk=2048):
|
| 36 |
"""Weighted CE (+ beta * soft-target CE) through the frozen LM head, in memory-bounded
|
| 37 |
-
chunks. Returns a surrogate whose gradient w.r.t. `o` equals the loss gradient.
|
|
|
|
|
|
|
|
|
|
| 38 |
n = o.shape[0]
|
| 39 |
denom = w.sum().clamp(min=1.0)
|
| 40 |
surrogate = torch.zeros((), device=o.device)
|
|
@@ -49,8 +52,14 @@ def head_loss(o, W, y, w, teach, beta, chunk=2048):
|
|
| 49 |
loss = (ce * w[s:e]).sum()
|
| 50 |
if teach is not None and beta > 0:
|
| 51 |
with torch.no_grad():
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
(g,) = torch.autograd.grad(loss / denom, z)
|
| 55 |
surrogate = surrogate + (o[s:e].float() * g.float()).sum()
|
| 56 |
ce_sum += float((ce.detach() * w[s:e]).sum())
|
|
@@ -74,8 +83,9 @@ def train_step(head, embed, W, batch, a, K=3):
|
|
| 74 |
bi, ni = valid.nonzero(as_tuple=True)
|
| 75 |
# the target's own distribution for the same token: h_{i+k} predicts x_{i+k+1}
|
| 76 |
teach = hidden[bi, (ni + k).clamp(max=N - 1)] if a.beta > 0 else None
|
| 77 |
-
s_k, ce_k, corr = head_loss(out[bi, ni], W, labels[bi, ni], w[bi, ni], teach, a.beta
|
| 78 |
-
|
|
|
|
| 79 |
full = torch.zeros(B, N, dtype=torch.bool, device=tokens.device)
|
| 80 |
full[bi, ni] = corr
|
| 81 |
reach = valid if prev is None else valid & prev
|
|
@@ -113,13 +123,26 @@ def main():
|
|
| 113 |
ap.add_argument("--batch-tokens", type=int, default=int(os.environ.get("TRAIN_BATCH_TOKENS", 8192)))
|
| 114 |
ap.add_argument("--rel-lr", type=float, default=float(os.environ.get("TRAIN_REL_LR", 1e-3)),
|
| 115 |
help="peak Adam step as a fraction of each tensor's RMS")
|
| 116 |
-
ap.add_argument("--beta", type=float, default=0.5)
|
| 117 |
-
|
| 118 |
-
ap.add_argument("--
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
ap.add_argument("--eval-every", type=int, default=60)
|
| 120 |
ap.add_argument("--seed", type=int, default=0)
|
| 121 |
ap.add_argument("--team", default=os.environ.get("TEAM_ID", "mudassiruddin"))
|
| 122 |
a = ap.parse_args()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
out = Path(a.out)
|
| 124 |
out.mkdir(parents=True, exist_ok=True)
|
| 125 |
rng = random.Random(a.seed)
|
|
@@ -152,13 +175,13 @@ def main():
|
|
| 152 |
|
| 153 |
def sims(tag):
|
| 154 |
r = {"val": simulate(head, embed, W, val)}
|
| 155 |
-
if dev_seqs:
|
| 156 |
r["dev"] = simulate(head, embed, W, dev_seqs)
|
| 157 |
summary["sim"][tag] = r
|
| 158 |
log(f"[{tag}] val tau {r['val']['acceptance_length']:.4f}"
|
| 159 |
+ (f" | dev tau {r['dev']['acceptance_length']:.4f} "
|
| 160 |
f"{ {d: round(v, 3) for d, v in r['dev']['acceptance_by_domain'].items()} } "
|
| 161 |
-
f"steps {[round(x, 3) for x in r['dev']['step_accuracy']]}" if
|
| 162 |
return r
|
| 163 |
|
| 164 |
sims("init")
|
|
@@ -175,7 +198,8 @@ def main():
|
|
| 175 |
log(f"equalisation factors {summary['equalize']} (must be function-preserving)")
|
| 176 |
if drift > 1e-2:
|
| 177 |
raise SystemExit(f"equalisation changed the head's output (drift {drift:.3g})")
|
| 178 |
-
|
|
|
|
| 179 |
head.set_fake_quant(True)
|
| 180 |
sims("fp8_untrained")
|
| 181 |
|
|
@@ -187,11 +211,17 @@ def main():
|
|
| 187 |
|
| 188 |
per_epoch = len(batches(train, a.batch_tokens))
|
| 189 |
total_steps = max(1, int(per_epoch * a.epochs))
|
|
|
|
|
|
|
| 190 |
warm = max(5, total_steps // 30)
|
| 191 |
key = "val"
|
| 192 |
-
|
|
|
|
| 193 |
"step": 0, "state": {k: v.detach().clone() for k, v in head.state_dict().items()}}
|
| 194 |
-
|
|
|
|
|
|
|
|
|
|
| 195 |
step, t0, hist = 0, time.time(), []
|
| 196 |
head.train()
|
| 197 |
done = False
|
|
@@ -206,7 +236,13 @@ def main():
|
|
| 206 |
f = (step + 1) / warm if step < warm else 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (step - warm) / max(1, total_steps - warm)))
|
| 207 |
for g in opt.param_groups:
|
| 208 |
g["lr"] = g["base"] * f
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
loss, info = train_step(head, embed, W, collate(group, device=dev), a)
|
|
|
|
| 210 |
opt.zero_grad(set_to_none=True)
|
| 211 |
loss.backward()
|
| 212 |
torch.nn.utils.clip_grad_norm_(head.parameters(), 1.0)
|
|
@@ -216,7 +252,8 @@ def main():
|
|
| 216 |
est = 1 + info["acc1"] * (1 + info["acc2"] * (1 + info["acc3"]))
|
| 217 |
log(f"step {step}/{total_steps} ce {info['ce1']:.3f}/{info['ce2']:.3f}/{info['ce3']:.3f} "
|
| 218 |
f"acc {info['acc1']:.3f}/{info['acc2']:.3f}/{info['acc3']:.3f} batch-tau~{est:.3f} "
|
| 219 |
-
f"lr x{f:.2f} {(time.time() - t0) / step:.2f}s/step"
|
|
|
|
| 220 |
if step % a.eval_every == 0 or step >= total_steps:
|
| 221 |
r = simulate(head, embed, W, val)
|
| 222 |
d = simulate(head, embed, W, dev_seqs[::4]) if dev_seqs else None
|
|
@@ -238,10 +275,18 @@ def main():
|
|
| 238 |
summary["best_step"] = best["step"]
|
| 239 |
summary["train_seconds"] = round(time.time() - t0, 1)
|
| 240 |
log(f"best checkpoint: step {best['step']} (val tau {best['tau']:.4f})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
meta = {"team_id": a.team,
|
| 243 |
"method_description": ("Replacement MTP head in the baseline layout, initialised from the target's "
|
| 244 |
"built-in head and fine-tuned with a 3-step recursive drafting objective"
|
|
|
|
|
|
|
| 245 |
+ (" and FP8 (E4M3) quantisation-aware training" if a.qat else "")),
|
| 246 |
"training_data": ("Greedy answers of the target itself (with its hidden states) to public "
|
| 247 |
"instruction prompts: GSM8K/Orca-Math, WritingPrompts, UltraChat/Alpaca/Dolly, "
|
|
|
|
| 32 |
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
| 33 |
|
| 34 |
|
| 35 |
+
def head_loss(o, W, y, w, teach, beta, chunk=2048, topk=0):
|
| 36 |
"""Weighted CE (+ beta * soft-target CE) through the frozen LM head, in memory-bounded
|
| 37 |
+
chunks. Returns a surrogate whose gradient w.r.t. `o` equals the loss gradient.
|
| 38 |
+
|
| 39 |
+
topk > 0 restricts the soft target to the target's `topk` most likely tokens (the
|
| 40 |
+
"harmonized objective distillation" of HASS): -sum_{t in top-k(p)} p(t) log q(t)."""
|
| 41 |
n = o.shape[0]
|
| 42 |
denom = w.sum().clamp(min=1.0)
|
| 43 |
surrogate = torch.zeros((), device=o.device)
|
|
|
|
| 52 |
loss = (ce * w[s:e]).sum()
|
| 53 |
if teach is not None and beta > 0:
|
| 54 |
with torch.no_grad():
|
| 55 |
+
tl = F.linear(teach[s:e], W.to(teach.dtype)).float()
|
| 56 |
+
if topk:
|
| 57 |
+
ix = tl.topk(topk, -1).indices
|
| 58 |
+
tp = F.softmax(tl, -1).gather(-1, ix)
|
| 59 |
+
else:
|
| 60 |
+
tp = F.softmax(tl, -1)
|
| 61 |
+
lq = logp.gather(-1, ix) if topk else logp
|
| 62 |
+
loss = loss + beta * (-(tp * lq).sum(-1) * w[s:e]).sum()
|
| 63 |
(g,) = torch.autograd.grad(loss / denom, z)
|
| 64 |
surrogate = surrogate + (o[s:e].float() * g.float()).sum()
|
| 65 |
ce_sum += float((ce.detach() * w[s:e]).sum())
|
|
|
|
| 83 |
bi, ni = valid.nonzero(as_tuple=True)
|
| 84 |
# the target's own distribution for the same token: h_{i+k} predicts x_{i+k+1}
|
| 85 |
teach = hidden[bi, (ni + k).clamp(max=N - 1)] if a.beta > 0 else None
|
| 86 |
+
s_k, ce_k, corr = head_loss(out[bi, ni], W, labels[bi, ni], w[bi, ni], teach, a.beta,
|
| 87 |
+
topk=getattr(a, "topk", 0))
|
| 88 |
+
total = total + getattr(a, "step_w_cur", a.step_w)[k - 1] * s_k
|
| 89 |
full = torch.zeros(B, N, dtype=torch.bool, device=tokens.device)
|
| 90 |
full[bi, ni] = corr
|
| 91 |
reach = valid if prev is None else valid & prev
|
|
|
|
| 123 |
ap.add_argument("--batch-tokens", type=int, default=int(os.environ.get("TRAIN_BATCH_TOKENS", 8192)))
|
| 124 |
ap.add_argument("--rel-lr", type=float, default=float(os.environ.get("TRAIN_REL_LR", 1e-3)),
|
| 125 |
help="peak Adam step as a fraction of each tensor's RMS")
|
| 126 |
+
ap.add_argument("--beta", type=float, default=float(os.environ.get("TRAIN_BETA", 0.5)),
|
| 127 |
+
help="weight of the soft-target (distillation) term")
|
| 128 |
+
ap.add_argument("--topk", type=int, default=int(os.environ.get("TRAIN_TOPK", 0)),
|
| 129 |
+
help="distil only the target's top-k tokens (0: full distribution)")
|
| 130 |
+
ap.add_argument("--floor", type=float, default=float(os.environ.get("TRAIN_FLOOR", 0.3)),
|
| 131 |
+
help="weight of later-step positions the engine would not reach")
|
| 132 |
+
ap.add_argument("--step-w", nargs="+", default=os.environ.get("TRAIN_STEP_W", "1 0.7 0.5").split(),
|
| 133 |
+
help="three step weights, or 'auto': each step weighted by the derivative of the "
|
| 134 |
+
"acceptance length with respect to its accuracy")
|
| 135 |
+
ap.add_argument("--max-steps", type=int, default=0, help="cap on optimizer steps (short ablation runs)")
|
| 136 |
+
ap.add_argument("--no-export", action="store_true", help="ablation run: no submission folders")
|
| 137 |
+
ap.add_argument("--quick", action="store_true", help="ablation run: simulate the validation set only")
|
| 138 |
ap.add_argument("--eval-every", type=int, default=60)
|
| 139 |
ap.add_argument("--seed", type=int, default=0)
|
| 140 |
ap.add_argument("--team", default=os.environ.get("TEAM_ID", "mudassiruddin"))
|
| 141 |
a = ap.parse_args()
|
| 142 |
+
auto_w = [x.lower() for x in a.step_w] == ["auto"]
|
| 143 |
+
if not auto_w:
|
| 144 |
+
a.step_w = [float(x) for x in a.step_w]
|
| 145 |
+
assert len(a.step_w) == 3, "--step-w takes three numbers or 'auto'"
|
| 146 |
out = Path(a.out)
|
| 147 |
out.mkdir(parents=True, exist_ok=True)
|
| 148 |
rng = random.Random(a.seed)
|
|
|
|
| 175 |
|
| 176 |
def sims(tag):
|
| 177 |
r = {"val": simulate(head, embed, W, val)}
|
| 178 |
+
if dev_seqs and not a.quick:
|
| 179 |
r["dev"] = simulate(head, embed, W, dev_seqs)
|
| 180 |
summary["sim"][tag] = r
|
| 181 |
log(f"[{tag}] val tau {r['val']['acceptance_length']:.4f}"
|
| 182 |
+ (f" | dev tau {r['dev']['acceptance_length']:.4f} "
|
| 183 |
f"{ {d: round(v, 3) for d, v in r['dev']['acceptance_by_domain'].items()} } "
|
| 184 |
+
f"steps {[round(x, 3) for x in r['dev']['step_accuracy']]}" if "dev" in r else ""))
|
| 185 |
return r
|
| 186 |
|
| 187 |
sims("init")
|
|
|
|
| 198 |
log(f"equalisation factors {summary['equalize']} (must be function-preserving)")
|
| 199 |
if drift > 1e-2:
|
| 200 |
raise SystemExit(f"equalisation changed the head's output (drift {drift:.3g})")
|
| 201 |
+
if not a.quick:
|
| 202 |
+
sims("equalized")
|
| 203 |
head.set_fake_quant(True)
|
| 204 |
sims("fp8_untrained")
|
| 205 |
|
|
|
|
| 211 |
|
| 212 |
per_epoch = len(batches(train, a.batch_tokens))
|
| 213 |
total_steps = max(1, int(per_epoch * a.epochs))
|
| 214 |
+
if a.max_steps:
|
| 215 |
+
total_steps = min(total_steps, a.max_steps)
|
| 216 |
warm = max(5, total_steps // 30)
|
| 217 |
key = "val"
|
| 218 |
+
start = summary["sim"]["fp8_untrained" if a.qat else "init"][key]
|
| 219 |
+
best = {"tau": start["acceptance_length"],
|
| 220 |
"step": 0, "state": {k: v.detach().clone() for k, v in head.state_dict().items()}}
|
| 221 |
+
# running per-step conditional accuracies, for acceptance-aware step weights
|
| 222 |
+
acc_ema = list(start["step_accuracy"])
|
| 223 |
+
log(f"training: {total_steps} steps planned ({per_epoch}/epoch), qat={a.qat}, "
|
| 224 |
+
f"step weights {'auto' if auto_w else a.step_w}, top-k {a.topk}, floor {a.floor}, rel-lr {a.rel_lr}")
|
| 225 |
step, t0, hist = 0, time.time(), []
|
| 226 |
head.train()
|
| 227 |
done = False
|
|
|
|
| 236 |
f = (step + 1) / warm if step < warm else 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (step - warm) / max(1, total_steps - warm)))
|
| 237 |
for g in opt.param_groups:
|
| 238 |
g["lr"] = g["base"] * f
|
| 239 |
+
if auto_w:
|
| 240 |
+
# d tau / d a_k for tau = 1 + a1 + a1 a2 + a1 a2 a3, normalised to step 1
|
| 241 |
+
a1, a2, a3 = acc_ema
|
| 242 |
+
d = [1 + a2 + a2 * a3, a1 * (1 + a3), a1 * a2]
|
| 243 |
+
a.step_w_cur = [x / d[0] for x in d]
|
| 244 |
loss, info = train_step(head, embed, W, collate(group, device=dev), a)
|
| 245 |
+
acc_ema = [0.98 * e + 0.02 * info[f"acc{k + 1}"] for k, e in enumerate(acc_ema)]
|
| 246 |
opt.zero_grad(set_to_none=True)
|
| 247 |
loss.backward()
|
| 248 |
torch.nn.utils.clip_grad_norm_(head.parameters(), 1.0)
|
|
|
|
| 252 |
est = 1 + info["acc1"] * (1 + info["acc2"] * (1 + info["acc3"]))
|
| 253 |
log(f"step {step}/{total_steps} ce {info['ce1']:.3f}/{info['ce2']:.3f}/{info['ce3']:.3f} "
|
| 254 |
f"acc {info['acc1']:.3f}/{info['acc2']:.3f}/{info['acc3']:.3f} batch-tau~{est:.3f} "
|
| 255 |
+
f"lr x{f:.2f} {(time.time() - t0) / step:.2f}s/step"
|
| 256 |
+
+ (f" w {[round(x, 2) for x in a.step_w_cur]}" if auto_w else ""))
|
| 257 |
if step % a.eval_every == 0 or step >= total_steps:
|
| 258 |
r = simulate(head, embed, W, val)
|
| 259 |
d = simulate(head, embed, W, dev_seqs[::4]) if dev_seqs else None
|
|
|
|
| 275 |
summary["best_step"] = best["step"]
|
| 276 |
summary["train_seconds"] = round(time.time() - t0, 1)
|
| 277 |
log(f"best checkpoint: step {best['step']} (val tau {best['tau']:.4f})")
|
| 278 |
+
summary["best_val_tau"] = best["tau"]
|
| 279 |
+
if a.no_export:
|
| 280 |
+
summary["total_seconds"] = round(time.time() - t_start, 1)
|
| 281 |
+
(out / "train_summary.json").write_text(json.dumps(summary, indent=2, default=str))
|
| 282 |
+
log("ablation run finished (no export)")
|
| 283 |
+
return
|
| 284 |
|
| 285 |
meta = {"team_id": a.team,
|
| 286 |
"method_description": ("Replacement MTP head in the baseline layout, initialised from the target's "
|
| 287 |
"built-in head and fine-tuned with a 3-step recursive drafting objective"
|
| 288 |
+
+ (", acceptance-aware step weights" if auto_w else "")
|
| 289 |
+
+ (f", top-{a.topk} distillation" if a.topk else "")
|
| 290 |
+ (" and FP8 (E4M3) quantisation-aware training" if a.qat else "")),
|
| 291 |
"training_data": ("Greedy answers of the target itself (with its hidden states) to public "
|
| 292 |
"instruction prompts: GSM8K/Orca-Math, WritingPrompts, UltraChat/Alpaca/Dolly, "
|
scripts/bench.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Measurements beyond the official score, with the kit's own engine command line and client.
|
| 3 |
+
|
| 4 |
+
batch concurrent requests 1, 2, 4 on the official engine settings (which allow 4
|
| 5 |
+
sequences), then 8 and 16 on an engine with room for 16: aggregate throughput,
|
| 6 |
+
per-request TPOT and TTFT, acceptance length
|
| 7 |
+
long prompts of about 1K to 16K tokens (a document assembled from the kit's reference
|
| 8 |
+
outputs, then an instruction), one request at a time: TTFT, TPOT, acceptance length
|
| 9 |
+
k draft lengths 8 and 12 instead of the competition's fixed 3 (information only)
|
| 10 |
+
|
| 11 |
+
Environment as for scripts/kit.py (EMC2_HOME, EMC_TARGET, EMC_SUB, EMC2_WORK, EMC_RESULTS);
|
| 12 |
+
--target-only measures the target without a draft. Writes $EMC_RESULTS/bench_<tag>.json.
|
| 13 |
+
|
| 14 |
+
python scripts/bench.py --tag draft --what batch,long,k
|
| 15 |
+
"""
|
| 16 |
+
import argparse
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import statistics
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
+
import traceback
|
| 23 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
kit = Path(os.environ["EMC2_HOME"]).resolve()
|
| 27 |
+
work = Path(os.environ.get("EMC2_WORK", "emc2-work")).resolve()
|
| 28 |
+
cache = work / "cache"
|
| 29 |
+
os.environ.update({
|
| 30 |
+
"EMC2_HOME": str(kit), "EMC2_WORK": str(work), "PYTHONDONTWRITEBYTECODE": "1",
|
| 31 |
+
"HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", "VLLM_NO_USAGE_STATS": "1", "DO_NOT_TRACK": "1",
|
| 32 |
+
"XDG_CACHE_HOME": str(cache), "HF_HOME": str(cache / "hf"), "VLLM_CACHE_ROOT": str(cache / "vllm"),
|
| 33 |
+
"TORCHINDUCTOR_CACHE_DIR": str(cache / "inductor"), "TRITON_CACHE_DIR": str(cache / "triton"),
|
| 34 |
+
"PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", ""),
|
| 35 |
+
})
|
| 36 |
+
sys.path.insert(0, str(kit))
|
| 37 |
+
from emc2 import client, common, server # noqa: E402
|
| 38 |
+
from emc2.common import load_json, load_jsonl # noqa: E402
|
| 39 |
+
|
| 40 |
+
TARGET = Path(os.environ["EMC_TARGET"]).resolve()
|
| 41 |
+
for mod in (common, server):
|
| 42 |
+
for name, value in (("TARGET_DIR", TARGET), ("WORK", work)):
|
| 43 |
+
if hasattr(mod, name):
|
| 44 |
+
setattr(mod, name, value)
|
| 45 |
+
DATA = kit / "data" / "dev"
|
| 46 |
+
CHAT_PREFIX = [248045, 846, 198] # <|im_start|>user\n
|
| 47 |
+
CHAT_SUFFIX = [248046, 198, 248045, 74455, 198, 248068, 271, 248069, 271] # ... assistant, no thinking
|
| 48 |
+
LENGTHS = (1000, 2000, 4000, 8000, 12000, 16000)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def log(msg):
|
| 52 |
+
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def ms(xs, q=0.5):
|
| 56 |
+
xs = sorted(x for x in xs if x is not None)
|
| 57 |
+
return round(1000 * xs[min(len(xs) - 1, int(q * len(xs)))], 2) if xs else None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def subset(prompts, per_domain):
|
| 61 |
+
seen, out = {}, []
|
| 62 |
+
for p in prompts:
|
| 63 |
+
if seen.get(p["domain"], 0) < per_domain:
|
| 64 |
+
seen[p["domain"]] = seen.get(p["domain"], 0) + 1
|
| 65 |
+
out.append(p)
|
| 66 |
+
return out
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Bench:
|
| 70 |
+
def __init__(self, sub, contract, target, stop):
|
| 71 |
+
self.spec = {"method": "mtp", "model": str(sub)} if sub else None
|
| 72 |
+
self.contract, self.target, self.stop = contract, target, stop
|
| 73 |
+
self.timeout = contract["request_timeout_s"]
|
| 74 |
+
|
| 75 |
+
def server(self, name, **override):
|
| 76 |
+
return server.VllmServer(dict(self.contract, **override), self.target, spec=self.spec, name=name)
|
| 77 |
+
|
| 78 |
+
def counters(self, srv):
|
| 79 |
+
return client.spec_counters(srv.url) if self.spec else (0.0, 0.0)
|
| 80 |
+
|
| 81 |
+
def warm(self, srv):
|
| 82 |
+
for w in load_jsonl(DATA / "warmup.jsonl"):
|
| 83 |
+
client.complete(srv.url, w["prompt_token_ids"], w["max_tokens"], self.stop, self.timeout)
|
| 84 |
+
|
| 85 |
+
def run(self, srv, prompts, concurrency=1):
|
| 86 |
+
"""Send the prompts with `concurrency` requests in flight; one row of measurements."""
|
| 87 |
+
a0, d0 = self.counters(srv)
|
| 88 |
+
t0 = time.monotonic()
|
| 89 |
+
call = lambda p: client.complete(srv.url, p["prompt_token_ids"], p["max_tokens"], self.stop, self.timeout)
|
| 90 |
+
with ThreadPoolExecutor(concurrency) as ex:
|
| 91 |
+
res = list(ex.map(call, prompts))
|
| 92 |
+
wall = time.monotonic() - t0
|
| 93 |
+
a1, d1 = self.counters(srv)
|
| 94 |
+
toks = sum(len(r["token_ids"]) for r in res)
|
| 95 |
+
return {"requests": len(res), "concurrency": concurrency, "output_tokens": toks,
|
| 96 |
+
"wall_s": round(wall, 2), "throughput_tok_s": round(toks / wall, 1),
|
| 97 |
+
"tpot_median_ms": ms([r["tpot_s"] for r in res]), "tpot_p90_ms": ms([r["tpot_s"] for r in res], 0.9),
|
| 98 |
+
"ttft_median_ms": ms([r["ttft_s"] for r in res]), "ttft_max_ms": ms([r["ttft_s"] for r in res], 1.0),
|
| 99 |
+
"acceptance_length": round(1 + (a1 - a0) / (d1 - d0), 4) if self.spec and d1 > d0 else None}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def long_prompts(per_length=2):
|
| 103 |
+
from tokenizers import Tokenizer
|
| 104 |
+
tok = Tokenizer.from_file(str(TARGET / "tokenizer.json"))
|
| 105 |
+
sep = tok.encode("\n\n", add_special_tokens=False).ids
|
| 106 |
+
instr = tok.encode("\n\nSummarize the text above in detail, section by section.", add_special_tokens=False).ids
|
| 107 |
+
stream = []
|
| 108 |
+
for r in load_jsonl(DATA / "reference.jsonl"):
|
| 109 |
+
stream += [t for t in r["token_ids"] if t < 248044] + sep # plain text only
|
| 110 |
+
while len(stream) < 2 * LENGTHS[-1]:
|
| 111 |
+
stream += stream
|
| 112 |
+
out = []
|
| 113 |
+
for L in LENGTHS:
|
| 114 |
+
body = L - len(CHAT_PREFIX) - len(instr) - len(CHAT_SUFFIX)
|
| 115 |
+
for j in range(per_length):
|
| 116 |
+
off = (j * len(stream) // per_length) % (len(stream) - body)
|
| 117 |
+
ids = CHAT_PREFIX + stream[off:off + body] + instr + CHAT_SUFFIX
|
| 118 |
+
out.append({"length": len(ids), "prompt_token_ids": ids, "max_tokens": 256})
|
| 119 |
+
return out
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def main():
|
| 123 |
+
ap = argparse.ArgumentParser()
|
| 124 |
+
ap.add_argument("--tag", required=True)
|
| 125 |
+
ap.add_argument("--what", default="batch,long")
|
| 126 |
+
ap.add_argument("--target-only", action="store_true")
|
| 127 |
+
ap.add_argument("--per-domain", type=int, default=8)
|
| 128 |
+
a = ap.parse_args()
|
| 129 |
+
sub = None if a.target_only or not os.environ.get("EMC_SUB") else Path(os.environ["EMC_SUB"]).resolve()
|
| 130 |
+
contract, target = load_json(kit / "contract.json"), load_json(kit / "target.json")
|
| 131 |
+
b = Bench(sub, contract, target, load_json(DATA / "meta.json")["stop_token_ids"])
|
| 132 |
+
prompts = subset(load_jsonl(DATA / "prompts.jsonl"), a.per_domain)
|
| 133 |
+
out = {"tag": a.tag, "draft": str(sub) if sub else None, "prompts": len(prompts),
|
| 134 |
+
"official_max_num_seqs": contract["max_num_seqs"], "batch": [], "long": [], "k": [], "errors": []}
|
| 135 |
+
dest = Path(os.environ.get("EMC_RESULTS", work / "results")) / f"bench_{a.tag}.json"
|
| 136 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 137 |
+
save = lambda: dest.write_text(json.dumps(out, indent=2))
|
| 138 |
+
what = set(a.what.split(","))
|
| 139 |
+
|
| 140 |
+
def section(name, fn):
|
| 141 |
+
if name not in what:
|
| 142 |
+
return
|
| 143 |
+
try:
|
| 144 |
+
fn()
|
| 145 |
+
except Exception as e: # noqa: BLE001 - keep the other measurements
|
| 146 |
+
out["errors"].append(f"{name}: {type(e).__name__}: {e}")
|
| 147 |
+
traceback.print_exc()
|
| 148 |
+
save()
|
| 149 |
+
|
| 150 |
+
def batch():
|
| 151 |
+
for max_seqs, levels in ((contract["max_num_seqs"], (1, 2, 4)), (16, (8, 16))):
|
| 152 |
+
with b.server(f"bench-batch{max_seqs}", max_num_seqs=max_seqs) as srv:
|
| 153 |
+
b.warm(srv)
|
| 154 |
+
for n in levels:
|
| 155 |
+
row = dict(b.run(srv, prompts, n), engine_max_num_seqs=max_seqs)
|
| 156 |
+
out["batch"].append(row)
|
| 157 |
+
log(f"batch {n}: {row}")
|
| 158 |
+
save()
|
| 159 |
+
|
| 160 |
+
def long():
|
| 161 |
+
rows = long_prompts()
|
| 162 |
+
with b.server("bench-long") as srv:
|
| 163 |
+
b.warm(srv)
|
| 164 |
+
for L in LENGTHS:
|
| 165 |
+
group = [r for r in rows if abs(r["length"] - L) < 64]
|
| 166 |
+
row = dict(b.run(srv, group, 1), prompt_tokens=L)
|
| 167 |
+
out["long"].append(row)
|
| 168 |
+
log(f"context {L}: {row}")
|
| 169 |
+
save()
|
| 170 |
+
|
| 171 |
+
def k():
|
| 172 |
+
if not sub:
|
| 173 |
+
return
|
| 174 |
+
for kk in (8, 12):
|
| 175 |
+
with b.server(f"bench-k{kk}", num_speculative_tokens=kk) as srv:
|
| 176 |
+
b.warm(srv)
|
| 177 |
+
row = dict(b.run(srv, prompts, 1), num_speculative_tokens=kk)
|
| 178 |
+
out["k"].append(row)
|
| 179 |
+
log(f"K={kk}: {row}")
|
| 180 |
+
save()
|
| 181 |
+
|
| 182 |
+
section("batch", batch)
|
| 183 |
+
section("long", long)
|
| 184 |
+
section("k", k)
|
| 185 |
+
log(f"wrote {dest}")
|
| 186 |
+
return 0 if not out["errors"] else 1
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
sys.exit(main())
|
scripts/choose.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Keep the better draft: the new run's draft replaces the previous best only when its
|
| 3 |
+
same-GPU score (kit formula against the baseline measured on this machine) is higher.
|
| 4 |
+
|
| 5 |
+
Writes <results>/choice.json and <state>/final_sub (the folder of the draft that is kept).
|
| 6 |
+
|
| 7 |
+
choose.py --new TAG --new-sub DIR [--prev TAG --prev-sub DIR] --results DIR --state DIR
|
| 8 |
+
"""
|
| 9 |
+
import argparse
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 16 |
+
from collect import score # noqa: E402
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main():
|
| 20 |
+
ap = argparse.ArgumentParser()
|
| 21 |
+
ap.add_argument("--new", required=True)
|
| 22 |
+
ap.add_argument("--new-sub", required=True)
|
| 23 |
+
ap.add_argument("--prev", default="")
|
| 24 |
+
ap.add_argument("--prev-sub", default="")
|
| 25 |
+
ap.add_argument("--results", required=True)
|
| 26 |
+
ap.add_argument("--state", required=True)
|
| 27 |
+
a = ap.parse_args()
|
| 28 |
+
res = Path(a.results)
|
| 29 |
+
kit = Path(os.environ["EMC2_HOME"])
|
| 30 |
+
cfg = json.loads((kit / "contract.json").read_text())["score"]
|
| 31 |
+
base = json.loads((res / "eval_baseline.json").read_text())
|
| 32 |
+
rows = {}
|
| 33 |
+
for name, tag, sub in (("new", a.new, a.new_sub), ("previous", a.prev, a.prev_sub)):
|
| 34 |
+
p = res / f"{tag}.json"
|
| 35 |
+
if tag and p.exists() and sub and Path(sub).is_dir():
|
| 36 |
+
m = json.loads(p.read_text())
|
| 37 |
+
rows[name] = {"tag": tag, "folder": sub, "acceptance_length": m["acceptance_length"],
|
| 38 |
+
"tpot_median_s": m["tpot_median_s"], "memory_bytes": m["memory_bytes"],
|
| 39 |
+
"same_gpu": score(m, base, cfg)}
|
| 40 |
+
if not rows:
|
| 41 |
+
raise SystemExit("no evaluated draft to choose from")
|
| 42 |
+
keep = max(rows, key=lambda n: rows[n]["same_gpu"]["score"])
|
| 43 |
+
out = {"kept": keep, "rows": rows,
|
| 44 |
+
"rule": "the new draft replaces the previous one only with a higher same-GPU score"}
|
| 45 |
+
(res / "choice.json").write_text(json.dumps(out, indent=2))
|
| 46 |
+
(Path(a.state) / "final_sub").write_text(rows[keep]["folder"] + "\n")
|
| 47 |
+
for n, r in rows.items():
|
| 48 |
+
print(f"{n:9s} {r['tag']}: tau {r['acceptance_length']:.4f}, TPOT {r['tpot_median_s'] * 1000:.2f} ms, "
|
| 49 |
+
f"same-GPU score {r['same_gpu']['score']}")
|
| 50 |
+
print(f"kept: {keep} ({rows[keep]['folder']})")
|
| 51 |
+
return 0
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
sys.exit(main())
|
scripts/collect.py
CHANGED
|
@@ -49,7 +49,8 @@ def main():
|
|
| 49 |
+ " / ".join(f"{m['acceptance_by_domain'].get(d, 0) or 0:.2f}" for d in ("chat", "code", "math", "longform"))
|
| 50 |
+ f" | {m['tpot_median_s'] * 1000:.2f} | {m['memory_bytes'] / 1e9:.3f} | "
|
| 51 |
+ (f"{off:.1f}" if off is not None else "-") + " | " + (f"{same:.1f}" if same is not None else "-") + " |")
|
| 52 |
-
|
|
|
|
| 53 |
out[p.stem] = json.loads(p.read_text())
|
| 54 |
for p in sorted(ROOT.glob("runs/*/train_summary.json")):
|
| 55 |
t = json.loads(p.read_text())
|
|
|
|
| 49 |
+ " / ".join(f"{m['acceptance_by_domain'].get(d, 0) or 0:.2f}" for d in ("chat", "code", "math", "longform"))
|
| 50 |
+ f" | {m['tpot_median_s'] * 1000:.2f} | {m['memory_bytes'] / 1e9:.3f} | "
|
| 51 |
+ (f"{off:.1f}" if off is not None else "-") + " | " + (f"{same:.1f}" if same is not None else "-") + " |")
|
| 52 |
+
extra = ["*_checks.json", "generation.json", "ablation.json", "choice.json", "bench_*.json"]
|
| 53 |
+
for p in [q for pat in extra for q in sorted(RES.glob(pat))]:
|
| 54 |
out[p.stem] = json.loads(p.read_text())
|
| 55 |
for p in sorted(ROOT.glob("runs/*/train_summary.json")):
|
| 56 |
t = json.loads(p.read_text())
|
scripts/pipeline.sh
CHANGED
|
@@ -30,6 +30,9 @@ if [ -n "${RUN_ID_FORCE:-}" ]; then echo "$RUN_ID_FORCE" > "$STATE/run_id"; fi
|
|
| 30 |
RUN_NAME="${RUN_NAME:-main}"; TRAIN_INIT="${TRAIN_INIT:-$BASELINE}"; EVAL_ALT="${EVAL_ALT:-1}"
|
| 31 |
case "$TRAIN_INIT" in /*) ;; *) TRAIN_INIT="$EMC_ROOT/$TRAIN_INIT" ;; esac
|
| 32 |
OUTRUN="$RUNS/$RUN_NAME"
|
|
|
|
|
|
|
|
|
|
| 33 |
if [ "$RUN_NAME" = main ]; then EVAL_PREFIX=eval_draft; else EVAL_PREFIX="eval_$RUN_NAME"; fi
|
| 34 |
|
| 35 |
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOGS/pipeline.log"; }
|
|
@@ -130,10 +133,8 @@ s_smoke_base() { SUB="$BASELINE" TAG=smoke_baseline kit eval --limit-per-domain
|
|
| 130 |
s_prompts() { "$PY" -m emcdraft.prompts --target "$TARGET" --kit "$KIT" --out "$DATA/prompts" --results "$RESULTS"; }
|
| 131 |
s_generate() { "$PY" -m emcdraft.gen_vllm --target "$TARGET" --prompts "$DATA/prompts" --out "$DATA/gen" --results "$RESULTS"; }
|
| 132 |
s_extract() { "$PY" -m emcdraft.extract --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --gen "$DATA/gen" --out "$DATA" --results "$RESULTS"; }
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
if [ ! -d "$TRAIN_INIT" ] && [ -n "${TRAIN_INIT_HF:-}" ]; then # e.g. on a fresh machine
|
| 136 |
-
"$PY" - "$TRAIN_INIT_HF" "$TRAIN_INIT" <<'PYEOF'
|
| 137 |
import shutil, sys
|
| 138 |
from pathlib import Path
|
| 139 |
from huggingface_hub import snapshot_download
|
|
@@ -141,12 +142,28 @@ repo, sub = sys.argv[1].split(":", 1)
|
|
| 141 |
src = Path(snapshot_download(repo, repo_type="dataset", allow_patterns=[sub + "/*"])) / sub
|
| 142 |
Path(sys.argv[2]).parent.mkdir(parents=True, exist_ok=True)
|
| 143 |
shutil.copytree(src, sys.argv[2])
|
| 144 |
-
print("
|
| 145 |
PYEOF
|
| 146 |
-
|
|
|
|
|
|
|
| 147 |
[ -d "$TRAIN_INIT" ] || { echo "starting weights $TRAIN_INIT not found"; return 1; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
rm -rf "$OUTRUN"
|
| 149 |
-
"$PY" -m emcdraft.train --target "$TARGET" --init "$TRAIN_INIT" --data "$DATA/train" --dev "$DATA/dev" --out "$OUTRUN" $qat
|
|
|
|
| 150 |
for s in "$OUTRUN"/sub_*; do SUB="$s" kit validate; done
|
| 151 |
}
|
| 152 |
primary() { if [ -d "$OUTRUN/sub_fp8" ]; then echo "$OUTRUN/sub_fp8"; else echo "$OUTRUN/sub_bf16"; fi; }
|
|
@@ -158,6 +175,21 @@ s_eval_alt() {
|
|
| 158 |
SUB="$OUTRUN/sub_bf16" TAG="${EVAL_PREFIX}_bf16" kit eval
|
| 159 |
}
|
| 160 |
s_report() { "$PY" "$REPO/scripts/collect.py"; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
log "pipeline start: run $(cat "$STATE/run_id"), code $(cat "$REPO/.commit" 2>/dev/null | cut -c1-12), training run $RUN_NAME"
|
| 163 |
# a vLLM server left behind by an interrupted run would still hold the GPU
|
|
@@ -175,6 +207,7 @@ if [ -n "$prompts_pid" ]; then wait "$prompts_pid"; fi
|
|
| 175 |
is_done prompts || { log "stopping: prompts failed"; exit 1; }
|
| 176 |
stage generate 1 s_generate
|
| 177 |
stage extract 1 s_extract
|
|
|
|
| 178 |
stage train 1 s_train
|
| 179 |
sync_hf --submissions
|
| 180 |
stage eval_main 0 s_eval_main || true
|
|
@@ -182,6 +215,14 @@ stage report_main 0 s_report || true
|
|
| 182 |
stage eval_baseline 0 s_eval_baseline || true
|
| 183 |
stage report_baseline 0 s_report || true
|
| 184 |
stage eval_alt 0 s_eval_alt || true
|
|
|
|
|
|
|
| 185 |
stage report 0 s_report || true
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
sync_hf --submissions
|
| 187 |
log "pipeline finished"
|
|
|
|
| 30 |
RUN_NAME="${RUN_NAME:-main}"; TRAIN_INIT="${TRAIN_INIT:-$BASELINE}"; EVAL_ALT="${EVAL_ALT:-1}"
|
| 31 |
case "$TRAIN_INIT" in /*) ;; *) TRAIN_INIT="$EMC_ROOT/$TRAIN_INIT" ;; esac
|
| 32 |
OUTRUN="$RUNS/$RUN_NAME"
|
| 33 |
+
# the previous best draft (kept unless the new one scores higher on this machine)
|
| 34 |
+
PREV_TAG="${PREV_TAG:-}"; PREV_SUB="${PREV_SUB:-}"
|
| 35 |
+
case "$PREV_SUB" in ""|/*) ;; *) PREV_SUB="$EMC_ROOT/$PREV_SUB" ;; esac
|
| 36 |
if [ "$RUN_NAME" = main ]; then EVAL_PREFIX=eval_draft; else EVAL_PREFIX="eval_$RUN_NAME"; fi
|
| 37 |
|
| 38 |
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOGS/pipeline.log"; }
|
|
|
|
| 133 |
s_prompts() { "$PY" -m emcdraft.prompts --target "$TARGET" --kit "$KIT" --out "$DATA/prompts" --results "$RESULTS"; }
|
| 134 |
s_generate() { "$PY" -m emcdraft.gen_vllm --target "$TARGET" --prompts "$DATA/prompts" --out "$DATA/gen" --results "$RESULTS"; }
|
| 135 |
s_extract() { "$PY" -m emcdraft.extract --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --gen "$DATA/gen" --out "$DATA" --results "$RESULTS"; }
|
| 136 |
+
fetch_hf() { # fetch_hf <dataset-repo>:<folder> <destination>: a draft folder from the dataset repo
|
| 137 |
+
"$PY" - "$1" "$2" <<'PYEOF'
|
|
|
|
|
|
|
| 138 |
import shutil, sys
|
| 139 |
from pathlib import Path
|
| 140 |
from huggingface_hub import snapshot_download
|
|
|
|
| 142 |
src = Path(snapshot_download(repo, repo_type="dataset", allow_patterns=[sub + "/*"])) / sub
|
| 143 |
Path(sys.argv[2]).parent.mkdir(parents=True, exist_ok=True)
|
| 144 |
shutil.copytree(src, sys.argv[2])
|
| 145 |
+
print("downloaded", sys.argv[1])
|
| 146 |
PYEOF
|
| 147 |
+
}
|
| 148 |
+
init_weights() { # starting weights for training (downloaded on a fresh machine)
|
| 149 |
+
if [ ! -d "$TRAIN_INIT" ] && [ -n "${TRAIN_INIT_HF:-}" ]; then fetch_hf "$TRAIN_INIT_HF" "$TRAIN_INIT"; fi
|
| 150 |
[ -d "$TRAIN_INIT" ] || { echo "starting weights $TRAIN_INIT not found"; return 1; }
|
| 151 |
+
}
|
| 152 |
+
s_ablate() { # short runs comparing training recipes; the best one is used by s_train
|
| 153 |
+
if [ "${ABLATE:-0}" != 1 ]; then echo "no recipe comparison requested (ABLATE=${ABLATE:-0})"; return 0; fi
|
| 154 |
+
local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"
|
| 155 |
+
init_weights
|
| 156 |
+
"$PY" -m emcdraft.ablate --target "$TARGET" --init "$TRAIN_INIT" --data "$DATA/train" --dev "$DATA/dev" \
|
| 157 |
+
--out "$RUNS/ablate" --results "$RESULTS" --state "$STATE" --steps "${ABLATE_STEPS:-300}" $qat
|
| 158 |
+
}
|
| 159 |
+
s_train() {
|
| 160 |
+
local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"
|
| 161 |
+
local extra=""; [ -f "$STATE/train_args" ] && extra=$(cat "$STATE/train_args")
|
| 162 |
+
echo "training recipe: ${extra:-defaults}"
|
| 163 |
+
init_weights
|
| 164 |
rm -rf "$OUTRUN"
|
| 165 |
+
"$PY" -m emcdraft.train --target "$TARGET" --init "$TRAIN_INIT" --data "$DATA/train" --dev "$DATA/dev" --out "$OUTRUN" $qat $extra
|
| 166 |
+
cat "$STATE/run_id" > "$OUTRUN/run_id" # which run the exported folders belong to (for uploads)
|
| 167 |
for s in "$OUTRUN"/sub_*; do SUB="$s" kit validate; done
|
| 168 |
}
|
| 169 |
primary() { if [ -d "$OUTRUN/sub_fp8" ]; then echo "$OUTRUN/sub_fp8"; else echo "$OUTRUN/sub_bf16"; fi; }
|
|
|
|
| 175 |
SUB="$OUTRUN/sub_bf16" TAG="${EVAL_PREFIX}_bf16" kit eval
|
| 176 |
}
|
| 177 |
s_report() { "$PY" "$REPO/scripts/collect.py"; }
|
| 178 |
+
new_tag() { echo "${EVAL_PREFIX}_$(basename "$(primary)" | sed 's/^sub_//')"; }
|
| 179 |
+
s_eval_prev() { # the previous best draft on this machine, when its result is not here yet
|
| 180 |
+
if [ -z "$PREV_TAG" ]; then echo "no previous draft to compare with"; return 0; fi
|
| 181 |
+
if [ -f "$RESULTS/$PREV_TAG.json" ]; then echo "previous draft already evaluated on this machine"; return 0; fi
|
| 182 |
+
if [ ! -d "$PREV_SUB" ] && [ -n "${PREV_SUB_HF:-}" ]; then fetch_hf "$PREV_SUB_HF" "$PREV_SUB"; fi
|
| 183 |
+
SUB="$PREV_SUB" TAG="$PREV_TAG" kit eval
|
| 184 |
+
}
|
| 185 |
+
s_choose() {
|
| 186 |
+
"$PY" "$REPO/scripts/choose.py" --new "$(new_tag)" --new-sub "$(primary)" --prev "$PREV_TAG" --prev-sub "$PREV_SUB" --results "$RESULTS" --state "$STATE"
|
| 187 |
+
}
|
| 188 |
+
bench() { env EMC_TARGET="$TARGET" EMC_SUB="${SUB:-}" EMC2_WORK="$WORK" "$PY" "$REPO/scripts/bench.py" "$@"; }
|
| 189 |
+
final_sub() { if [ -f "$STATE/final_sub" ]; then cat "$STATE/final_sub"; else primary; fi; }
|
| 190 |
+
s_bench_draft() { SUB="$(final_sub)" bench --tag draft --what batch,long,k; }
|
| 191 |
+
s_bench_baseline() { SUB="$BASELINE" bench --tag baseline --what batch,long; }
|
| 192 |
+
s_bench_target() { SUB="" bench --tag target_only --target-only --what batch,long; }
|
| 193 |
|
| 194 |
log "pipeline start: run $(cat "$STATE/run_id"), code $(cat "$REPO/.commit" 2>/dev/null | cut -c1-12), training run $RUN_NAME"
|
| 195 |
# a vLLM server left behind by an interrupted run would still hold the GPU
|
|
|
|
| 207 |
is_done prompts || { log "stopping: prompts failed"; exit 1; }
|
| 208 |
stage generate 1 s_generate
|
| 209 |
stage extract 1 s_extract
|
| 210 |
+
stage ablate 0 s_ablate || true
|
| 211 |
stage train 1 s_train
|
| 212 |
sync_hf --submissions
|
| 213 |
stage eval_main 0 s_eval_main || true
|
|
|
|
| 215 |
stage eval_baseline 0 s_eval_baseline || true
|
| 216 |
stage report_baseline 0 s_report || true
|
| 217 |
stage eval_alt 0 s_eval_alt || true
|
| 218 |
+
stage eval_prev 0 s_eval_prev || true
|
| 219 |
+
stage choose 0 s_choose || true
|
| 220 |
stage report 0 s_report || true
|
| 221 |
+
if [ "${BENCH:-0}" = 1 ]; then
|
| 222 |
+
stage bench_draft 0 s_bench_draft || true
|
| 223 |
+
stage bench_baseline 0 s_bench_baseline || true
|
| 224 |
+
stage bench_target 0 s_bench_target || true
|
| 225 |
+
stage report_bench 0 s_report || true
|
| 226 |
+
fi
|
| 227 |
sync_hf --submissions
|
| 228 |
log "pipeline finished"
|
scripts/sync.py
CHANGED
|
@@ -101,8 +101,13 @@ def main():
|
|
| 101 |
except Exception as e: # noqa: BLE001
|
| 102 |
print(f"could not list the repository: {e}")
|
| 103 |
for sub in subs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
name = f"{sub.parent.name}-{sub.name[4:]}"
|
| 105 |
-
dest = f"submissions/{
|
| 106 |
missing = [p.name for p in sub.iterdir() if p.is_file() and f"{dest}/{p.name}" not in have]
|
| 107 |
if "--submissions" in sys.argv or missing:
|
| 108 |
info = api.upload_folder(folder_path=str(sub), repo_id=REPO_ID, repo_type="dataset",
|
|
|
|
| 101 |
except Exception as e: # noqa: BLE001
|
| 102 |
print(f"could not list the repository: {e}")
|
| 103 |
for sub in subs:
|
| 104 |
+
# a training run records which run it belongs to; folders without that record
|
| 105 |
+
# (older runs, or starting weights fetched from the Hub) are not uploaded again
|
| 106 |
+
marker = sub.parent / "run_id"
|
| 107 |
+
if not marker.exists():
|
| 108 |
+
continue
|
| 109 |
name = f"{sub.parent.name}-{sub.name[4:]}"
|
| 110 |
+
dest = f"submissions/{marker.read_text().strip()}/{name}"
|
| 111 |
missing = [p.name for p in sub.iterdir() if p.is_file() and f"{dest}/{p.name}" not in have]
|
| 112 |
if "--submissions" in sys.argv or missing:
|
| 113 |
info = api.upload_folder(folder_path=str(sub), repo_id=REPO_ID, repo_type="dataset",
|
tests/test_head.py
CHANGED
|
@@ -246,6 +246,74 @@ def test_append():
|
|
| 246 |
print(" append: earlier answers and shards kept, new files only, same validation split")
|
| 247 |
|
| 248 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
if __name__ == "__main__":
|
| 250 |
head = MTPHead(C)
|
| 251 |
for p in head.parameters():
|
|
@@ -259,4 +327,5 @@ if __name__ == "__main__":
|
|
| 259 |
print("train/export"); test_train_and_export(head, E, W)
|
| 260 |
print("helpers"); test_helpers()
|
| 261 |
print("append"); test_append()
|
|
|
|
| 262 |
print("ALL OK")
|
|
|
|
| 246 |
print(" append: earlier answers and shards kept, new files only, same validation split")
|
| 247 |
|
| 248 |
|
| 249 |
+
def test_recipes(head, E, W):
|
| 250 |
+
"""The full training entry point with the new recipe options, the recipe comparison and
|
| 251 |
+
the keep-the-better-draft rule, end to end on a tiny fake target (CPU)."""
|
| 252 |
+
import subprocess
|
| 253 |
+
from emcdraft.head import save_safetensors_raw
|
| 254 |
+
from emcdraft.sim import save_shard
|
| 255 |
+
root = Path(__file__).resolve().parents[1]
|
| 256 |
+
env = dict(os.environ, PYTHONPATH=str(root), TRAIN_DATA_DEVICE="cpu")
|
| 257 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 258 |
+
tmp = Path(tmp)
|
| 259 |
+
tgt, init, data = tmp / "target", tmp / "init", tmp / "data"
|
| 260 |
+
tgt.mkdir()
|
| 261 |
+
(tgt / "config.json").write_text(json.dumps({"text_config": {
|
| 262 |
+
"hidden_size": C.hidden, "intermediate_size": C.inter, "num_attention_heads": C.heads,
|
| 263 |
+
"num_key_value_heads": C.kv_heads, "head_dim": C.head_dim, "partial_rotary_factor": C.rot_dim / C.head_dim,
|
| 264 |
+
"rope_theta": C.theta, "rms_norm_eps": C.eps, "max_position_embeddings": 262144,
|
| 265 |
+
"mtp_num_hidden_layers": 1}}))
|
| 266 |
+
names = {"lm_head.weight": W, "model.language_model.embed_tokens.weight": E}
|
| 267 |
+
save_safetensors_raw(tgt / "model.safetensors", {
|
| 268 |
+
n: ("BF16", t.shape, t.to(torch.bfloat16).contiguous().view(torch.int16).numpy().tobytes())
|
| 269 |
+
for n, t in names.items()})
|
| 270 |
+
(tgt / "model.safetensors.index.json").write_text(json.dumps({"weight_map": {n: "model.safetensors" for n in names}}))
|
| 271 |
+
head.set_fake_quant(False)
|
| 272 |
+
export_submission(head, init, tgt / "config.json", False, {"team_id": "t", "method_description": "m", "training_data": "d"})
|
| 273 |
+
g = torch.Generator().manual_seed(3)
|
| 274 |
+
for split, n in (("train", 20), ("dev", 4)):
|
| 275 |
+
seqs = [{"tokens": torch.randint(0, V, (16,), generator=g), "hidden": torch.randn(15, C.hidden, generator=g),
|
| 276 |
+
"P": 4, "domain": d, "id": f"{d}{i}"} for d in ("chat", "code", "math", "longform") for i in range(n)]
|
| 277 |
+
(data / split).mkdir(parents=True)
|
| 278 |
+
save_shard(str(data / split / ("g0000" if split == "train" else "all")), seqs)
|
| 279 |
+
common = ["--target", str(tgt), "--init", str(init), "--data", str(data / "train"), "--dev", str(data / "dev")]
|
| 280 |
+
run = lambda args: subprocess.run([sys.executable, "-m", *args], env=env, capture_output=True, text=True)
|
| 281 |
+
r = run(["emcdraft.train", *common, "--out", str(tmp / "full"), "--qat", "--step-w", "auto", "--topk", "5",
|
| 282 |
+
"--floor", "0.1", "--max-steps", "4", "--eval-every", "2", "--batch-tokens", "200"])
|
| 283 |
+
assert r.returncode == 0, r.stdout[-2000:] + r.stderr[-3000:]
|
| 284 |
+
s = json.loads((tmp / "full" / "train_summary.json").read_text())
|
| 285 |
+
meta = json.loads((tmp / "full" / "sub_fp8" / "metadata.json").read_text())
|
| 286 |
+
assert "acceptance-aware" in meta["method_description"] and "top-5" in meta["method_description"]
|
| 287 |
+
assert len(s["history"]) == 2 and (tmp / "full" / "sub_bf16" / "model.safetensors").exists()
|
| 288 |
+
assert "w [" in r.stdout, "auto step weights not reported"
|
| 289 |
+
r = run(["emcdraft.ablate", *common, "--out", str(tmp / "abl"), "--results", str(tmp / "res"),
|
| 290 |
+
"--state", str(tmp), "--qat", "--steps", "2"])
|
| 291 |
+
assert r.returncode == 0, r.stdout[-2000:] + r.stderr[-3000:]
|
| 292 |
+
ab = json.loads((tmp / "res" / "ablation.json").read_text())
|
| 293 |
+
assert set(ab["recipes"]) == {"control", "accw_topk", "accw_topk_mask", "accw_topk_lr2"}
|
| 294 |
+
assert (tmp / "train_args").read_text().split() == ab["recipes"][ab["chosen"]]["flags"]
|
| 295 |
+
assert not any((tmp / "abl" / n / "sub_fp8").exists() for n in ab["recipes"]), "ablation runs must not export"
|
| 296 |
+
# keep-the-better-draft rule
|
| 297 |
+
kit = os.environ.get("EMC2_HOME")
|
| 298 |
+
if kit:
|
| 299 |
+
res = tmp / "res"
|
| 300 |
+
m = lambda tau, tpot: {"acceptance_length": tau, "tpot_median_s": tpot, "memory_bytes": 607177728}
|
| 301 |
+
(res / "eval_baseline.json").write_text(json.dumps(dict(m(2.805, 0.01539), memory_bytes=916507648)))
|
| 302 |
+
(res / "eval_new.json").write_text(json.dumps(m(2.95, 0.0150)))
|
| 303 |
+
(res / "eval_old.json").write_text(json.dumps(m(2.90, 0.01524)))
|
| 304 |
+
ch = lambda new, old: subprocess.run([sys.executable, str(root / "scripts" / "choose.py"), "--new", new,
|
| 305 |
+
"--new-sub", str(tmp / "full" / "sub_fp8"), "--prev", old,
|
| 306 |
+
"--prev-sub", str(init), "--results", str(res), "--state", str(tmp)],
|
| 307 |
+
env=env, capture_output=True, text=True)
|
| 308 |
+
r = ch("eval_new", "eval_old")
|
| 309 |
+
assert r.returncode == 0 and json.loads((res / "choice.json").read_text())["kept"] == "new", r.stderr
|
| 310 |
+
assert (tmp / "final_sub").read_text().strip() == str(tmp / "full" / "sub_fp8")
|
| 311 |
+
r = ch("eval_old", "eval_new") # a worse new draft keeps the previous one
|
| 312 |
+
assert json.loads((res / "choice.json").read_text())["kept"] == "previous", r.stderr
|
| 313 |
+
assert (tmp / "final_sub").read_text().strip() == str(init)
|
| 314 |
+
print(" recipes: training options, recipe comparison and keep-the-better rule work end to end")
|
| 315 |
+
|
| 316 |
+
|
| 317 |
if __name__ == "__main__":
|
| 318 |
head = MTPHead(C)
|
| 319 |
for p in head.parameters():
|
|
|
|
| 327 |
print("train/export"); test_train_and_export(head, E, W)
|
| 328 |
print("helpers"); test_helpers()
|
| 329 |
print("append"); test_append()
|
| 330 |
+
print("recipes"); test_recipes(head, E, W)
|
| 331 |
print("ALL OK")
|