Run r4: A + B + C; code delivery from this repo
Browse filesFiles changed (13)
- control/reset.txt+1
- control/run.env+26-6
- emcdraft/eagle.pyAdded+198
- emcdraft/extract.py+87-6
- emcdraft/gen_vllm.py+15-1
- emcdraft/head.py+5-3
- emcdraft/sim.py+42-8
- emcdraft/target.py+27
- emcdraft/train.py+5-2
- scripts/launch.py+12-6
- scripts/pipeline.sh+42-4
- scripts/supervise.py+44
- tests/test_head.py+91
3 unmodified lines4563 unmodified linesr2 generate extract train eval_main report_main eval_alt reportr3 generate extract ablate train eval_main report_main eval_alt eval_prev choose report bench_draft bench_baseline bench_target report_benchr3m fetch_final bench_draft bench_baseline bench_target report_bench3 unmodified lines45673 unmodified linesr2 generate extract train eval_main report_main eval_alt reportr3 generate extract ablate train eval_main report_main eval_alt eval_prev choose report bench_draft bench_baseline bench_target report_benchr3m fetch_final bench_draft bench_baseline bench_target report_benchr4 fetch_gen generate extract eagle_eval train eval_main report_main eval_baseline report_baseline choose report
1234567# KEY=VALUE settings passed to scripts/pipeline.sh by scripts/supervise.py# measurements only (the machine of run r3 stopped during them): batch sizes, long contexts and# draft lengths for the r3 draft (fetched from the dataset repo), the baseline and the target aloneRUN_ID_FORCE=r3mBENCH_ONLY=1FINAL_SUB=models/final-fp8FINAL_SUB_HF=mudassiruddin21/EMC:submissions/r3/main3-fp8123456789101112131415161718192021222324252627# KEY=VALUE settings passed to scripts/pipeline.sh by scripts/supervise.py# run r4 = options A + B + C on a fresh machine:# A more data: r3's 6.1M generated tokens reused from the dataset repo, total 9.5M, features in FP8# B the new answers mostly long-form writing (the weakest domain, the largest share of eval tokens)# C an EAGLE-3 draft trained online from the same target forward passes, then evaluated# the MTP head is retrained from r3 with r3's winning recipe; r3 stays the submission unless beatenRUN_ID_FORCE=r4FP8_OK=1FETCH_GEN=mudassiruddin21/EMC:runs/r3/data/genGEN_TOKENS=9500000GEN_MINUTES=50GEN_APPEND=1GEN_SHARE=longform=0.6,chat=0.2,code=0.1,math=0.1EXTRACT_FP8=1EXTRACT_BATCH_TOKENS=8192EXTRACT_MINUTES=100EAGLE=1EAGLE_LR=3e-4EAGLE_FULL_MIN=2.8RUN_NAME=main4TRAIN_INIT=models/r3-bf16TRAIN_INIT_HF=mudassiruddin21/EMC:submissions/r3/main3-bf16TRAIN_ARGS=--step-w auto --topk 10 --floor 0.3 --rel-lr 1e-3 --lora 128TRAIN_EPOCHS=1.5TRAIN_MINUTES=55EVAL_ALT=0BENCH=0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""EAGLE-3 draft head in the layout of the engine's `LlamaForCausalLMEagle3`.
The draft reads three intermediate residual streams of the target (layers 2, 32 and 61 of 64,the engine's default), normalises each, fuses them with one linear layer, and runs a singledecoder layer whose attention sees [norm(embedding of the next token), norm(fused state)]. Ithas no embedding and no output layer of its own: the engine then shares the target's, so theycost nothing in the memory metric and the draft predicts over the full vocabulary.
Drafting in the engine (vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py): step 1takes combine_hidden_states(aux) at the target's positions; every later step takes the draft'sown pre-norm output, while the post-norm output goes to the shared LM head. Positions and thedraft KV cache follow the same rules as the MTP head, so `emcdraft.head.unroll` applies as is.
Trained online during feature extraction (`OnlineTrainer`), from the same target forwardpasses that produce the MTP features."""from __future__ import annotations
import jsonimport mathimport timefrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom types import SimpleNamespace
import torchimport torch.nn as nnimport torch.nn.functional as F
from .head import QLinear, rope, save_safetensors_raw
@dataclassclass EagleConfig: hidden: int = 5120 heads: int = 32 kv_heads: int = 8 head_dim: int = 128 inter: int = 6144 # keeps the bf16 weights inside the memory cap (see README) eps: float = 1e-6 theta: float = 1e6 aux_layers: tuple = (2, 32, 61) vocab: int = 248320 max_pos: int = 262144
class RMSNorm(nn.Module): """x * rsqrt(mean(x^2) + eps) * w, in fp32 (the engine's RMSNorm)."""
def __init__(self, dim: int, eps: float): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x): xf = x.float() return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight.float()).to(x.dtype)
class Eagle3Head(nn.Module): def __init__(self, c: EagleConfig): super().__init__() self.c = c H, n = c.hidden, len(c.aux_layers) self.fc_norm = nn.ModuleList([RMSNorm(H, c.eps) for _ in range(n)]) self.fc = QLinear(n * H, H) self.input_layernorm = RMSNorm(H, c.eps) self.hidden_norm = RMSNorm(H, c.eps) self.q_proj = QLinear(2 * H, c.heads * c.head_dim) self.k_proj = QLinear(2 * H, c.kv_heads * c.head_dim) self.v_proj = QLinear(2 * H, c.kv_heads * c.head_dim) self.o_proj = QLinear(c.heads * c.head_dim, H) self.post_attention_layernorm = RMSNorm(H, c.eps) self.gate_proj = QLinear(H, c.inter) self.up_proj = QLinear(H, c.inter) self.down_proj = QLinear(c.inter, H) self.norm = RMSNorm(H, c.eps) for m in self.modules(): if isinstance(m, QLinear): nn.init.normal_(m.weight, std=0.02)
def combine(self, aux): """[.., n*H] auxiliary states -> [.., H] (the engine's combine_hidden_states, fc_norm=True).""" H = self.c.hidden return self.fc(torch.cat([nm(ch) for nm, ch in zip(self.fc_norm, aux.split(H, -1))], -1))
def step(self, emb, hid, pos, mem=(), mask=None): """One drafting step. Returns (post-norm output for the LM head, (k, v), pre-norm output that the next step consumes).""" c = self.c B, N, _ = emb.shape x = torch.cat([self.input_layernorm(emb), self.hidden_norm(hid)], -1) q = self.q_proj(x).view(B, N, c.heads, c.head_dim) k = self.k_proj(x).view(B, N, c.kv_heads, c.head_dim) v = self.v_proj(x).view(B, N, c.kv_heads, c.head_dim) q = rope(q, pos, c.head_dim, c.theta).transpose(1, 2) k = rope(k, pos, c.head_dim, c.theta).transpose(1, 2) v = v.transpose(1, 2) keys = torch.cat([m[0] for m in mem] + [k], 2) vals = torch.cat([m[1] for m in mem] + [v], 2) rep = c.heads // c.kv_heads o = F.scaled_dot_product_attention(q, keys.repeat_interleave(rep, 1), vals.repeat_interleave(rep, 1), attn_mask=mask) r = self.o_proj(o.transpose(1, 2).reshape(B, N, c.heads * c.head_dim)) + hid h = self.post_attention_layernorm(r) pre = self.down_proj(F.silu(self.gate_proj(h)) * self.up_proj(h)) + r return self.norm(pre), (k, v), pre
def engine_names(head: Eagle3Head) -> dict: """Our parameter name -> checkpoint name read by the engine's Eagle3LlamaForCausalLM.""" out = {} for n, _ in head.named_parameters(): if n.startswith(("fc.", "fc_norm.", "norm.")): out[n] = n elif n.split(".")[0] in ("q_proj", "k_proj", "v_proj", "o_proj"): out[n] = "midlayer.self_attn." + n elif n.split(".")[0] in ("gate_proj", "up_proj", "down_proj"): out[n] = "midlayer.mlp." + n else: out[n] = "midlayer." + n return out
def engine_config(c: EagleConfig) -> dict: return { "architectures": ["LlamaForCausalLMEagle3"], "model_type": "llama", "hidden_size": c.hidden, "intermediate_size": c.inter, "num_attention_heads": c.heads, "num_key_value_heads": c.kv_heads, "head_dim": c.head_dim, "num_hidden_layers": 1, "hidden_act": "silu", "rms_norm_eps": c.eps, "max_position_embeddings": c.max_pos, "rope_theta": c.theta, "rope_parameters": {"rope_type": "default", "rope_theta": c.theta}, "attention_bias": False, "mlp_bias": False, "tie_word_embeddings": False, "vocab_size": c.vocab, "draft_vocab_size": c.vocab, "target_hidden_size": c.hidden, "fc_norm": True, "eagle_aux_hidden_state_layer_ids": list(c.aux_layers), "eagle_config": {"eagle_aux_hidden_state_layer_ids": list(c.aux_layers), "use_aux_hidden_state": True}, "torch_dtype": "bfloat16", }
@torch.no_grad()def export_eagle(head: Eagle3Head, out_dir, metadata: dict) -> dict: """Kit-format folder: config.json (the draft's own), model.safetensors (bf16), spec, metadata.""" out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) tensors, nbytes = {}, 0 for ours, name in engine_names(head).items(): t = head.state_dict()[ours].detach().float().to(torch.bfloat16).cpu().contiguous() tensors[name] = ("BF16", tuple(t.shape), t.view(torch.int16).numpy().tobytes()) nbytes += t.numel() * 2 save_safetensors_raw(out_dir / "model.safetensors", tensors) (out_dir / "config.json").write_text(json.dumps(engine_config(head.c), indent=2)) (out_dir / "spec.json").write_text(json.dumps({"method": "eagle3"})) (out_dir / "metadata.json").write_text(json.dumps(metadata, indent=2)) return {"weight_bytes": nbytes, "tensors": len(tensors), "params": sum(p.numel() for p in head.parameters())}
class OnlineTrainer: """Trains an Eagle3Head one batch at a time from target states computed elsewhere."""
def __init__(self, cfg: EagleConfig, device, total_steps: int, lr=3e-4, warmup=100, step_w=(1.0, 0.8, 0.64), topk=10, beta=0.5, floor=0.3, log=print): self.head = Eagle3Head(cfg).to(device) self.opt = torch.optim.AdamW(self.head.parameters(), lr=lr, betas=(0.9, 0.95), weight_decay=0.0) self.a = SimpleNamespace(beta=beta, floor=floor, step_w=list(step_w), topk=topk) self.total, self.warm, self.lr = max(1, total_steps), warmup, lr self.n, self.skipped, self.log, self.t0 = 0, 0, log, time.time() self.hist = []
def step(self, embed, W, tokens, aux, teacher, P, T): from .train import train_step f = (self.n + 1) / self.warm if self.n < self.warm else \ 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(1.0, (self.n - self.warm) / max(1, self.total - self.warm)))) for g in self.opt.param_groups: g["lr"] = self.lr * f try: self.head.train() loss, info = train_step(self.head, embed, W, (tokens, aux, P, T), self.a, teacher=teacher) self.opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(self.head.parameters(), 1.0) self.opt.step() except torch.OutOfMemoryError: self.opt.zero_grad(set_to_none=True) torch.cuda.empty_cache() self.skipped += 1 return None self.n += 1 if self.n % 25 == 0 or self.n == 1: est = 1 + info["acc1"] * (1 + info["acc2"] * (1 + info["acc3"])) self.log(f" eagle step {self.n}/{self.total} ce {info['ce1']:.3f}/{info['ce2']:.3f}/{info['ce3']:.3f} " f"acc {info['acc1']:.3f}/{info['acc2']:.3f}/{info['acc3']:.3f} batch-tau~{est:.3f} " f"lr x{f:.2f} ({(time.time() - self.t0) / self.n:.2f}s/step incl. target)") return info
def summary(self): return {"config": asdict(self.head.c), "steps": self.n, "skipped_oom": self.skipped, "lr": self.lr, "history": self.hist}43 unmodified lines44454647484950514 unmodified lines565758596061629 unmodified lines7273747576777879808135 unmodified lines11711811912012112210 unmodified lines1331341351361371383 unmodified lines14214314414514614714811 unmodified lines16016116216316416517 unmodified lines1831841851861871881891901911921931941953 unmodified lines19920020120220320443 unmodified linesreturn outdef featurize(tgt, seqs, max_tokens, agree):"""Teacher-forced hidden states for every sequence (kept on the GPU)."""feats = []queue = make_batches(seqs, max_tokens)while queue:4 unmodified linesx[r, :len(seqs[i]["ids"])] = torch.tensor(seqs[i]["ids"], device=tgt.device)try:h = tgt.hidden(x)except torch.OutOfMemoryError:torch.cuda.empty_cache()if len(b) == 1:raise9 unmodified linesagree[s["domain"]][1] += n - Pfeats.append({"tokens": x[r, :n].clone(), "hidden": hid, "P": P, "T": n,"domain": s["domain"], "id": s.get("id", "")})del h, xreturn featsdef shard_part(name: str) -> int:"""Training shards of the first extraction are g0000...; later appended parts p<k>g0000..."""return int(name[1:name.index("g")]) if name.startswith("p") else 135 unmodified linesap.add_argument("--minutes", type=float, default=float(os.environ.get("EXTRACT_MINUTES", 22)))ap.add_argument("--group", type=int, default=256, help="sequences per training shard")ap.add_argument("--seed", type=int, default=0)a = ap.parse_args()out, res = Path(a.out), Path(a.results)(out / "dev").mkdir(parents=True, exist_ok=True)10 unmodified linesreport["load_seconds"] = round(time.time() - t0, 1)report["hidden_state_call"] = tgt.modelog(f"target loaded in {report['load_seconds']}s (hidden states via '{tgt.mode}')")# 1. dev referenceskit = Path(a.kit) / "data/dev"3 unmodified lines"domain": p["domain"], "id": p["id"]} for p in dev]agree = defaultdict(lambda: [0, 0])t0 = time.time()feats = featurize(tgt, seqs, a.batch_tokens, agree)for d in DOMAINS:save_shard(str(out / "dev" / d), [f for f in feats if f["domain"] == d])report["dev_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}11 unmodified linesf"{base['acceptance_length']:.3f}; per domain "+ ", ".join(f"{d} {sim['acceptance_by_domain'][d]:.3f}/{base['acceptance_by_domain'][d]:.3f}" for d in DOMAINS)+ f"; step accuracies {[round(x, 3) for x in sim['step_accuracy']]}")(res / "extract_checks.json").write_text(json.dumps(report, indent=2))gap = abs(sim["acceptance_length"] - base["acceptance_length"])if gap > 0.25:17 unmodified linesdone = defaultdict(lambda: [0, 0])t0 = time.time()complete = Truefor g in range(0, len(gen), a.group):if time.time() - t0 > a.minutes * 60:log("time budget reached")complete = Falsebreakfeats = featurize(tgt, gen[g:g + a.group], a.batch_tokens, agree)save_shard(str(out / "train" / f"{prefix}{g // a.group:04d}"), feats)for f in feats:done[f["domain"]][0] += 1done[f["domain"]][1] += f["T"] - f["P"]3 unmodified linesreport["train_sequences"] = {d: {"sequences": v[0], "generated_tokens": v[1]} for d, v in done.items()}report["train_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}report["extract_seconds"] = round(time.time() - t0, 1)if complete: # a file cut off by the time budget is not marked, so it is not skipped later(out / "consumed_gen.json").write_text(json.dumps(sorted(consumed | {p.name for p in files})))(res / "extract_checks.json").write_text(json.dumps(report, indent=2))43 unmodified lines444546474849505152534 unmodified lines585960616263646566679 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111235 unmodified lines14814915015115215315415515615710 unmodified lines1681691701711721731741751761771781793 unmodified lines18318418518618718818919019119219319419519619719811 unmodified lines21021121221321421521621721821922022122222317 unmodified lines2412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732743 unmodified lines27827928028128228328428543 unmodified linesreturn outdef featurize(tgt, seqs, max_tokens, agree, on_batch=None):"""Teacher-forced hidden states for every sequence (kept on the GPU). With on_batch, it iscalled as on_batch(batch_indices, ids, final_hidden, aux) after every forward pass, aux beingthe captured auxiliary layers (Target.capture_aux) or None."""feats = []queue = make_batches(seqs, max_tokens)while queue:4 unmodified linesx[r, :len(seqs[i]["ids"])] = torch.tensor(seqs[i]["ids"], device=tgt.device)try:h = tgt.hidden(x)aux = tgt.take_aux() if getattr(tgt, "_aux_ids", None) else Noneexcept torch.OutOfMemoryError:if getattr(tgt, "_aux_ids", None):tgt._aux = {}torch.cuda.empty_cache()if len(b) == 1:raise9 unmodified linesagree[s["domain"]][1] += n - Pfeats.append({"tokens": x[r, :n].clone(), "hidden": hid, "P": P, "T": n,"domain": s["domain"], "id": s.get("id", "")})if on_batch is not None:on_batch(b, x, h, aux)del h, x, auxreturn featsdef finish_eagle(trainer, dev_eagle, embed, W, out_dir, res):"""Score the online-trained EAGLE-3 draft on the dev set and export it for the engine."""from .eagle import export_eagletrainer.head.eval()summary = trainer.summary()if dev_eagle:summary["dev"] = simulate(trainer.head, embed, W, dev_eagle)log(f"EAGLE-3 after {trainer.n} steps: simulated dev acceptance {summary['dev']['acceptance_length']:.4f} "f"{ {d: round(v, 3) for d, v in summary['dev']['acceptance_by_domain'].items()} } "f"steps {[round(x, 3) for x in summary['dev']['step_accuracy']]}")meta = {"team_id": os.environ.get("TEAM_ID", "mudassiruddin"),"method_description": ("EAGLE-3 draft (one decoder layer over three fused intermediate states of the ""target, shared embeddings and LM head) trained with a 3-step recursive ""drafting objective on the target's own outputs"),"training_data": ("Greedy answers of the target itself to public instruction prompts: GSM8K/Orca-Math, ""WritingPrompts, UltraChat/Alpaca/Dolly, Python instruction sets; dev prompts excluded")}out_dir.mkdir(parents=True, exist_ok=True)summary["export"] = export_eagle(trainer.head, out_dir / "sub_bf16", meta)torch.save(trainer.head.state_dict(), out_dir / "eagle_state.pt")(out_dir / "eagle_summary.json").write_text(json.dumps(summary, indent=2, default=str))(res / "eagle_summary.json").write_text(json.dumps(summary, indent=2, default=str))log(f"EAGLE-3 exported to {out_dir / 'sub_bf16'}: {summary['export']}")def shard_part(name: str) -> int:"""Training shards of the first extraction are g0000...; later appended parts p<k>g0000..."""return int(name[1:name.index("g")]) if name.startswith("p") else 135 unmodified linesap.add_argument("--minutes", type=float, default=float(os.environ.get("EXTRACT_MINUTES", 22)))ap.add_argument("--group", type=int, default=256, help="sequences per training shard")ap.add_argument("--seed", type=int, default=0)ap.add_argument("--fp8", action="store_true", default=os.environ.get("EXTRACT_FP8", "0") == "1",help="store training hidden states as FP8 with per-position scales (half the size)")ap.add_argument("--eagle-out", default=os.environ.get("EAGLE_OUT", ""),help="also train an EAGLE-3 draft online from the same forward passes; export it here")a = ap.parse_args()out, res = Path(a.out), Path(a.results)(out / "dev").mkdir(parents=True, exist_ok=True)10 unmodified linesreport["load_seconds"] = round(time.time() - t0, 1)report["hidden_state_call"] = tgt.modelog(f"target loaded in {report['load_seconds']}s (hidden states via '{tgt.mode}')")eagle_cfg = Noneif a.eagle_out:from .eagle import EagleConfigeagle_cfg = EagleConfig(hidden=tgt.W.shape[1], vocab=tgt.W.shape[0])tgt.capture_aux(eagle_cfg.aux_layers)log(f"EAGLE-3: capturing target layers {eagle_cfg.aux_layers} for online training")# 1. dev referenceskit = Path(a.kit) / "data/dev"3 unmodified lines"domain": p["domain"], "id": p["id"]} for p in dev]agree = defaultdict(lambda: [0, 0])t0 = time.time()dev_eagle = []def keep_dev_aux(b, x, h, aux):if aux is not None:for r, i in enumerate(b):n = len(seqs[i]["ids"])dev_eagle.append({"tokens": x[r, :n].cpu(), "hidden": aux[r, :n - 1].cpu(), "P": seqs[i]["P"],"T": n, "domain": seqs[i]["domain"], "id": seqs[i].get("id", "")})feats = featurize(tgt, seqs, a.batch_tokens, agree, on_batch=keep_dev_aux)for d in DOMAINS:save_shard(str(out / "dev" / d), [f for f in feats if f["domain"] == d])report["dev_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}11 unmodified linesf"{base['acceptance_length']:.3f}; per domain "+ ", ".join(f"{d} {sim['acceptance_by_domain'][d]:.3f}/{base['acceptance_by_domain'][d]:.3f}" for d in DOMAINS)+ f"; step accuracies {[round(x, 3) for x in sim['step_accuracy']]}")if a.fp8: # what FP8 storage of the inputs costs the baseline head, on the dev setfrom .sim import fp8_dequantize, fp8_quantizeq = [dict(f, hidden=fp8_dequantize(*fp8_quantize(f["hidden"]))) for f in feats]sim8 = simulate(head, lambda i: F.embedding(i, E), tgt.W, q)report["sim_baseline_dev_fp8_features"] = sim8log(f"FP8 feature storage: simulated baseline acceptance {sim8['acceptance_length']:.4f} "f"(bf16 features {sim['acceptance_length']:.4f})")del q(res / "extract_checks.json").write_text(json.dumps(report, indent=2))gap = abs(sim["acceptance_length"] - base["acceptance_length"])if gap > 0.25:17 unmodified linesdone = defaultdict(lambda: [0, 0])t0 = time.time()complete = Truetrainer, on_batch, embed = None, None, (lambda ids: F.embedding(ids, E))if eagle_cfg is not None:from .eagle import OnlineTrainersteps = sum(len(make_batches(gen[g:g + a.group], a.batch_tokens)) for g in range(0, len(gen), a.group))trainer = OnlineTrainer(eagle_cfg, tgt.device, steps, lr=float(os.environ.get("EAGLE_LR", 3e-4)), log=log)log(f"EAGLE-3: {sum(p.numel() for p in trainer.head.parameters()) / 1e6:.1f} M parameters, "f"{steps} training steps planned (one pass over the data)")def on_batch(b, x, h, aux, group):if aux is None:returnn = x.shape[1]lens = torch.tensor([len(group[i]["ids"]) for i in b], device=x.device)P = torch.tensor([group[i]["P"] for i in b], device=x.device)trainer.step(embed, tgt.W, x, aux[:, :n - 1], h[:, :n - 1], P, lens)if trainer.n and trainer.n % 300 == 0 and dev_eagle and (not trainer.hist or trainer.hist[-1]["step"] != trainer.n):r = simulate(trainer.head, embed, tgt.W, dev_eagle[::4])trainer.hist.append({"step": trainer.n, "dev_quarter_tau": r["acceptance_length"]})log(f" eagle step {trainer.n}: dev(1/4) tau {r['acceptance_length']:.4f}")for g in range(0, len(gen), a.group):if time.time() - t0 > a.minutes * 60:log("time budget reached")complete = Falsebreakgroup = gen[g:g + a.group]cb = (lambda b, x, h, aux, group=group: on_batch(b, x, h, aux, group)) if on_batch else Nonefeats = featurize(tgt, group, a.batch_tokens, agree, on_batch=cb)save_shard(str(out / "train" / f"{prefix}{g // a.group:04d}"), feats, fp8=a.fp8)for f in feats:done[f["domain"]][0] += 1done[f["domain"]][1] += f["T"] - f["P"]3 unmodified linesreport["train_sequences"] = {d: {"sequences": v[0], "generated_tokens": v[1]} for d, v in done.items()}report["train_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}report["extract_seconds"] = round(time.time() - t0, 1)if trainer is not None:finish_eagle(trainer, dev_eagle, embed, tgt.W, Path(a.eagle_out), res)if complete: # a file cut off by the time budget is not marked, so it is not skipped later(out / "consumed_gen.json").write_text(json.dumps(sorted(consumed | {p.name for p in files})))(res / "extract_checks.json").write_text(json.dumps(report, indent=2))
19 unmodified lines20212223242567 unmodified lines9394959697989910010110210319 unmodified linesfrom .prompts import DOMAINS, MAX_NEWSHARE = {"longform": 0.45, "chat": 0.22, "code": 0.15, "math": 0.18} # of generated tokensMEAN_LEN = {"chat": 383, "code": 270, "math": 309, "longform": 938} # dev reference meansSTOP_IDS = [248046, 248044]67 unmodified linestotal, suffix = 0, ""previous = totalitems = []for d in DOMAINS:pool = [json.loads(line)["ids"] for line in open(Path(a.prompts) / f"{d}.jsonl") if line.strip()]rng.shuffle(pool)want = math.ceil(1.1 * a.tokens * SHARE[d] / MEAN_LEN[d])new = [(d, ids) for ids in pool[:want] if tuple(ids) not in seen[d]]items += newlog(f"{d}: {len(new)} new prompts (pool {len(pool)}, {len(seen[d])} answered before)")19 unmodified lines20212223242526272829303132333435363767 unmodified lines10510610710810911011111211311411511611719 unmodified linesfrom .prompts import DOMAINS, MAX_NEWSHARE = {"longform": 0.45, "chat": 0.22, "code": 0.15, "math": 0.18} # of generated tokensdef share_from_env(text: str | None) -> dict:"""GEN_SHARE="longform=0.6,chat=0.2,code=0.1,math=0.1" overrides the domain mix."""share = dict(SHARE)for part in (text or "").split(","):if "=" in part:k, v = part.split("=", 1)if k.strip() in share:share[k.strip()] = float(v)total = sum(share.values())return {k: v / total for k, v in share.items()}MEAN_LEN = {"chat": 383, "code": 270, "math": 309, "longform": 938} # dev reference meansSTOP_IDS = [248046, 248044]67 unmodified linestotal, suffix = 0, ""previous = totalshare = share_from_env(os.environ.get("GEN_SHARE"))log(f"domain mix of the token budget: { {d: round(v, 3) for d, v in share.items()} }")items = []for d in DOMAINS:pool = [json.loads(line)["ids"] for line in open(Path(a.prompts) / f"{d}.jsonl") if line.strip()]rng.shuffle(pool)want = math.ceil(1.1 * a.tokens * share[d] / MEAN_LEN[d])new = [(d, ids) for ids in pool[:want] if tuple(ids) not in seen[d]]items += newlog(f"{d}: {len(new)} new prompts (pool {len(pool)}, {len(seen[d])} answered before)")
265 unmodified lines266267268269270271272273274275276277278265 unmodified linespos = base[None].expand(B, N)tri = torch.ones(N, N, dtype=torch.bool, device=dev).tril()eye = torch.eye(N, dtype=torch.bool, device=dev)mem, hid = [], hiddenfor k in range(1, K + 1):tok_k = tokens[:, (base + k).clamp(max=T - 1)]mask = torch.cat([tri] + [eye] * (k - 1), 1)[None, None]out, kv = head.step(embed(tok_k), hid, pos + (k - 1), mem, mask)mem.append(kv)hid = outyield k, out265 unmodified lines266267268269270271272273274275276277278279280265 unmodified linespos = base[None].expand(B, N)tri = torch.ones(N, N, dtype=torch.bool, device=dev).tril()eye = torch.eye(N, dtype=torch.bool, device=dev)# heads with their own input fusion (EAGLE-3: auxiliary target states -> fc) apply it firstmem, hid = [], (head.combine(hidden) if hasattr(head, "combine") else hidden)for k in range(1, K + 1):tok_k = tokens[:, (base + k).clamp(max=T - 1)]mask = torch.cat([tri] + [eye] * (k - 1), 1)[None, None]res = head.step(embed(tok_k), hid, pos + (k - 1), mem, mask)out, kv = res[0], res[1]mem.append(kv)hid = res[2] if len(res) > 2 else out # EAGLE-3 recurses on its pre-norm outputyield k, out
20 unmodified lines212223242526272829303132333435363738396 unmodified lines46474849505152535455565 unmodified lines62636465666768697071727374757620 unmodified linesDOMAINS = ("chat", "code", "math", "longform")def save_shard(stem: str, seqs: list[dict]):"""seqs: dicts with tokens [T] (long), hidden [T-1, H] (bf16), P, domain, optional id."""toks = torch.cat([s["tokens"] for s in seqs]).to(torch.int32).cpu().numpy()hid = torch.cat([s["hidden"] for s in seqs]).to(torch.bfloat16).cpu()np.save(stem + ".tok.npy", toks)np.save(stem + ".hid.npy", hid.view(torch.int16).numpy())meta = {"T": [int(s["tokens"].numel()) for s in seqs], "P": [int(s["P"]) for s in seqs],"domain": [s["domain"] for s in seqs], "id": [s.get("id", "") for s in seqs]}Path(stem + ".json").write_text(json.dumps(meta))def shards_bytes(data_dir) -> int:return sum(p.stat().st_size for p in Path(data_dir).glob("*.hid.npy"))def load_shards(data_dir, device, max_tokens: int | None = None) -> list[dict]:6 unmodified linespart = int(name[1:name.index("g")]) if name.startswith("p") else 1meta = json.loads(meta_path.read_text())tok = torch.from_numpy(np.load(stem + ".tok.npy").astype(np.int64)).to(device)hid = torch.from_numpy(np.load(stem + ".hid.npy")).view(torch.bfloat16).to(device)to = ho = 0for T, P, dom, sid in zip(meta["T"], meta["P"], meta["domain"], meta["id"]):seqs.append({"tokens": tok[to:to + T], "hidden": hid[ho:ho + T - 1], "P": P, "T": T,"domain": dom, "id": sid, "part": part})to, ho, total = to + T, ho + T - 1, total + Tif max_tokens and total >= max_tokens:break5 unmodified linesB, Tm = len(seqs), max(s["T"] for s in seqs)dev = seqs[0]["tokens"].deviceH = seqs[0]["hidden"].shape[-1]tokens = torch.full((B, Tm), pad, dtype=torch.long, device=dev)hidden = torch.zeros((B, Tm - 1, H), dtype=seqs[0]["hidden"].dtype, device=dev)for b, s in enumerate(seqs):tokens[b, :s["T"]] = s["tokens"]hidden[b, :s["T"] - 1] = s["hidden"]P = torch.tensor([s["P"] for s in seqs], device=dev)T = torch.tensor([s["T"] for s in seqs], device=dev)if device is not None and torch.device(device) != torch.device(dev):tokens, hidden, P, T = (x.to(device) for x in (tokens, hidden, P, T))return tokens, hidden, P, T20 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657586 unmodified lines656667686970717273747576777879808182835 unmodified lines899091929394959697989910010110210310410510610710810911020 unmodified linesDOMAINS = ("chat", "code", "math", "longform")def fp8_quantize(h: torch.Tensor):"""Per-row FP8 (E4M3) storage of hidden states: (uint8 codes, float32 row scales)."""hf = h.float()scale = (hf.abs().amax(-1, keepdim=True) / 448.0).clamp(min=1e-12)q = (hf / scale).to(torch.float8_e4m3fn)return q.view(torch.uint8), scale.squeeze(-1)def fp8_dequantize(codes: torch.Tensor, scale: torch.Tensor, dtype=torch.bfloat16) -> torch.Tensor:return (codes.view(torch.float8_e4m3fn).float() * scale.float()[..., None]).to(dtype)def save_shard(stem: str, seqs: list[dict], fp8: bool = False):"""seqs: dicts with tokens [T] (long), hidden [T-1, H] (bf16), P, domain, optional id.fp8=True stores the hidden states as E4M3 codes with one scale per position (half thebytes of bf16; about 2-3% relative error per value)."""toks = torch.cat([s["tokens"] for s in seqs]).to(torch.int32).cpu().numpy()hid = torch.cat([s["hidden"] for s in seqs]).to(torch.bfloat16)np.save(stem + ".tok.npy", toks)if fp8:codes, scale = fp8_quantize(hid)np.save(stem + ".hid8.npy", codes.cpu().numpy())np.save(stem + ".scale.npy", scale.cpu().numpy().astype(np.float32))else:np.save(stem + ".hid.npy", hid.cpu().view(torch.int16).numpy())meta = {"T": [int(s["tokens"].numel()) for s in seqs], "P": [int(s["P"]) for s in seqs],"domain": [s["domain"] for s in seqs], "id": [s.get("id", "") for s in seqs]}Path(stem + ".json").write_text(json.dumps(meta))def shards_bytes(data_dir) -> int:return sum(p.stat().st_size for pat in ("*.hid.npy", "*.hid8.npy") for p in Path(data_dir).glob(pat))def load_shards(data_dir, device, max_tokens: int | None = None) -> list[dict]:6 unmodified linespart = int(name[1:name.index("g")]) if name.startswith("p") else 1meta = json.loads(meta_path.read_text())tok = torch.from_numpy(np.load(stem + ".tok.npy").astype(np.int64)).to(device)scale = Noneif Path(stem + ".hid8.npy").exists(): # FP8 codes + per-position scaleshid = torch.from_numpy(np.load(stem + ".hid8.npy")).to(device)scale = torch.from_numpy(np.load(stem + ".scale.npy")).to(device)else:hid = torch.from_numpy(np.load(stem + ".hid.npy")).view(torch.bfloat16).to(device)to = ho = 0for T, P, dom, sid in zip(meta["T"], meta["P"], meta["domain"], meta["id"]):s = {"tokens": tok[to:to + T], "hidden": hid[ho:ho + T - 1], "P": P, "T": T,"domain": dom, "id": sid, "part": part}if scale is not None:s["scale"] = scale[ho:ho + T - 1]seqs.append(s)to, ho, total = to + T, ho + T - 1, total + Tif max_tokens and total >= max_tokens:break5 unmodified linesB, Tm = len(seqs), max(s["T"] for s in seqs)dev = seqs[0]["tokens"].deviceH = seqs[0]["hidden"].shape[-1]fp8 = "scale" in seqs[0]tokens = torch.full((B, Tm), pad, dtype=torch.long, device=dev)hidden = torch.zeros((B, Tm - 1, H), dtype=seqs[0]["hidden"].dtype, device=dev)scale = torch.zeros((B, Tm - 1), dtype=torch.float32, device=dev) if fp8 else Nonefor b, s in enumerate(seqs):tokens[b, :s["T"]] = s["tokens"]hidden[b, :s["T"] - 1] = s["hidden"]if fp8:scale[b, :s["T"] - 1] = s["scale"]P = torch.tensor([s["P"] for s in seqs], device=dev)T = torch.tensor([s["T"] for s in seqs], device=dev)if device is not None and torch.device(device) != torch.device(dev):tokens, hidden, P, T = (x.to(device) for x in (tokens, hidden, P, T))scale = scale.to(device) if fp8 else Noneif fp8: # move the compact codes, expand on arrivalhidden = fp8_dequantize(hidden, scale)return tokens, hidden, P, T
69 unmodified lines70717269 unmodified lines@torch.no_grad()def hidden(self, ids: torch.Tensor) -> torch.Tensor:return self._forward(ids, self.mode)69 unmodified lines70717273747576777879808182838485868788899091929394959697989969 unmodified lines@torch.no_grad()def hidden(self, ids: torch.Tensor) -> torch.Tensor:return self._forward(ids, self.mode)def decoder_layers(self):"""The language model's decoder layers (a ModuleList as long as num_hidden_layers)."""cfg = getattr(self.model.config, "text_config", None) or self.model.confign = cfg.num_hidden_layersfound = [m for name, m in self.model.named_modules()if isinstance(m, torch.nn.ModuleList) and len(m) == n and name.endswith("layers")]if not found:raise RuntimeError("decoder layers not found")return found[0]def capture_aux(self, layer_ids):"""Record the residual stream after `layer_ids` layers (the engine's EAGLE-3 auxiliarystates: index i = after i decoder layers) on every forward pass; read with take_aux()."""self._aux_ids = tuple(layer_ids)self._aux = {}layers = self.decoder_layers()for i in self._aux_ids:def hook(_mod, _inp, out, i=i):self._aux[i] = (out[0] if isinstance(out, (tuple, list)) else out).detach()layers[i - 1].register_forward_hook(hook)def take_aux(self) -> torch.Tensor:"""[B, L, len(layer_ids) * H] from the last forward pass, in layer order."""out = torch.cat([self._aux[i] for i in self._aux_ids], -1)self._aux = {}return out
66 unmodified lines67686970717273747 unmodified lines8283848586878866 unmodified linesreturn surrogate, ce_sum / float(denom), correctdef train_step(head, embed, W, batch, a, K=3):tokens, hidden, P, T = batchB, Tm = tokens.shapeN = Tm - 1base = torch.arange(N, device=tokens.device)[None]7 unmodified linesw = valid.float() if prev is None else valid.float() * (a.floor + (1 - a.floor) * prev.float())bi, ni = valid.nonzero(as_tuple=True)# the target's own distribution for the same token: h_{i+k} predicts x_{i+k+1}teach = hidden[bi, (ni + k).clamp(max=N - 1)] if a.beta > 0 else Nones_k, ce_k, corr = head_loss(out[bi, ni], W, labels[bi, ni], w[bi, ni], teach, a.beta,topk=getattr(a, "topk", 0))total = total + getattr(a, "step_w_cur", a.step_w)[k - 1] * s_k66 unmodified lines67686970717273747576777 unmodified lines8586878889909166 unmodified linesreturn surrogate, ce_sum / float(denom), correctdef train_step(head, embed, W, batch, a, K=3, teacher=None):"""`teacher`: the target's final hidden states for the soft targets when `hidden` is notthem (EAGLE-3 consumes auxiliary layers instead)."""tokens, hidden, P, T = batchsrc = hidden if teacher is None else teacherB, Tm = tokens.shapeN = Tm - 1base = torch.arange(N, device=tokens.device)[None]7 unmodified linesw = valid.float() if prev is None else valid.float() * (a.floor + (1 - a.floor) * prev.float())bi, ni = valid.nonzero(as_tuple=True)# the target's own distribution for the same token: h_{i+k} predicts x_{i+k+1}teach = src[bi, (ni + k).clamp(max=N - 1)] if a.beta > 0 else Nones_k, ce_k, corr = head_loss(out[bi, ni], W, labels[bi, ni], w[bi, ni], teach, a.beta,topk=getattr(a, "topk", 0))total = total + getattr(a, "step_w_cur", a.step_w)[k - 1] * s_k
111 unmodified lines112113114115116117118119120121122123124111 unmodified lines(root / ".scrub").write_text(os.environ["EMC_SCRUB"])if not alive(root / "supervisor.pid"):uv = get_uv(root)req = urllib.request.Request(f"https://github.com/{SOURCE}.git/info/refs?service=git-upload-pack",headers={"User-Agent": "git/2.45.0"})sha = re.search(r"([0-9a-f]{40}) refs/heads/main", urllib.request.urlopen(req, timeout=30).read().decode("latin-1")).group(1)sup = root / "supervise.py"sup.write_bytes(urllib.request.urlopen(f"https://raw.githubusercontent.com/{SOURCE}/{sha}/scripts/supervise.py", timeout=60).read())env = {k: v for k, v in os.environ.items() if k != "HF_TOKEN"}env.update(EMC_ROOT=str(root), UV=uv, RUN_ID=os.environ.get("RUN_ID", "r1"))with open(root / "logs" / "supervisor.log", "a") as out:111 unmodified lines112113114115116117118119120121122123124125126127128129130111 unmodified lines(root / ".scrub").write_text(os.environ["EMC_SCRUB"])if not alive(root / "supervisor.pid"):uv = get_uv(root)sup = root / "supervise.py"if os.environ.get("EMC_CODE") == "hf": # private repositories: code from the HF dataset reporepo = os.environ.get("HF_REPO", "mudassiruddin21/EMC")req = urllib.request.Request(f"https://huggingface.co/datasets/{repo}/resolve/main/scripts/supervise.py",headers={"Authorization": f"Bearer {(root / '.hf_token').read_text().strip()}"})sup.write_bytes(urllib.request.urlopen(req, timeout=60).read())else:req = urllib.request.Request(f"https://github.com/{SOURCE}.git/info/refs?service=git-upload-pack",headers={"User-Agent": "git/2.45.0"})sha = re.search(r"([0-9a-f]{40}) refs/heads/main", urllib.request.urlopen(req, timeout=30).read().decode("latin-1")).group(1)sup.write_bytes(urllib.request.urlopen(f"https://raw.githubusercontent.com/{SOURCE}/{sha}/scripts/supervise.py", timeout=60).read())env = {k: v for k, v in os.environ.items() if k != "HF_TOKEN"}env.update(EMC_ROOT=str(root), UV=uv, RUN_ID=os.environ.get("RUN_ID", "r1"))with open(root / "logs" / "supervisor.log", "a") as out:
23 unmodified lines242526272829101 unmodified lines13113213313413513613713819 unmodified lines15815916016116216316445 unmodified lines21021121221321421521621721821922022122222316 unmodified lines24024124224324424524624724824925025123 unmodified linesexport TORCHINDUCTOR_CACHE_DIR="$WORK/cache/inductor" TRITON_CACHE_DIR="$WORK/cache/triton"# greedy decoding only: use the built-in sampler instead of compiling FlashInfer kernels at start-upexport VLLM_USE_FLASHINFER_SAMPLER=0[ -f "$STATE/run_id" ] || echo "${RUN_ID:-$(date +%Y%m%d-%H%M)}" > "$STATE/run_id"if [ -n "${RUN_ID_FORCE:-}" ]; then echo "$RUN_ID_FORCE" > "$STATE/run_id"; fi # e.g. a new run on a fresh machine# training run name (runs/<name>), its starting weights and whether to also evaluate the bf16 variant101 unmodified lines}s_smoke_base() { SUB="$BASELINE" TAG=smoke_baseline kit eval --limit-per-domain 2; }s_prompts() { "$PY" -m emcdraft.prompts --target "$TARGET" --kit "$KIT" --out "$DATA/prompts" --results "$RESULTS"; }s_generate() { "$PY" -m emcdraft.gen_vllm --target "$TARGET" --prompts "$DATA/prompts" --out "$DATA/gen" --results "$RESULTS"; }s_extract() { "$PY" -m emcdraft.extract --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --gen "$DATA/gen" --out "$DATA" --results "$RESULTS"; }fetch_hf() { # fetch_hf <dataset-repo>:<folder> <destination>: a draft folder from the dataset repo"$PY" - "$1" "$2" <<'PYEOF'import shutil, sys19 unmodified lines}s_train() {local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"local extra=""; [ -f "$STATE/train_args" ] && extra=$(cat "$STATE/train_args")echo "training recipe: ${extra:-defaults}"init_weightsrm -rf "$OUTRUN"45 unmodified linesshards_ok() { # every shard listed by its metadata file is present and non-emptylocal d=$1 jhas_files "$d/*.json" || return 1for j in "$d"/*.json; do [ -s "${j%.json}.tok.npy" ] && [ -s "${j%.json}.hid.npy" ] || return 1; done}check_done env "$PY" -c "import vllm, torch, transformers"check_done download "$PY" -c "import json, os, sys; d = '$TARGET'; f = set(json.load(open(d + '/model.safetensors.index.json'))['weight_map'].values()); sys.exit(0 if os.path.isfile('$KIT/contract.json') and all(os.path.getsize(os.path.join(d, x)) > 0 for x in f) else 1)"check_done baseline test -s "$BASELINE/model.safetensors"check_done probe test -s "$PROBE/model.safetensors"check_done prompts has_files "$DATA/prompts/*.jsonl"check_done smoke_fp8 test -s "$RESULTS/smoke_fp8.json"check_done generate has_files "$DATA/gen/*.jsonl"check_done extract shards_ok "$DATA/train"check_done extract shards_ok "$DATA/dev"16 unmodified linesif ! is_done prompts; then (stage prompts 1 s_prompts) & prompts_pid=$!; fistage checkenv 0 s_checkenv || truestage probe 0 s_probe || trueif is_done probe; then stage smoke_fp8 0 s_smoke_fp8 || true; fiif ! is_done smoke_fp8; then stage smoke_base 1 s_smoke_base; fi # engine itself must workif [ -n "$prompts_pid" ]; then wait "$prompts_pid"; fiis_done prompts || { log "stopping: prompts failed"; exit 1; }stage generate 1 s_generatestage extract 1 s_extractstage ablate 0 s_ablate || truestage train 1 s_trainsync_hf --submissions23 unmodified lines242526272829303132101 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917019 unmodified lines19019119219319419519645 unmodified lines24224324424524624724824925025125225325425525616 unmodified lines27327427527627727827928028128228328428528628728828923 unmodified linesexport TORCHINDUCTOR_CACHE_DIR="$WORK/cache/inductor" TRITON_CACHE_DIR="$WORK/cache/triton"# greedy decoding only: use the built-in sampler instead of compiling FlashInfer kernels at start-upexport VLLM_USE_FLASHINFER_SAMPLER=0# downloads from a private dataset repo (earlier answers, starting weights) need the tokenif [ -z "${HF_TOKEN:-}" ] && [ -s "$EMC_ROOT/.hf_token" ]; then HF_TOKEN="$(cat "$EMC_ROOT/.hf_token")"; export HF_TOKEN; fiexport PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"[ -f "$STATE/run_id" ] || echo "${RUN_ID:-$(date +%Y%m%d-%H%M)}" > "$STATE/run_id"if [ -n "${RUN_ID_FORCE:-}" ]; then echo "$RUN_ID_FORCE" > "$STATE/run_id"; fi # e.g. a new run on a fresh machine# training run name (runs/<name>), its starting weights and whether to also evaluate the bf16 variant101 unmodified lines}s_smoke_base() { SUB="$BASELINE" TAG=smoke_baseline kit eval --limit-per-domain 2; }s_prompts() { "$PY" -m emcdraft.prompts --target "$TARGET" --kit "$KIT" --out "$DATA/prompts" --results "$RESULTS"; }s_fetch_gen() { # FETCH_GEN=<dataset-repo>:<folder>: answers generated in an earlier run, reused hereif [ -z "${FETCH_GEN:-}" ]; then echo "nothing to fetch"; return 0; fimkdir -p "$DATA/gen""$PY" - "$FETCH_GEN" "$DATA/gen" <<'PYEOF'import shutil, sysfrom pathlib import Pathfrom huggingface_hub import snapshot_downloadrepo, sub = sys.argv[1].split(":", 1)src = Path(snapshot_download(repo, repo_type="dataset", allow_patterns=[sub + "/*.jsonl"])) / subn = 0for f in sorted(src.glob("*.jsonl")):shutil.copyfile(f, Path(sys.argv[2]) / f.name)n += sum(len(__import__("json").loads(line)["o"]) for line in open(f) if line.strip())print(f"fetched {sys.argv[1]}: {n} generated tokens")PYEOF}s_generate() { "$PY" -m emcdraft.gen_vllm --target "$TARGET" --prompts "$DATA/prompts" --out "$DATA/gen" --results "$RESULTS"; }s_extract() {local eagle=""; [ "${EAGLE:-0}" = 1 ] && eagle="--eagle-out $RUNS/eagle""$PY" -m emcdraft.extract --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --gen "$DATA/gen" --out "$DATA" --results "$RESULTS" $eagleif [ -d "$RUNS/eagle/sub_bf16" ]; then cat "$STATE/run_id" > "$RUNS/eagle/run_id"; SUB="$RUNS/eagle/sub_bf16" kit validate; fi}s_eagle_eval() { # the EAGLE-3 draft through the official eval: a quick check first, the full set if promisingif [ ! -d "$RUNS/eagle/sub_bf16" ]; then echo "no EAGLE-3 draft"; return 0; fiSUB="$RUNS/eagle/sub_bf16" TAG=eagle_smoke kit eval --limit-per-domain 4if "$PY" -c "import json, sys; m = json.load(open('$RESULTS/eagle_smoke.json')); sys.exit(0 if m['acceptance_length'] >= float('${EAGLE_FULL_MIN:-2.8}') else 1)"; thenSUB="$RUNS/eagle/sub_bf16" TAG=eval_eagle3 kit evalelseecho "EAGLE-3 acceptance below ${EAGLE_FULL_MIN:-2.8} on the quick check: full evaluation skipped"fi}fetch_hf() { # fetch_hf <dataset-repo>:<folder> <destination>: a draft folder from the dataset repo"$PY" - "$1" "$2" <<'PYEOF'import shutil, sys19 unmodified lines}s_train() {local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"local extra="${TRAIN_ARGS:-}"; [ -z "$extra" ] && [ -f "$STATE/train_args" ] && extra=$(cat "$STATE/train_args")echo "training recipe: ${extra:-defaults}"init_weightsrm -rf "$OUTRUN"45 unmodified linesshards_ok() { # every shard listed by its metadata file is present and non-emptylocal d=$1 jhas_files "$d/*.json" || return 1for j in "$d"/*.json; do [ -s "${j%.json}.tok.npy" ] && { [ -s "${j%.json}.hid.npy" ] || [ -s "${j%.json}.hid8.npy" ]; } || return 1; done}check_done env "$PY" -c "import vllm, torch, transformers"check_done download "$PY" -c "import json, os, sys; d = '$TARGET'; f = set(json.load(open(d + '/model.safetensors.index.json'))['weight_map'].values()); sys.exit(0 if os.path.isfile('$KIT/contract.json') and all(os.path.getsize(os.path.join(d, x)) > 0 for x in f) else 1)"check_done baseline test -s "$BASELINE/model.safetensors"check_done probe test -s "$PROBE/model.safetensors"check_done prompts has_files "$DATA/prompts/*.jsonl"[ "${FP8_OK:-0}" = 1 ] || check_done smoke_fp8 test -s "$RESULTS/smoke_fp8.json"check_done fetch_gen has_files "$DATA/gen/*.jsonl"check_done generate has_files "$DATA/gen/*.jsonl"check_done extract shards_ok "$DATA/train"check_done extract shards_ok "$DATA/dev"16 unmodified linesif ! is_done prompts; then (stage prompts 1 s_prompts) & prompts_pid=$!; fistage checkenv 0 s_checkenv || truestage probe 0 s_probe || trueif [ "${FP8_OK:-0}" = 1 ] && ! is_done smoke_fp8; then # FP8 loading already verified in earlier runsecho "1.0" > "$STATE/fp8_ok"; echo 0 > "$STATE/smoke_fp8.done"; log "skip smoke_fp8 (FP8_OK=1)"fiif is_done probe; then stage smoke_fp8 0 s_smoke_fp8 || true; fiif ! is_done smoke_fp8; then stage smoke_base 1 s_smoke_base; fi # engine itself must workif [ -n "$prompts_pid" ]; then wait "$prompts_pid"; fiis_done prompts || { log "stopping: prompts failed"; exit 1; }stage fetch_gen 1 s_fetch_genstage generate 1 s_generatestage extract 1 s_extractstage eagle_eval 0 s_eagle_eval || truestage ablate 0 s_ablate || truestage train 1 s_trainsync_hf --submissions
11 unmodified lines121314151617189 unmodified lines2829303132336 unmodified lines4041424344454611 unmodified lines58596061626311 unmodified linesWhile the pipeline runs, logs are pushed every 10 minutes. Create $EMC_ROOT/STOP to end it."""import ioimport osimport reimport shutil9 unmodified linesBRANCH = os.environ.get("EMC_BRANCH", "main")UV = os.environ.get("UV", "uv")LOGS, STATE, CODE = ROOT / "logs", ROOT / "state", ROOT / "code"VENV_PY = ROOT / "venv" / "bin" / "python"6 unmodified linesUV_LINK_MODE="copy", TMPDIR=str(ROOT / "tmp"), HF_HOME=str(ROOT / "hf"))def remote_sha():req = urllib.request.Request(f"https://github.com/{SOURCE}.git/info/refs?service=git-upload-pack",headers={"User-Agent": "git/2.45.0"})body = urllib.request.urlopen(req, timeout=30).read().decode("latin-1")11 unmodified linesdest = CODE / sha[:12]if dest.exists() and not complete(dest):shutil.rmtree(dest, ignore_errors=True)if not dest.exists():data = urllib.request.urlopen(f"https://codeload.github.com/{SOURCE}/tar.gz/{sha}", timeout=300).read()tmp = CODE / f".{sha[:12]}.tmp"11 unmodified lines1213141516171819209 unmodified lines30313233343536373839406 unmodified lines4748495051525354555657585960616263646566676869707172737475767778798011 unmodified lines929394959697989910010110210310410510610711 unmodified linesWhile the pipeline runs, logs are pushed every 10 minutes. Create $EMC_ROOT/STOP to end it."""import hashlibimport ioimport jsonimport osimport reimport shutil9 unmodified linesBRANCH = os.environ.get("EMC_BRANCH", "main")UV = os.environ.get("UV", "uv")LOGS, STATE, CODE = ROOT / "logs", ROOT / "state", ROOT / "code"# EMC_CODE=hf: take the code from the (private) Hugging Face dataset repo instead of GitHubCODE_SRC = os.environ.get("EMC_CODE", "github")HF_REPO = os.environ.get("HF_REPO", "mudassiruddin21/EMC")CODE_DIRS = ("emcdraft", "scripts", "control", "tests")_hf = {"commit": None, "files": []}VENV_PY = ROOT / "venv" / "bin" / "python"6 unmodified linesUV_LINK_MODE="copy", TMPDIR=str(ROOT / "tmp"), HF_HOME=str(ROOT / "hf"))def hf_token():p = ROOT / ".hf_token"return p.read_text().strip() if p.exists() else os.environ.get("HF_TOKEN", "")def hf_get(path):req = urllib.request.Request(f"https://huggingface.co/{path}",headers={"Authorization": f"Bearer {hf_token()}", "User-Agent": "emc-supervisor"})return urllib.request.urlopen(req, timeout=120).read()def hf_code_version():"""A fingerprint of the code files only (the same repo also receives the run's logs, whoseuploads must not count as code changes), plus the commit to download them from."""commit = json.loads(hf_get(f"api/datasets/{HF_REPO}/revision/main"))["sha"]files = []for d in CODE_DIRS:for e in json.loads(hf_get(f"api/datasets/{HF_REPO}/tree/{commit}/{d}?recursive=true")):if e.get("type") == "file":files.append((e["path"], e["oid"]))files.sort()_hf.update(commit=commit, files=files)return hashlib.sha1("\n".join(f"{p} {o}" for p, o in files).encode()).hexdigest()def remote_sha():if CODE_SRC == "hf":return hf_code_version()req = urllib.request.Request(f"https://github.com/{SOURCE}.git/info/refs?service=git-upload-pack",headers={"User-Agent": "git/2.45.0"})body = urllib.request.urlopen(req, timeout=30).read().decode("latin-1")11 unmodified linesdest = CODE / sha[:12]if dest.exists() and not complete(dest):shutil.rmtree(dest, ignore_errors=True)if not dest.exists() and CODE_SRC == "hf":tmp = CODE / f".{sha[:12]}.tmp"shutil.rmtree(tmp, ignore_errors=True)tmp.mkdir(parents=True)for path, _ in _hf["files"]:f = tmp / pathf.parent.mkdir(parents=True, exist_ok=True)f.write_bytes(hf_get(f"datasets/{HF_REPO}/resolve/{_hf['commit']}/{path}"))(tmp / ".commit").write_text(sha + "\n")tmp.rename(dest)if not dest.exists():data = urllib.request.urlopen(f"https://codeload.github.com/{SOURCE}/tar.gz/{sha}", timeout=300).read()tmp = CODE / f".{sha[:12]}.tmp"
321 unmodified lines3223233243253263278 unmodified lines336337338339321 unmodified linesprint(" recipes: training options, recipe comparison and keep-the-better rule work end to end")if __name__ == "__main__":head = MTPHead(C)for p in head.parameters():8 unmodified linesprint("helpers"); test_helpers()print("append"); test_append()print("recipes"); test_recipes(head, E, W)print("ALL OK")321 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164178 unmodified lines426427428429430321 unmodified linesprint(" recipes: training options, recipe comparison and keep-the-better rule work end to end")def test_eagle(E, W):"""EAGLE-3 head: the batched unroll equals a literal emulation of the engine's drafting loop(fused auxiliary states for step 1, pre-norm recursion afterwards); online training learns;the export has exactly the names the engine's loader maps and passes the kit's validate;the full-size draft stays inside the memory cap."""from emcdraft.eagle import EagleConfig, Eagle3Head, OnlineTrainer, engine_config, export_eaglefrom emcdraft.sim import collate, fp8_dequantize, fp8_quantize, load_shards, save_shardtorch.manual_seed(1)cfg = EagleConfig(hidden=C.hidden, heads=4, kv_heads=2, head_dim=12, inter=64, aux_layers=(1, 2, 3), vocab=V)head = Eagle3Head(cfg)T = 12tokens = torch.randint(0, V, (T,))aux = torch.randn(T - 1, 3 * C.hidden)with torch.no_grad():par = [o for _, o in unroll(head, lambda ids: E[ids], tokens[None], aux[None], 3)]worst = 0.0for i in range(T - 1):pos = torch.arange(i + 1)[None]tri = torch.ones(i + 1, i + 1, dtype=torch.bool).tril()[None, None]out, (ck, cv), pre = head.step(E[tokens[1:i + 2]][None], head.combine(aux[None, :i + 1]), pos, (), tri)outs, h = [out[0, -1]], pre[:, -1:]for k in range(2, 4):if i + k > T - 1:breako, kv, pre = head.step(E[tokens[i + k]][None, None], h, torch.tensor([[i + k - 1]]), [(ck, cv)],torch.ones(1, 1, 1, ck.shape[2] + 1, dtype=torch.bool))ck, cv = torch.cat([ck, kv[0]], 2), torch.cat([cv, kv[1]], 2)outs.append(o[0, 0])h = prefor k, o in enumerate(outs):worst = max(worst, float((par[k][0, i] - o).abs().max()))assert worst < 1e-4, worstprint(f" eagle unroll == step-by-step emulation with pre-norm recursion (max abs diff {worst:.2e})")tr = OnlineTrainer(cfg, "cpu", total_steps=40, lr=3e-3, warmup=5)toks = torch.randint(0, V, (4, 16))ax, teach = torch.randn(4, 15, 3 * C.hidden), torch.randn(4, 15, C.hidden)P, L = torch.tensor([3, 3, 4, 5]), torch.tensor([16, 14, 16, 12])first = tr.step(lambda ids: F.embedding(ids, E), W, toks, ax, teach, P, L)["ce1"]for _ in range(25):last = tr.step(lambda ids: F.embedding(ids, E), W, toks, ax, teach, P, L)["ce1"]assert last < first, (first, last)print(f" eagle online training: ce1 {first:.3f} -> {last:.3f}")with tempfile.TemporaryDirectory() as tmp:info = export_eagle(tr.head, Path(tmp) / "eagle", {"team_id": "t", "method_description": "m", "training_data": "d"})from emcdraft.head import read_safetensorsnames = set(read_safetensors(Path(tmp) / "eagle" / "model.safetensors"))want = {"fc.weight", "fc_norm.0.weight", "fc_norm.1.weight", "fc_norm.2.weight", "norm.weight","midlayer.input_layernorm.weight", "midlayer.hidden_norm.weight", "midlayer.post_attention_layernorm.weight",*(f"midlayer.self_attn.{x}_proj.weight" for x in "qkvo"),*(f"midlayer.mlp.{x}_proj.weight" for x in ("gate", "up", "down"))}assert names == want, names ^ wantcfgj = json.loads((Path(tmp) / "eagle" / "config.json").read_text())assert cfgj["architectures"] == ["LlamaForCausalLMEagle3"] and cfgj["fc_norm"] is Trueassert json.loads((Path(tmp) / "eagle" / "spec.json").read_text()) == {"method": "eagle3"}kit = os.environ.get("EMC2_HOME")if kit:sys.path.insert(0, kit)from emc2 import submissionerrors, kinfo = submission.check(Path(tmp) / "eagle", json.loads((Path(kit) / "contract.json").read_text()),json.loads((Path(kit) / "target.json").read_text()))assert not errors, errorsassert kinfo["weight_bytes"] == info["weight_bytes"]# FP8 feature shards: compact on disk, close to the original after batchingseqs = [{"tokens": torch.randint(0, V, (9,)), "hidden": (torch.randn(8, C.hidden) * 3).to(torch.bfloat16),"P": 2, "domain": "chat", "id": str(i)} for i in range(3)]save_shard(str(Path(tmp) / "f8"), seqs, fp8=True)assert (Path(tmp) / "f8.hid8.npy").exists() and not (Path(tmp) / "f8.hid.npy").exists()back = load_shards(tmp, "cpu")_, hb, _, _ = collate(back)rel = float((hb.float() - torch.stack([s["hidden"].float() for s in seqs])).norm()/ torch.stack([s["hidden"].float() for s in seqs]).norm())assert rel < 0.05, relx = torch.randn(5, C.hidden)assert float((fp8_dequantize(*fp8_quantize(x), dtype=torch.float32) - x).norm() / x.norm()) < 0.05# the full-size draft against the memory cap (bf16 weights + KV cache at 16K tokens)big = EagleConfig()H, n = big.hidden, len(big.aux_layers)params = (n * H * H + 2 * H * big.heads * big.head_dim + 2 * 2 * H * big.kv_heads * big.head_dim+ big.heads * big.head_dim * H + 3 * H * big.inter + (n + 4) * H)memory = 2 * params + 1 * big.kv_heads * big.head_dim * 2 * 2 * 16384assert 916507648 / memory >= 1.5, (params, memory)from emcdraft.gen_vllm import share_from_envsh = share_from_env("longform=0.6,chat=0.2,code=0.1,math=0.1")assert abs(sh["longform"] - 0.6) < 1e-9 and abs(sum(sh.values()) - 1) < 1e-9print(f" eagle export: engine names, validate, FP8 shards (rel err {rel:.3f}); full size {params / 1e6:.0f} M params, "f"memory {memory / 1e9:.3f} GB (ratio {916507648 / memory:.2f} >= 1.5)")if __name__ == "__main__":head = MTPHead(C)for p in head.parameters():8 unmodified linesprint("helpers"); test_helpers()print("append"); test_append()print("recipes"); test_recipes(head, E, W)print("eagle"); test_eagle(E, W)print("ALL OK")
control/reset.txt+1
control/run.env+26-6
emcdraft/eagle.pyAdded+198
emcdraft/extract.py+87-6
emcdraft/gen_vllm.py+15-1
emcdraft/head.py+5-3
emcdraft/sim.py+42-8
emcdraft/target.py+27
emcdraft/train.py+5-2
scripts/launch.py+12-6
scripts/pipeline.sh+42-4
scripts/supervise.py+44
tests/test_head.py+91