mudassiruddin21 commited on
Commit
b80a86d
·
verified ·
1 Parent(s): dcc3a31

Engine-based data generation and an unattended GPU driver

Browse files
README.md CHANGED
@@ -57,12 +57,17 @@ before choosing it:
57
 
58
  ### Training
59
 
60
- * **Data — the target's own greedy answers.** The target (Hugging Face implementation) answers
61
- fresh prompts in the four evaluated domains (chat, code, math, long-form writing), phrased
62
- like the public dev tasks; every token's final hidden state is stored. Prompts come from
63
- public instruction sets (GSM8K / MetaMathQA, WritingPrompts, UltraChat / Alpaca / Dolly,
64
- Python instruction sets). Anything overlapping the dev prompts is removed; the dev set is
65
- never trained on.
 
 
 
 
 
66
  * **Objective — the engine's drafting loop.** `emcdraft.head.unroll` runs all three draft steps
67
  for every position of a sequence in parallel, with exactly the key/value visibility the
68
  engine's draft cache has (verified prefix, then the round's own entries). Each step is
@@ -89,36 +94,54 @@ dataset repo. *(Filled in by the run — see `results/summary.md`.)*
89
 
90
  ```
91
  emcdraft/head.py MTP head re-implementation, K-step unroll, FP8 rounding/encoding, export
92
- emcdraft/target.py target wrapper: final hidden states and batched greedy generation
93
- emcdraft/prompts.py training prompts per domain, dev-overlap filter
94
- emcdraft/datagen.py sanity checks against the dev set, hold-out features, data generation
 
95
  emcdraft/sim.py offline acceptance simulator, feature shards
96
  emcdraft/train.py fine-tuning (recursive objective, optional FP8 QAT), export
97
  emcdraft/probe.py untrained FP8 copy of the baseline (engine loading probe)
98
  scripts/kit.py runs the official kit commands without a container runtime
99
- scripts/pipeline.sh end-to-end, resumable pipeline; scripts/bootstrap.sh starts it detached
 
 
100
  scripts/sync.py pushes logs / results / draft folders to the Hugging Face dataset repo
101
  scripts/collect.py results/summary.{json,md}
 
102
  tests/test_head.py CPU self-test (FP8 codec, unroll vs. step-by-step emulation, export)
103
  ```
104
 
105
  ## Reproduce
106
 
107
- Linux, one GPU with ≥ 80 GB, ~110 GB of disk.
 
108
 
109
- ```bash
110
- git clone https://github.com/Mudassiruddin7/EMC.git ~/emc/repo
111
- bash ~/emc/repo/scripts/bootstrap.sh # runs detached; progress in ~/emc/logs/pipeline.log
 
 
 
112
  ```
113
 
114
- The pipeline installs `vllm==0.31.0` into a private environment, downloads the target at the
115
- kit's pinned revision, builds and validates the baseline, checks that the engine loads an
116
- FP8-typed head, generates data, trains, and evaluates with the **official kit**
117
- (`validate`, `eval`) — through `scripts/kit.py`, which only redirects the kit's container
118
- paths. The engine is the pinned version installed from PyPI rather than the container image;
119
- the results JSON records this.
120
-
121
- `python tests/test_head.py` runs the CPU self-test (no GPU, no downloads).
 
 
 
 
 
 
 
 
 
 
122
 
123
  ## Submission format and rules
124
 
 
57
 
58
  ### Training
59
 
60
+ * **Data — the target's own greedy answers.** Fresh prompts in the four evaluated domains
61
+ (chat, code, math, long-form writing), phrased like the public dev tasks, are answered
62
+ greedily by the target running in the serving engine itself (vLLM 0.31.0), so the training
63
+ text is exactly the kind of text the draft has to predict. The target's final hidden state
64
+ at every position is then recomputed with the reference implementation in one
65
+ teacher-forced pass. Two checks guard this step: the reference implementation must agree
66
+ with the engine's greedy choices along the dev references, and the offline simulator
67
+ (below) must reproduce the kit-measured acceptance of the baseline head. Prompts come from
68
+ public instruction sets (GSM8K / Orca-Math, WritingPrompts, UltraChat / Alpaca / Dolly,
69
+ Python instruction sets, MBPP); anything overlapping the dev prompts is removed and the
70
+ dev set is never trained on.
71
  * **Objective — the engine's drafting loop.** `emcdraft.head.unroll` runs all three draft steps
72
  for every position of a sequence in parallel, with exactly the key/value visibility the
73
  engine's draft cache has (verified prefix, then the round's own entries). Each step is
 
94
 
95
  ```
96
  emcdraft/head.py MTP head re-implementation, K-step unroll, FP8 rounding/encoding, export
97
+ emcdraft/prompts.py training prompts per domain, dev-overlap filter, template check
98
+ emcdraft/gen_vllm.py greedy answers of the target with the serving engine
99
+ emcdraft/target.py reference implementation wrapper: final hidden states (teacher forcing)
100
+ emcdraft/extract.py hidden-state shards, agreement check, simulator check on the baseline
101
  emcdraft/sim.py offline acceptance simulator, feature shards
102
  emcdraft/train.py fine-tuning (recursive objective, optional FP8 QAT), export
103
  emcdraft/probe.py untrained FP8 copy of the baseline (engine loading probe)
104
  scripts/kit.py runs the official kit commands without a container runtime
105
+ scripts/pipeline.sh end-to-end, resumable pipeline (one stage per step, logs per stage)
106
+ scripts/supervise.py unattended driver: code updates, control requests, log uploads
107
+ scripts/launch.py starts the driver on a GPU machine (or prints its status)
108
  scripts/sync.py pushes logs / results / draft folders to the Hugging Face dataset repo
109
  scripts/collect.py results/summary.{json,md}
110
+ control/ stage re-run requests and budget settings read by the driver
111
  tests/test_head.py CPU self-test (FP8 codec, unroll vs. step-by-step emulation, export)
112
  ```
113
 
114
  ## Reproduce
115
 
116
+ Linux, one GPU with at least 80 GB, about 110 GB of disk. In a Python shell or notebook on
117
+ that machine:
118
 
119
+ ```python
120
+ import os, urllib.request
121
+ os.environ["HF_TOKEN"] = "<token with write access to the results repo>"
122
+ exec(urllib.request.urlopen(
123
+ "https://raw.githubusercontent.com/Mudassiruddin7/EMC/main/scripts/launch.py").read(),
124
+ {"__name__": "__main__"})
125
  ```
126
 
127
+ This starts `scripts/supervise.py`, which runs `scripts/pipeline.sh` stage by stage:
128
+
129
+ | stage | what it does |
130
+ |---|---|
131
+ | env | private Python 3.12 environment with `vllm==0.31.0` |
132
+ | download | the kit (pinned commit) and the target at the kit's pinned revision |
133
+ | baseline | `emc2 prepare-baseline` + `validate` |
134
+ | probe, smoke_fp8 | FP8 copy of the untrained baseline head through the official `eval` (2 prompts per domain) |
135
+ | prompts | training prompts (runs in parallel with the GPU checks) |
136
+ | generate | greedy answers with the engine (token budget `GEN_TOKENS`) |
137
+ | extract | hidden states + agreement and simulator checks |
138
+ | train | fine-tuning, export of `sub_fp8` / `sub_bf16`, `validate` |
139
+ | eval_main, eval_baseline, eval_alt | full official `eval` (160 dev prompts) of the draft, the baseline and the second variant |
140
+
141
+ Every stage resumes after an interruption, and logs, kit results, generated data and the
142
+ draft folders are pushed to the dataset repo as they are produced. The engine is the
143
+ pinned version installed from PyPI rather than the container image; the results JSON records
144
+ this. `python tests/test_head.py` runs the CPU self-test (no GPU, no downloads).
145
 
146
  ## Submission format and rules
147
 
control/reset.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Requests to re-run pipeline stages on the GPU machine (read by scripts/supervise.py).
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
control/run.env ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # KEY=VALUE settings passed to scripts/pipeline.sh by scripts/supervise.py
2
+ GEN_TOKENS=2000000
3
+ GEN_MINUTES=30
4
+ EXTRACT_MINUTES=22
5
+ TRAIN_MINUTES=24
emcdraft/datagen.py DELETED
@@ -1,200 +0,0 @@
1
- """Self-distillation data: the target's own greedy answers with its final hidden states.
2
-
3
- 1. sanity checks against the public dev set (chat template, greedy agreement with the kit's
4
- reference outputs, and the offline simulator reproducing the baseline head's acceptance);
5
- 2. hidden states for the dev references (hold-out features, never trained on);
6
- 3. greedy generation for fresh prompts in the four domains under a wall-clock budget.
7
-
8
- Prompts in a batch all have the same token length, so no padding is ever fed to the model.
9
- """
10
- from __future__ import annotations
11
-
12
- import argparse
13
- import json
14
- import os
15
- import random
16
- import time
17
- from pathlib import Path
18
-
19
- import torch
20
- import torch.nn.functional as F
21
-
22
- from . import prompts as PR
23
- from .head import HeadConfig, build_head, load_mtp_state
24
- from .sim import DOMAINS, save_shard, simulate
25
- from .target import CHAT_PREFIX, CHAT_SUFFIX, Target
26
-
27
- SHARE = {"longform": 0.45, "chat": 0.22, "code": 0.15, "math": 0.18}
28
-
29
-
30
- def log(msg):
31
- print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
32
-
33
-
34
- def load_jsonl(p):
35
- return [json.loads(line) for line in open(p) if line.strip()]
36
-
37
-
38
- def equal_length_batches(ids_list, B, rng):
39
- by = {}
40
- for ids in ids_list:
41
- by.setdefault(len(ids), []).append(ids)
42
- for size in (B, B // 2, B // 4, 8):
43
- pool = []
44
- for _, v in by.items():
45
- rng.shuffle(v)
46
- pool += [v[s:s + size] for s in range(0, len(v) - size + 1, size)]
47
- if len(pool) >= 4 or size == 8:
48
- rng.shuffle(pool)
49
- return pool
50
- return []
51
-
52
-
53
- def gen_batch(tgt, ids, max_new, deadline):
54
- try:
55
- return [(ids, *tgt.generate(ids, max_new, deadline=deadline))]
56
- except torch.OutOfMemoryError:
57
- torch.cuda.empty_cache()
58
- if ids.shape[0] < 8:
59
- raise
60
- log(f" out of GPU memory at batch {ids.shape[0]}, splitting")
61
- h = ids.shape[0] // 2
62
- return gen_batch(tgt, ids[:h], max_new, deadline) + gen_batch(tgt, ids[h:], max_new, deadline)
63
-
64
-
65
- def main():
66
- ap = argparse.ArgumentParser()
67
- ap.add_argument("--target", required=True)
68
- ap.add_argument("--kit", required=True)
69
- ap.add_argument("--baseline", required=True)
70
- ap.add_argument("--out", required=True)
71
- ap.add_argument("--results", required=True)
72
- ap.add_argument("--minutes", type=float, default=float(os.environ.get("GEN_MINUTES", 22)))
73
- ap.add_argument("--batch", type=int, default=int(os.environ.get("GEN_BATCH", 96)))
74
- ap.add_argument("--pool", type=int, default=int(os.environ.get("GEN_POOL", 12000)))
75
- ap.add_argument("--seed", type=int, default=0)
76
- args = ap.parse_args()
77
- out, res = Path(args.out), Path(args.results)
78
- (out / "train").mkdir(parents=True, exist_ok=True)
79
- (out / "dev").mkdir(parents=True, exist_ok=True)
80
- res.mkdir(parents=True, exist_ok=True)
81
- rng = random.Random(args.seed)
82
- report = {}
83
-
84
- from transformers import AutoTokenizer
85
- tok = AutoTokenizer.from_pretrained(args.target)
86
- dev = load_jsonl(Path(args.kit) / "data/dev/prompts.jsonl")
87
- ref = {r["id"]: r["token_ids"] for r in load_jsonl(Path(args.kit) / "data/dev/reference.jsonl")}
88
- pre, suf = list(CHAT_PREFIX), list(CHAT_SUFFIX)
89
- dev_texts = [tok.decode(p["prompt_token_ids"][len(pre):-len(suf)]) for p in dev]
90
-
91
- # -- chat template check: our fast path must reproduce the kit's prompt token ids
92
- ok = 0
93
- for p, text in list(zip(dev, dev_texts))[::16]:
94
- ok += (pre + tok(text, add_special_tokens=False)["input_ids"] + suf) == p["prompt_token_ids"]
95
- report["template_match"] = f"{ok}/{len(dev[::16])}"
96
- log(f"chat template check: {report['template_match']} dev prompts reproduced exactly")
97
-
98
- # -- prompt pools (CPU only, before the model is loaded)
99
- pools = {}
100
- for d in DOMAINS:
101
- log(f"building prompt pool: {d}")
102
- texts = PR.drop_dev_overlap(PR.build(d, args.pool, args.seed, log), dev_texts, log)
103
- ids = []
104
- for i in range(0, len(texts), 2000):
105
- enc = tok([t.strip() for t in texts[i:i + 2000]], add_special_tokens=False)["input_ids"]
106
- ids += [pre + e + suf for e in enc if 8 <= len(e) <= 440]
107
- pools[d] = ids
108
- log(f" {d}: {len(ids)} prompts")
109
- report["pool_sizes"] = {d: len(v) for d, v in pools.items()}
110
-
111
- log("loading the target model")
112
- t0 = time.time()
113
- tgt = Target(args.target)
114
- report["load_s"] = round(time.time() - t0, 1)
115
- log(f"target loaded in {report['load_s']}s (hidden states via "
116
- f"{'base model' if tgt.use_base else 'LM-head hook'})")
117
-
118
- # -- greedy agreement with the kit's reference outputs (engine vs. this implementation)
119
- agree = []
120
- for p in [x for x in dev if x["domain"] == "math"][:6]:
121
- ids = torch.tensor([p["prompt_token_ids"]], device=tgt.device)
122
- toks, lens, _, _ = tgt.generate(ids, 48)
123
- r = ref[p["id"]][:48]
124
- g = toks[0, :len(r)].tolist()
125
- same = next((i for i, (a, b) in enumerate(zip(g, r)) if a != b), min(len(g), len(r)))
126
- agree.append(same / max(1, len(r)))
127
- report["greedy_prefix_agreement"] = round(sum(agree) / len(agree), 3)
128
- log(f"greedy agreement with reference outputs (first 48 tokens): {report['greedy_prefix_agreement']:.3f}")
129
-
130
- # -- hold-out features: hidden states along the dev references
131
- dev_seqs = {d: [] for d in DOMAINS}
132
- t0 = time.time()
133
- for p in dev:
134
- ids = p["prompt_token_ids"] + ref[p["id"]]
135
- x = torch.tensor([ids], device=tgt.device)
136
- h, _ = tgt.run(x, use_cache=False)
137
- dev_seqs[p["domain"]].append({"tokens": x[0], "hidden": h[0, :-1].clone(), "T": len(ids),
138
- "P": len(p["prompt_token_ids"]), "domain": p["domain"], "id": p["id"]})
139
- for d in DOMAINS:
140
- save_shard(str(out / "dev" / d), dev_seqs[d])
141
- log(f"dev features: {sum(len(v) for v in dev_seqs.values())} sequences in {time.time() - t0:.0f}s")
142
-
143
- # -- the simulator must reproduce the baseline head's measured acceptance
144
- cfg = HeadConfig.from_target(json.loads((Path(args.target) / "config.json").read_text()))
145
- head = build_head(load_mtp_state(args.baseline), cfg, tgt.device)
146
- E = tgt.embed.weight
147
- sim = simulate(head, lambda i: F.embedding(i, E), tgt.W, [s for d in DOMAINS for s in dev_seqs[d]])
148
- kit_base = json.loads((Path(args.kit) / "data/dev/baseline.json").read_text())
149
- report["sim_baseline_dev"] = sim
150
- report["kit_baseline_dev"] = {k: kit_base[k] for k in ("acceptance_length", "acceptance_by_domain")}
151
- log(f"simulated baseline acceptance {sim['acceptance_length']:.3f} "
152
- f"(kit measured {kit_base['acceptance_length']:.3f}); per domain "
153
- + ", ".join(f"{d} {sim['acceptance_by_domain'][d]:.3f}/{kit_base['acceptance_by_domain'][d]:.3f}"
154
- for d in DOMAINS))
155
- log(f"step accuracies {[round(a, 3) for a in sim['step_accuracy']]}")
156
- (res / "datagen_checks.json").write_text(json.dumps(report, indent=2))
157
- del head, dev_seqs
158
- torch.cuda.empty_cache()
159
-
160
- # -- generation under a wall-clock budget
161
- stats = {}
162
- budget = args.minutes * 60
163
- for d in ("longform", "chat", "code", "math"):
164
- groups = equal_length_batches(pools[d], args.batch, rng)
165
- end = time.time() + budget * SHARE[d]
166
- n_tok = n_seq = 0
167
- t0 = time.time()
168
- for bi, batch in enumerate(groups):
169
- if time.time() > end - 20:
170
- break
171
- ids = torch.tensor(batch, device=tgt.device)
172
- tb = time.time()
173
- seqs = []
174
- for pid, toks, lens, hp, hs in gen_batch(tgt, ids, PR.MAX_NEW[d], end):
175
- P = pid.shape[1]
176
- for b in range(pid.shape[0]):
177
- n = int(lens[b])
178
- if n < 8:
179
- continue
180
- seqs.append({"tokens": torch.cat([pid[b], toks[b, :n]]),
181
- "hidden": torch.cat([hp[b], hs[b, :n - 1]]), "P": P, "domain": d})
182
- del toks, hp, hs
183
- if seqs:
184
- save_shard(str(out / "train" / f"{d}_{bi:04d}"), seqs)
185
- got = sum(int(s["tokens"].numel()) - s["P"] for s in seqs)
186
- n_tok += got
187
- n_seq += len(seqs)
188
- log(f" {d} batch {bi}: {len(seqs)} seqs, {got} new tokens, "
189
- f"{got / max(1e-6, time.time() - tb):.0f} tok/s")
190
- del seqs
191
- torch.cuda.empty_cache()
192
- stats[d] = {"sequences": n_seq, "generated_tokens": n_tok, "seconds": round(time.time() - t0, 1)}
193
- log(f"{d}: {n_seq} sequences, {n_tok} generated tokens")
194
- report["generation"] = stats
195
- (res / "datagen_checks.json").write_text(json.dumps(report, indent=2))
196
- log("data generation finished")
197
-
198
-
199
- if __name__ == "__main__":
200
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
emcdraft/extract.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hidden states of the target along token sequences, plus the checks the training relies on.
2
+
3
+ 1. Dev references (the kit's target-only outputs): features for the hold-out evaluation,
4
+ teacher-forced agreement of the reference implementation with the engine's greedy choices,
5
+ and the offline simulator replaying the *baseline* head - its acceptance must match what the
6
+ kit measured, otherwise the simulator (and the training objective) is not trustworthy.
7
+ 2. Generated training sequences (emcdraft.gen_vllm): feature shards for training, under a
8
+ wall-clock budget, domains interleaved so a cut-off keeps the mix.
9
+
10
+ python -m emcdraft.extract --target DIR --kit DIR --baseline DIR --gen data/gen --out data --results results
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import random
18
+ import time
19
+ from collections import defaultdict
20
+ from pathlib import Path
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+
25
+ from .head import HeadConfig, build_head, load_mtp_state
26
+ from .sim import DOMAINS, argmax_logits, save_shard, simulate
27
+ from .target import PAD_ID, Target
28
+
29
+
30
+ def log(msg):
31
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
32
+
33
+
34
+ def make_batches(seqs, max_tokens):
35
+ order = sorted(range(len(seqs)), key=lambda i: len(seqs[i]["ids"]))
36
+ out, cur = [], []
37
+ for i in order:
38
+ if cur and (len(cur) + 1) * len(seqs[i]["ids"]) > max_tokens:
39
+ out.append(cur)
40
+ cur = []
41
+ cur.append(i)
42
+ if cur:
43
+ out.append(cur)
44
+ return out
45
+
46
+
47
+ def featurize(tgt, seqs, max_tokens, agree):
48
+ """Teacher-forced hidden states for every sequence (kept on the GPU)."""
49
+ feats = []
50
+ queue = make_batches(seqs, max_tokens)
51
+ while queue:
52
+ b = queue.pop(0)
53
+ L = max(len(seqs[i]["ids"]) for i in b)
54
+ x = torch.full((len(b), L), PAD_ID, dtype=torch.long, device=tgt.device)
55
+ for r, i in enumerate(b):
56
+ x[r, :len(seqs[i]["ids"])] = torch.tensor(seqs[i]["ids"], device=tgt.device)
57
+ try:
58
+ h = tgt.hidden(x)
59
+ except torch.OutOfMemoryError:
60
+ torch.cuda.empty_cache()
61
+ if len(b) == 1:
62
+ raise
63
+ log(f" out of memory on {len(b)} x {L}; splitting the batch")
64
+ queue[:0] = [b[: len(b) // 2], b[len(b) // 2:]]
65
+ continue
66
+ for r, i in enumerate(b):
67
+ s = seqs[i]
68
+ n, P = len(s["ids"]), s["P"]
69
+ hid = h[r, : n - 1].clone()
70
+ pred = argmax_logits(hid[P - 1:], tgt.W)
71
+ agree[s["domain"]][0] += int((pred == x[r, P:n]).sum())
72
+ agree[s["domain"]][1] += n - P
73
+ feats.append({"tokens": x[r, :n].clone(), "hidden": hid, "P": P, "T": n,
74
+ "domain": s["domain"], "id": s.get("id", "")})
75
+ del h, x
76
+ return feats
77
+
78
+
79
+ def main():
80
+ ap = argparse.ArgumentParser()
81
+ ap.add_argument("--target", required=True)
82
+ ap.add_argument("--kit", required=True)
83
+ ap.add_argument("--baseline", required=True)
84
+ ap.add_argument("--gen", required=True)
85
+ ap.add_argument("--out", required=True)
86
+ ap.add_argument("--results", required=True)
87
+ ap.add_argument("--batch-tokens", type=int, default=int(os.environ.get("EXTRACT_BATCH_TOKENS", 16384)))
88
+ ap.add_argument("--minutes", type=float, default=float(os.environ.get("EXTRACT_MINUTES", 22)))
89
+ ap.add_argument("--group", type=int, default=256, help="sequences per training shard")
90
+ ap.add_argument("--seed", type=int, default=0)
91
+ a = ap.parse_args()
92
+ out, res = Path(a.out), Path(a.results)
93
+ for sub in ("dev", "train"):
94
+ (out / sub).mkdir(parents=True, exist_ok=True)
95
+ for p in (out / sub).glob("*"):
96
+ p.unlink()
97
+ res.mkdir(parents=True, exist_ok=True)
98
+ report = {}
99
+
100
+ t0 = time.time()
101
+ tgt = Target(a.target)
102
+ report["load_seconds"] = round(time.time() - t0, 1)
103
+ report["hidden_state_call"] = tgt.mode
104
+ log(f"target loaded in {report['load_seconds']}s (hidden states via '{tgt.mode}')")
105
+
106
+ # 1. dev references
107
+ kit = Path(a.kit) / "data/dev"
108
+ ref = {r["id"]: r["token_ids"] for r in map(json.loads, open(kit / "reference.jsonl")) if r}
109
+ dev = [json.loads(line) for line in open(kit / "prompts.jsonl") if line.strip()]
110
+ seqs = [{"ids": p["prompt_token_ids"] + ref[p["id"]], "P": len(p["prompt_token_ids"]),
111
+ "domain": p["domain"], "id": p["id"]} for p in dev]
112
+ agree = defaultdict(lambda: [0, 0])
113
+ t0 = time.time()
114
+ feats = featurize(tgt, seqs, a.batch_tokens, agree)
115
+ for d in DOMAINS:
116
+ save_shard(str(out / "dev" / d), [f for f in feats if f["domain"] == d])
117
+ report["dev_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}
118
+ log(f"dev features: {len(feats)} sequences in {time.time() - t0:.0f}s; teacher-forced agreement with "
119
+ f"the engine's greedy outputs {report['dev_teacher_forced_agreement']}")
120
+
121
+ cfg = HeadConfig.from_target(json.loads((Path(a.target) / "config.json").read_text()))
122
+ head = build_head(load_mtp_state(a.baseline), cfg, tgt.device)
123
+ E = tgt.E
124
+ sim = simulate(head, lambda i: F.embedding(i, E), tgt.W, feats)
125
+ base = json.loads((kit / "baseline.json").read_text())
126
+ report["sim_baseline_dev"] = sim
127
+ report["kit_baseline_dev"] = {k: base[k] for k in ("acceptance_length", "acceptance_by_domain")}
128
+ log(f"simulated baseline acceptance {sim['acceptance_length']:.3f} vs kit-measured "
129
+ f"{base['acceptance_length']:.3f}; per domain "
130
+ + ", ".join(f"{d} {sim['acceptance_by_domain'][d]:.3f}/{base['acceptance_by_domain'][d]:.3f}" for d in DOMAINS)
131
+ + f"; step accuracies {[round(x, 3) for x in sim['step_accuracy']]}")
132
+ (res / "extract_checks.json").write_text(json.dumps(report, indent=2))
133
+ gap = abs(sim["acceptance_length"] - base["acceptance_length"])
134
+ if gap > 0.25:
135
+ raise SystemExit(f"the simulator disagrees with the kit by {gap:.3f}: refusing to train on it")
136
+ del head, feats
137
+ torch.cuda.empty_cache()
138
+
139
+ # 2. generated training sequences
140
+ rng = random.Random(a.seed)
141
+ gen = []
142
+ for d in DOMAINS:
143
+ p = Path(a.gen) / f"{d}.jsonl"
144
+ if p.exists():
145
+ for line in open(p):
146
+ r = json.loads(line)
147
+ if len(r["o"]) >= 8:
148
+ gen.append({"ids": r["p"] + r["o"], "P": len(r["p"]), "domain": d})
149
+ rng.shuffle(gen)
150
+ log(f"{len(gen)} generated sequences to featurize")
151
+ agree = defaultdict(lambda: [0, 0])
152
+ done = defaultdict(lambda: [0, 0])
153
+ t0 = time.time()
154
+ for g in range(0, len(gen), a.group):
155
+ if time.time() - t0 > a.minutes * 60:
156
+ log("time budget reached")
157
+ break
158
+ feats = featurize(tgt, gen[g:g + a.group], a.batch_tokens, agree)
159
+ save_shard(str(out / "train" / f"g{g // a.group:04d}"), feats)
160
+ for f in feats:
161
+ done[f["domain"]][0] += 1
162
+ done[f["domain"]][1] += f["T"] - f["P"]
163
+ del feats
164
+ n = sum(v[1] for v in done.values())
165
+ log(f" group {g // a.group}: {n} generated tokens featurized, {n / (time.time() - t0):.0f} tok/s")
166
+ report["train_sequences"] = {d: {"sequences": v[0], "generated_tokens": v[1]} for d, v in done.items()}
167
+ report["train_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}
168
+ report["extract_seconds"] = round(time.time() - t0, 1)
169
+ (res / "extract_checks.json").write_text(json.dumps(report, indent=2))
170
+ log(f"done: {report['train_sequences']}")
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
emcdraft/gen_vllm.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Greedy answers of the target to the training prompts, generated with the serving engine.
2
+
3
+ Using vLLM (the same engine and settings family the competition scores with) makes the
4
+ training text exactly the kind of text the draft will be asked to predict, and is an order of
5
+ magnitude faster than generating with the reference implementation. Hidden states are added
6
+ afterwards by `emcdraft.extract` in one teacher-forced pass per sequence.
7
+
8
+ python -m emcdraft.gen_vllm --target DIR --prompts data/prompts --out data/gen --results results
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import math
15
+ import os
16
+ import random
17
+ import time
18
+ from pathlib import Path
19
+
20
+ from .prompts import DOMAINS, MAX_NEW
21
+
22
+ SHARE = {"longform": 0.45, "chat": 0.22, "code": 0.15, "math": 0.18} # of generated tokens
23
+ MEAN_LEN = {"chat": 383, "code": 270, "math": 309, "longform": 938} # dev reference means
24
+ STOP_IDS = [248046, 248044]
25
+
26
+
27
+ def log(msg):
28
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
29
+
30
+
31
+ def make_llm(target: str):
32
+ from vllm import LLM
33
+ kw = dict(model=target, tokenizer=target, dtype="bfloat16", seed=0,
34
+ max_model_len=int(os.environ.get("GEN_MAX_LEN", 2048)),
35
+ gpu_memory_utilization=float(os.environ.get("GEN_GPU_UTIL", 0.90)),
36
+ max_num_seqs=int(os.environ.get("GEN_MAX_SEQS", 128)),
37
+ enable_prefix_caching=False, generation_config="vllm", language_model_only=True)
38
+ for drop in ((), ("language_model_only",), ("language_model_only", "generation_config")):
39
+ try:
40
+ return LLM(**{k: v for k, v in kw.items() if k not in drop})
41
+ except TypeError as e:
42
+ log(f"engine rejected an option ({e}); retrying without {drop or 'nothing'}")
43
+ raise RuntimeError("could not start the engine")
44
+
45
+
46
+ def main():
47
+ ap = argparse.ArgumentParser()
48
+ ap.add_argument("--target", required=True)
49
+ ap.add_argument("--prompts", required=True)
50
+ ap.add_argument("--out", required=True)
51
+ ap.add_argument("--results", required=True)
52
+ ap.add_argument("--tokens", type=float, default=float(os.environ.get("GEN_TOKENS", 2.0e6)))
53
+ ap.add_argument("--minutes", type=float, default=float(os.environ.get("GEN_MINUTES", 30)))
54
+ ap.add_argument("--chunk", type=int, default=int(os.environ.get("GEN_CHUNK", 2000)))
55
+ ap.add_argument("--seed", type=int, default=0)
56
+ a = ap.parse_args()
57
+ rng = random.Random(a.seed)
58
+ out = Path(a.out)
59
+ out.mkdir(parents=True, exist_ok=True)
60
+ for d in DOMAINS:
61
+ (out / f"{d}.jsonl").unlink(missing_ok=True)
62
+
63
+ items = []
64
+ for d in DOMAINS:
65
+ pool = [json.loads(line)["ids"] for line in open(Path(a.prompts) / f"{d}.jsonl") if line.strip()]
66
+ rng.shuffle(pool)
67
+ want = math.ceil(1.1 * a.tokens * SHARE[d] / MEAN_LEN[d])
68
+ items += [(d, ids) for ids in pool[:want]]
69
+ log(f"{d}: {min(want, len(pool))} prompts (pool {len(pool)})")
70
+ rng.shuffle(items)
71
+
72
+ from vllm import SamplingParams
73
+ sp = {d: SamplingParams(temperature=0.0, max_tokens=MAX_NEW[d], stop_token_ids=STOP_IDS,
74
+ detokenize=False) for d in DOMAINS}
75
+ t0 = time.time()
76
+ llm = make_llm(a.target)
77
+ log(f"engine ready in {time.time() - t0:.0f}s")
78
+ t0 = time.time()
79
+ stats = {d: {"sequences": 0, "generated_tokens": 0, "stopped": 0} for d in DOMAINS}
80
+ files = {d: open(out / f"{d}.jsonl", "a") for d in DOMAINS}
81
+ total = 0
82
+ for s in range(0, len(items), a.chunk):
83
+ if time.time() - t0 > a.minutes * 60 or total >= a.tokens:
84
+ log("budget reached")
85
+ break
86
+ chunk = items[s:s + a.chunk]
87
+ tc = time.time()
88
+ res = llm.generate([{"prompt_token_ids": ids} for _, ids in chunk], [sp[d] for d, _ in chunk],
89
+ use_tqdm=False)
90
+ got = 0
91
+ for (d, ids), r in zip(chunk, res):
92
+ o = list(r.outputs[0].token_ids)
93
+ files[d].write(json.dumps({"p": ids, "o": o}) + "\n")
94
+ stats[d]["sequences"] += 1
95
+ stats[d]["generated_tokens"] += len(o)
96
+ stats[d]["stopped"] += int(bool(o) and o[-1] in STOP_IDS)
97
+ got += len(o)
98
+ for f in files.values():
99
+ f.flush()
100
+ total += got
101
+ log(f"chunk {s // a.chunk}: {len(chunk)} prompts, {got} tokens, {got / (time.time() - tc):.0f} tok/s "
102
+ f"(total {total})")
103
+ for f in files.values():
104
+ f.close()
105
+ report = {"seconds": round(time.time() - t0, 1), "generated_tokens": total, "by_domain": stats}
106
+ Path(a.results).mkdir(parents=True, exist_ok=True)
107
+ (Path(a.results) / "generation.json").write_text(json.dumps(report, indent=2))
108
+ log(f"generated {total} tokens in {report['seconds']}s")
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
emcdraft/head.py CHANGED
@@ -75,8 +75,18 @@ def e4m3_round(w: torch.Tensor) -> torch.Tensor:
75
  return (torch.sign(w.detach().float()) * q).to(w.dtype)
76
 
77
 
78
- def e4m3_encode(w: torch.Tensor) -> torch.Tensor:
79
- """uint8 bit patterns (sign | 4-bit exponent, bias 7 | 3-bit mantissa) of on-grid values."""
 
 
 
 
 
 
 
 
 
 
80
  q = e4m3_round(w.float())
81
  a = q.abs()
82
  _, ex = torch.frexp(a)
 
75
  return (torch.sign(w.detach().float()) * q).to(w.dtype)
76
 
77
 
78
+ def e4m3_encode(w: torch.Tensor, chunk: int = 1 << 24) -> torch.Tensor:
79
+ """uint8 bit patterns (sign | 4-bit exponent, bias 7 | 3-bit mantissa) of on-grid values.
80
+
81
+ Works in chunks so the int64 temporaries stay small (host memory is limited)."""
82
+ flat = w.detach().reshape(-1)
83
+ out = torch.empty(flat.numel(), dtype=torch.uint8, device=flat.device)
84
+ for s in range(0, flat.numel(), chunk):
85
+ out[s:s + chunk] = _e4m3_encode(flat[s:s + chunk])
86
+ return out.view(w.shape)
87
+
88
+
89
+ def _e4m3_encode(w: torch.Tensor) -> torch.Tensor:
90
  q = e4m3_round(w.float())
91
  a = q.abs()
92
  _, ex = torch.frexp(a)
emcdraft/prompts.py CHANGED
@@ -1,13 +1,21 @@
1
- """Training prompts for the four evaluation domains (chat, code, math, long-form writing).
2
 
3
- Prompts come from public instruction datasets and are wrapped in the same task phrasing the
4
- public dev set uses. Anything that overlaps the dev prompts is dropped, so the dev set stays
5
- a clean hold-out.
 
 
 
 
6
  """
7
  from __future__ import annotations
8
 
 
 
9
  import random
10
  import re
 
 
11
 
12
  CODE_T = ("Complete the following Python function. Reply with the full function in a single "
13
  "Python code block.\n\n```python\n{stub}```")
@@ -15,7 +23,12 @@ MATH_T = ("{q}\n\nSolve this step by step, then give the final answer on its own
15
  "'Answer: <number>'.")
16
  STORY_T = "Write a short story of about {n} words based on this prompt:\n\n{p}"
17
 
18
- MAX_NEW = {"chat": 512, "code": 512, "math": 384, "longform": 1024}
 
 
 
 
 
19
  DEF_RE = re.compile(r"^def\s+([A-Za-z_]\w*)\s*\(.*?\)\s*(->\s*[^:\n]+)?:\s*$", re.M)
20
  TAG_RE = re.compile(r"^\s*\[\s*([A-Za-z]{2})\s*\]\s*")
21
  DETOK = ((" n't", "n't"), (" 's", "'s"), (" 're", "'re"), (" 've", "'ve"), (" 'm", "'m"),
@@ -23,16 +36,21 @@ DETOK = ((" n't", "n't"), (" 's", "'s"), (" 're", "'re"), (" 've", "'ve"), (" 'm
23
  (" ;", ";"), (" :", ":"), ("`` ", '"'), (" ''", '"'), ("( ", "("), (" )", ")"))
24
 
25
 
 
 
 
 
26
  def norm(s: str) -> str:
27
  return re.sub(r"[^a-z0-9]+", " ", s.lower()).strip()
28
 
29
 
30
- def take(name, config, split, n, seed, log):
31
- """First n rows of a shuffled stream; an unavailable source just yields nothing."""
32
  try:
33
  from datasets import load_dataset
34
  args = (name, config) if config else (name,)
35
- ds = load_dataset(*args, split=split, streaming=True).shuffle(seed=seed, buffer_size=10000)
 
36
  out = []
37
  for row in ds:
38
  out.append(row)
@@ -41,18 +59,19 @@ def take(name, config, split, n, seed, log):
41
  log(f" source {name}: {len(out)} rows")
42
  return out
43
  except Exception as e: # noqa: BLE001
44
- log(f" source {name}: unavailable ({type(e).__name__}: {str(e)[:120]})")
45
  return []
46
 
47
 
48
  def make_stub(instruction: str, code: str):
 
49
  code = code.replace("\r\n", "\n").replace("\t", " ")
50
  m = DEF_RE.search(code)
51
  instruction = instruction.strip()
52
  if not m or not (15 <= len(instruction) <= 500):
53
- return None, None
54
  doc = "\n ".join(line.rstrip() for line in instruction.replace('"""', "'''").splitlines())
55
- return f'{m.group(0).rstrip()}\n """{doc}\n """\n', m.group(1)
56
 
57
 
58
  def clean_story_prompt(p: str):
@@ -66,42 +85,42 @@ def clean_story_prompt(p: str):
66
  return p if 15 <= len(p) <= 400 else None
67
 
68
 
69
- def build(domain: str, n: int, seed: int, log) -> list[str]:
70
  rng = random.Random(seed)
71
  out: list[str] = []
72
  if domain == "math":
73
- for r in take("openai/gsm8k", "main", "train", 8000, seed, log):
74
  out.append(MATH_T.format(q=r["question"].strip()))
75
- for r in take("meta-math/MetaMathQA", None, "train", 3 * n, seed, log):
76
- if str(r.get("type", "")).startswith("GSM"):
77
- out.append(MATH_T.format(q=r["query"].strip()))
 
78
  elif domain == "code":
79
- pairs = []
80
- for r in take("iamtarun/python_code_instructions_18k_alpaca", None, "train", 18000, seed, log):
81
- pairs.append((r["instruction"], r["output"]))
82
- for r in take("sahil2801/CodeAlpaca-20k", None, "train", 20000, seed, log):
83
- pairs.append((r["instruction"], r["output"]))
84
- for r in take("google-research-datasets/mbpp", "full", "train", 1000, seed, log):
85
- pairs.append((r["text"], r["code"]))
86
  for instr, code in pairs:
87
- stub, _name = make_stub(instr, code)
88
  if stub:
89
  out.append(CODE_T.format(stub=stub))
90
- free = [r["instruction"].strip() for r in
91
- take("nickrosh/Evol-Instruct-Code-80k-v1", None, "train", n, seed, log)]
92
- out += [f for f in free if 20 <= len(f) <= 1200][: max(1, len(out) // 3)]
93
  elif domain == "longform":
94
- for r in take("euclaise/writingprompts", None, "train", 6 * n, seed, log):
95
  p = clean_story_prompt(r["prompt"])
96
  if p:
97
  words = 600 if rng.random() < 0.8 else rng.choice([300, 400, 500, 800])
98
  out.append(STORY_T.format(n=words, p=p))
99
  elif domain == "chat":
100
- for r in take("HuggingFaceH4/ultrachat_200k", None, "train_sft", 2 * n, seed, log):
101
  out.append(r["prompt"].strip())
102
- for r in take("tatsu-lab/alpaca", None, "train", n, seed, log):
103
  out.append((r["instruction"] + ("\n\n" + r["input"] if r.get("input") else "")).strip())
104
- for r in take("databricks/databricks-dolly-15k", None, "train", n // 2, seed, log):
105
  out.append((r["instruction"] + ("\n\n" + r["context"] if r.get("context") else "")).strip())
106
  out = [p for p in out if 20 <= len(p) <= 1500]
107
  else:
@@ -111,22 +130,72 @@ def build(domain: str, n: int, seed: int, log) -> list[str]:
111
  return out
112
 
113
 
114
- def drop_dev_overlap(prompts: list[str], dev_texts: list[str], log) -> list[str]:
115
- """Remove any training prompt whose task text also appears in the public dev set."""
116
  blob = " || ".join(norm(t) for t in dev_texts)
117
  dev_defs = {m.group(1) for t in dev_texts for m in DEF_RE.finditer(t)}
 
118
  kept = []
119
  for p in prompts:
120
  core = p
121
- for t in (CODE_T, MATH_T, STORY_T):
122
- head = t.split("{")[0]
123
- if head and p.startswith(head):
124
- core = p[len(head):]
125
  core = core.split("\n\nSolve this step by step")[0]
126
  key = norm(core)[:160]
127
  names = {m.group(1) for m in DEF_RE.finditer(p)}
128
  if (len(key) >= 20 and key in blob) or (names & dev_defs):
129
  continue
130
  kept.append(p)
131
- log(f" dev-overlap filter: kept {len(kept)} of {len(prompts)}")
132
  return kept
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training prompts for the four evaluated domains (chat, code, math, long-form writing).
2
 
3
+ Prompts come from public instruction datasets and are phrased like the public dev tasks.
4
+ Anything that overlaps the dev prompts is dropped, so the dev set stays a clean hold-out.
5
+
6
+ python -m emcdraft.prompts --target DIR --kit DIR --out data/prompts --results results
7
+
8
+ writes data/prompts/<domain>.jsonl ({"ids": chat-templated prompt token ids}) and
9
+ results/prompts_checks.json (template round-trip check against the kit's dev prompts).
10
  """
11
  from __future__ import annotations
12
 
13
+ import argparse
14
+ import json
15
  import random
16
  import re
17
+ import time
18
+ from pathlib import Path
19
 
20
  CODE_T = ("Complete the following Python function. Reply with the full function in a single "
21
  "Python code block.\n\n```python\n{stub}```")
 
23
  "'Answer: <number>'.")
24
  STORY_T = "Write a short story of about {n} words based on this prompt:\n\n{p}"
25
 
26
+ DOMAINS = ("chat", "code", "math", "longform")
27
+ MAX_NEW = {"chat": 512, "code": 512, "math": 384, "longform": 1024} # as in the dev set
28
+ CHAT_PREFIX = [248045, 846, 198] # <|im_start|>user\n
29
+ CHAT_SUFFIX = [248046, 198, 248045, 74455, 198, 248068, 271, 248069, 271]
30
+ # <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n (enable_thinking = False)
31
+
32
  DEF_RE = re.compile(r"^def\s+([A-Za-z_]\w*)\s*\(.*?\)\s*(->\s*[^:\n]+)?:\s*$", re.M)
33
  TAG_RE = re.compile(r"^\s*\[\s*([A-Za-z]{2})\s*\]\s*")
34
  DETOK = ((" n't", "n't"), (" 's", "'s"), (" 're", "'re"), (" 've", "'ve"), (" 'm", "'m"),
 
36
  (" ;", ";"), (" :", ":"), ("`` ", '"'), (" ''", '"'), ("( ", "("), (" )", ")"))
37
 
38
 
39
+ def log(msg):
40
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
41
+
42
+
43
  def norm(s: str) -> str:
44
  return re.sub(r"[^a-z0-9]+", " ", s.lower()).strip()
45
 
46
 
47
+ def take(name, config, split, n, seed):
48
+ """Up to n rows of a shuffled stream; an unavailable source just yields nothing."""
49
  try:
50
  from datasets import load_dataset
51
  args = (name, config) if config else (name,)
52
+ ds = load_dataset(*args, split=split, streaming=True)
53
+ ds = ds.shuffle(seed=seed, buffer_size=min(10000, max(500, 2 * n)))
54
  out = []
55
  for row in ds:
56
  out.append(row)
 
59
  log(f" source {name}: {len(out)} rows")
60
  return out
61
  except Exception as e: # noqa: BLE001
62
+ log(f" source {name}: unavailable ({type(e).__name__}: {str(e)[:160]})")
63
  return []
64
 
65
 
66
  def make_stub(instruction: str, code: str):
67
+ """A HumanEval-style stub (signature + docstring) from an instruction/solution pair."""
68
  code = code.replace("\r\n", "\n").replace("\t", " ")
69
  m = DEF_RE.search(code)
70
  instruction = instruction.strip()
71
  if not m or not (15 <= len(instruction) <= 500):
72
+ return None
73
  doc = "\n ".join(line.rstrip() for line in instruction.replace('"""', "'''").splitlines())
74
+ return f'{m.group(0).rstrip()}\n """{doc}\n """\n'
75
 
76
 
77
  def clean_story_prompt(p: str):
 
85
  return p if 15 <= len(p) <= 400 else None
86
 
87
 
88
+ def build(domain: str, n: int, seed: int) -> list[str]:
89
  rng = random.Random(seed)
90
  out: list[str] = []
91
  if domain == "math":
92
+ for r in take("openai/gsm8k", "main", "train", 8000, seed):
93
  out.append(MATH_T.format(q=r["question"].strip()))
94
+ for r in take("microsoft/orca-math-word-problems-200k", None, "train", n, seed):
95
+ q = r["question"].strip()
96
+ if 20 <= len(q) <= 800:
97
+ out.append(MATH_T.format(q=q))
98
  elif domain == "code":
99
+ pairs = [(r["instruction"], r["output"]) for r in
100
+ take("iamtarun/python_code_instructions_18k_alpaca", None, "train", 2 * n, seed)]
101
+ pairs += [(r["instruction"], r["output"]) for r in
102
+ take("sahil2801/CodeAlpaca-20k", None, "train", 2 * n, seed)]
103
+ pairs += [(r["text"], r["code"]) for r in take("google-research-datasets/mbpp", "full", "train", 1000, seed)]
104
+ free = []
 
105
  for instr, code in pairs:
106
+ stub = make_stub(instr, code)
107
  if stub:
108
  out.append(CODE_T.format(stub=stub))
109
+ elif 20 <= len(instr.strip()) <= 600 and "python" in instr.lower():
110
+ free.append(instr.strip())
111
+ out += free[: max(1, len(out) // 3)]
112
  elif domain == "longform":
113
+ for r in take("euclaise/writingprompts", None, "train", 4 * n, seed):
114
  p = clean_story_prompt(r["prompt"])
115
  if p:
116
  words = 600 if rng.random() < 0.8 else rng.choice([300, 400, 500, 800])
117
  out.append(STORY_T.format(n=words, p=p))
118
  elif domain == "chat":
119
+ for r in take("HuggingFaceH4/ultrachat_200k", None, "train_sft", n, seed):
120
  out.append(r["prompt"].strip())
121
+ for r in take("tatsu-lab/alpaca", None, "train", n // 2, seed):
122
  out.append((r["instruction"] + ("\n\n" + r["input"] if r.get("input") else "")).strip())
123
+ for r in take("databricks/databricks-dolly-15k", None, "train", n // 2, seed):
124
  out.append((r["instruction"] + ("\n\n" + r["context"] if r.get("context") else "")).strip())
125
  out = [p for p in out if 20 <= len(p) <= 1500]
126
  else:
 
130
  return out
131
 
132
 
133
+ def drop_dev_overlap(prompts: list[str], dev_texts: list[str]) -> list[str]:
134
+ """Remove every training prompt whose task text also appears in the public dev set."""
135
  blob = " || ".join(norm(t) for t in dev_texts)
136
  dev_defs = {m.group(1) for t in dev_texts for m in DEF_RE.finditer(t)}
137
+ heads = [t.split("{")[0] for t in (CODE_T, MATH_T, STORY_T)]
138
  kept = []
139
  for p in prompts:
140
  core = p
141
+ for h in heads:
142
+ if h and p.startswith(h):
143
+ core = p[len(h):]
 
144
  core = core.split("\n\nSolve this step by step")[0]
145
  key = norm(core)[:160]
146
  names = {m.group(1) for m in DEF_RE.finditer(p)}
147
  if (len(key) >= 20 and key in blob) or (names & dev_defs):
148
  continue
149
  kept.append(p)
 
150
  return kept
151
+
152
+
153
+ def main():
154
+ ap = argparse.ArgumentParser()
155
+ ap.add_argument("--target", required=True)
156
+ ap.add_argument("--kit", required=True)
157
+ ap.add_argument("--out", required=True)
158
+ ap.add_argument("--results", required=True)
159
+ ap.add_argument("--n", type=int, default=4000, help="rows drawn per source")
160
+ ap.add_argument("--seed", type=int, default=0)
161
+ a = ap.parse_args()
162
+ from tokenizers import Tokenizer
163
+ tok = Tokenizer.from_file(str(Path(a.target) / "tokenizer.json"))
164
+ out = Path(a.out)
165
+ out.mkdir(parents=True, exist_ok=True)
166
+ Path(a.results).mkdir(parents=True, exist_ok=True)
167
+
168
+ dev = [json.loads(line) for line in open(Path(a.kit) / "data/dev/prompts.jsonl") if line.strip()]
169
+ pre, suf = len(CHAT_PREFIX), len(CHAT_SUFFIX)
170
+ dev_texts = [tok.decode(p["prompt_token_ids"][pre:-suf], skip_special_tokens=False) for p in dev]
171
+ sample = list(zip(dev, dev_texts))[::4]
172
+ ok = sum(CHAT_PREFIX + tok.encode(t, add_special_tokens=False).ids + CHAT_SUFFIX == p["prompt_token_ids"]
173
+ for p, t in sample)
174
+ report = {"template_match": f"{ok}/{len(sample)}", "domains": {}}
175
+ log(f"chat template check: {ok}/{len(sample)} dev prompts reproduced token-for-token")
176
+ if ok < 0.9 * len(sample):
177
+ raise SystemExit("the prompt template does not reproduce the dev prompts")
178
+
179
+ for d in DOMAINS:
180
+ log(f"domain {d}")
181
+ texts = build(d, a.n, a.seed)
182
+ kept = drop_dev_overlap(texts, dev_texts)
183
+ rows = []
184
+ for i in range(0, len(kept), 1000):
185
+ for e in tok.encode_batch(kept[i:i + 1000], add_special_tokens=False):
186
+ if 8 <= len(e.ids) <= 440:
187
+ rows.append(CHAT_PREFIX + e.ids + CHAT_SUFFIX)
188
+ with open(out / f"{d}.jsonl", "w") as f:
189
+ for ids in rows:
190
+ f.write(json.dumps({"ids": ids}) + "\n")
191
+ lens = sorted(len(r) for r in rows) or [0]
192
+ report["domains"][d] = {"candidates": len(texts), "after_dev_filter": len(kept), "prompts": len(rows),
193
+ "median_prompt_tokens": lens[len(lens) // 2]}
194
+ log(f" {d}: {len(rows)} prompts (dev-overlap filter removed {len(texts) - len(kept)})")
195
+ if len(rows) < 200:
196
+ raise SystemExit(f"too few prompts for {d}")
197
+ (Path(a.results) / "prompts_checks.json").write_text(json.dumps(report, indent=2))
198
+
199
+
200
+ if __name__ == "__main__":
201
+ main()
emcdraft/target.py CHANGED
@@ -1,18 +1,15 @@
1
- """Thin wrapper around the Hugging Face implementation of the target model.
2
 
3
- Only used offline (data generation and hidden-state extraction); serving always goes through
4
- the pinned engine. The wrapper exposes the *final, post-norm* hidden state of every position,
5
- which is exactly what the engine hands to the MTP head.
 
6
  """
7
  from __future__ import annotations
8
 
9
  import torch
10
- import torch.nn.functional as F
11
 
12
- STOP_IDS = (248046, 248044) # <|im_end|>, <|endoftext|> (data/dev/meta.json)
13
- CHAT_PREFIX = (248045, 846, 198) # <|im_start|>user\n
14
- CHAT_SUFFIX = (248046, 198, 248045, 74455, 198, 248068, 271, 248069, 271)
15
- # <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n (enable_thinking=False)
16
 
17
 
18
  def load_model(path: str):
@@ -28,7 +25,7 @@ def load_model(path: str):
28
  if next(model.parameters()).dtype != torch.bfloat16:
29
  raise RuntimeError("model was not loaded in bfloat16")
30
  return model.eval()
31
- except Exception as e: # noqa: BLE001 - try the next spelling / class
32
  errs.append(f"{name}({dk}): {type(e).__name__}: {str(e)[:300]}")
33
  torch.cuda.empty_cache()
34
  raise RuntimeError("could not load the target model:\n " + "\n ".join(errs))
@@ -37,69 +34,39 @@ def load_model(path: str):
37
  class Target:
38
  def __init__(self, path: str):
39
  self.model = load_model(path)
40
- self.lm_head = self.model.get_output_embeddings()
41
- self.embed = self.model.get_input_embeddings()
42
- self.W = self.lm_head.weight
43
  self.device = self.W.device
44
- self.base = getattr(self.model, "model", None)
45
  self._cap = None
46
- self.lm_head.register_forward_pre_hook(self._hook)
47
- self.use_base = self._check_base()
48
 
49
  def _hook(self, _mod, args):
50
  self._cap = args[0]
51
 
52
- @torch.no_grad()
53
- def _check_base(self) -> bool:
54
- """Is `model.model(...)` usable and does it return the tensor fed to the LM head?"""
55
- ids = torch.tensor([list(CHAT_PREFIX) + [6820, 488, 513, 264, 5484]], device=self.device)
56
- self.model(input_ids=ids)
57
- ref = self._cap.float()
58
- try:
59
- out = self.base(input_ids=ids, use_cache=True)
60
- h = out.last_hidden_state.float()
61
- return bool(h.shape == ref.shape and out.past_key_values is not None
62
- and (h - ref).abs().max() <= 0.02 * ref.abs().max())
63
- except Exception: # noqa: BLE001
64
- return False
65
 
66
  @torch.no_grad()
67
- def run(self, ids, past=None, use_cache=True):
68
- """Post-norm hidden states [B, T, H] for `ids` and the updated cache."""
69
- if self.use_base:
70
- out = self.base(input_ids=ids, past_key_values=past, use_cache=use_cache)
71
- return out.last_hidden_state, getattr(out, "past_key_values", None)
72
- out = self.model(input_ids=ids, past_key_values=past, use_cache=use_cache)
73
- return self._cap, getattr(out, "past_key_values", None)
 
 
 
 
 
 
 
74
 
75
  @torch.no_grad()
76
- def generate(self, ids, max_new: int, stop_ids=STOP_IDS, deadline: float | None = None):
77
- """Greedy decoding for a batch of equal-length prompts (no padding needed).
78
-
79
- Returns generated tokens [B, S], per-row lengths (stop token included), the prompt
80
- hidden states [B, P, H] and the hidden states of the fed-back tokens [B, S-1, H].
81
- Rows still running at `deadline` (time.time()) are cut there: a prefix of a greedy
82
- answer is still valid training data.
83
- """
84
- import time
85
- B = ids.shape[0]
86
- hp, past = self.run(ids)
87
- h = hp[:, -1]
88
- stop = torch.tensor(stop_ids, device=ids.device)
89
- alive = torch.ones(B, dtype=torch.bool, device=ids.device)
90
- lens = torch.zeros(B, dtype=torch.long, device=ids.device)
91
- toks, hs = [], []
92
- for t in range(max_new):
93
- nxt = F.linear(h, self.W).float().argmax(-1)
94
- toks.append(nxt)
95
- done = alive & torch.isin(nxt, stop)
96
- lens[done] = t + 1
97
- alive &= ~done
98
- if t == max_new - 1 or not bool(alive.any()) or (deadline and time.time() > deadline):
99
- break
100
- hstep, past = self.run(nxt[:, None], past)
101
- h = hstep[:, -1]
102
- hs.append(h)
103
- lens[alive] = len(toks)
104
- steps = torch.stack(hs, 1) if hs else hp[:, :0]
105
- return torch.stack(toks, 1), lens, hp, steps
 
1
+ """Thin wrapper around the Hugging Face implementation of the target model (offline use only).
2
 
3
+ It returns the final, post-norm hidden state of every position - exactly the tensor the engine
4
+ hands to the MTP head - for whole sequences in one teacher-forced forward pass. Sequences in a
5
+ batch are right-padded: in a causal model, padding *after* a sequence cannot change its hidden
6
+ states, so no attention mask and no position bookkeeping is needed.
7
  """
8
  from __future__ import annotations
9
 
10
  import torch
 
11
 
12
+ PAD_ID = 248044
 
 
 
13
 
14
 
15
  def load_model(path: str):
 
25
  if next(model.parameters()).dtype != torch.bfloat16:
26
  raise RuntimeError("model was not loaded in bfloat16")
27
  return model.eval()
28
+ except Exception as e: # noqa: BLE001 - try the next class / spelling
29
  errs.append(f"{name}({dk}): {type(e).__name__}: {str(e)[:300]}")
30
  torch.cuda.empty_cache()
31
  raise RuntimeError("could not load the target model:\n " + "\n ".join(errs))
 
34
  class Target:
35
  def __init__(self, path: str):
36
  self.model = load_model(path)
37
+ head = self.model.get_output_embeddings()
38
+ self.W = head.weight
39
+ self.E = self.model.get_input_embeddings().weight
40
  self.device = self.W.device
 
41
  self._cap = None
42
+ head.register_forward_pre_hook(self._hook)
43
+ self.mode = self._select_mode()
44
 
45
  def _hook(self, _mod, args):
46
  self._cap = args[0]
47
 
48
+ def _forward(self, ids, mode):
49
+ if mode == "base":
50
+ return self.model.model(input_ids=ids, use_cache=False).last_hidden_state
51
+ out = self.model(input_ids=ids, use_cache=False, output_hidden_states=True, logits_to_keep=1)
52
+ return out.hidden_states[-1]
 
 
 
 
 
 
 
 
53
 
54
  @torch.no_grad()
55
+ def _select_mode(self) -> str:
56
+ """Pick the call whose output equals the tensor the LM head consumes."""
57
+ ids = torch.tensor([[248045, 846, 198, 6820, 488, 513, 264, 5484, 6618, 22839, 13]] * 2,
58
+ device=self.device)
59
+ self.model(input_ids=ids, use_cache=False)
60
+ ref = self._cap.float()
61
+ for mode in ("base", "states"):
62
+ try:
63
+ h = self._forward(ids, mode).float()
64
+ if h.shape == ref.shape and float((h - ref).abs().max()) <= 0.02 * float(ref.abs().max()):
65
+ return mode
66
+ except Exception: # noqa: BLE001
67
+ pass
68
+ raise RuntimeError("could not obtain the final hidden states from the target model")
69
 
70
  @torch.no_grad()
71
+ def hidden(self, ids: torch.Tensor) -> torch.Tensor:
72
+ return self._forward(ids, self.mode)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
emcdraft/train.py CHANGED
@@ -2,8 +2,8 @@
2
 
3
  Objective: for every position of a greedy answer, run the same K-step recursive drafting
4
  the engine runs (step k re-uses the head's own hidden state from step k-1) and train every
5
- step to produce the token the target actually emitted. Step 1 additionally distils the
6
- target's full next-token distribution. Later steps are weighted by whether the earlier
7
  steps were right, because the engine only ever reaches them in that case.
8
 
9
  With --qat the large matrices are trained through FP8 (E4M3) rounding (straight-through),
@@ -72,7 +72,8 @@ def train_step(head, embed, W, batch, a, K=3):
72
  labels = tokens[:, (base[0] + 1 + k).clamp(max=Tm - 1)]
73
  w = valid.float() if prev is None else valid.float() * (a.floor + (1 - a.floor) * prev.float())
74
  bi, ni = valid.nonzero(as_tuple=True)
75
- teach = hidden[bi, (ni + 1).clamp(max=N - 1)] if (k == 1 and a.beta > 0) else None
 
76
  s_k, ce_k, corr = head_loss(out[bi, ni], W, labels[bi, ni], w[bi, ni], teach, a.beta)
77
  total = total + a.step_w[k - 1] * s_k
78
  full = torch.zeros(B, N, dtype=torch.bool, device=tokens.device)
 
2
 
3
  Objective: for every position of a greedy answer, run the same K-step recursive drafting
4
  the engine runs (step k re-uses the head's own hidden state from step k-1) and train every
5
+ step to produce the token the target actually emitted, plus (weight beta) the target's full
6
+ next-token distribution at that position. Later steps are weighted by whether the earlier
7
  steps were right, because the engine only ever reaches them in that case.
8
 
9
  With --qat the large matrices are trained through FP8 (E4M3) rounding (straight-through),
 
72
  labels = tokens[:, (base[0] + 1 + k).clamp(max=Tm - 1)]
73
  w = valid.float() if prev is None else valid.float() * (a.floor + (1 - a.floor) * prev.float())
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
  total = total + a.step_w[k - 1] * s_k
79
  full = torch.zeros(B, N, dtype=torch.bool, device=tokens.device)
requirements.txt CHANGED
@@ -1,6 +1,6 @@
1
  # engine (pinned by the competition kit)
2
  vllm==0.31.0
3
- # offline data generation / training
4
  accelerate
5
  datasets
6
  safetensors
 
1
  # engine (pinned by the competition kit)
2
  vllm==0.31.0
3
+ # data generation / training (installed next to the engine)
4
  accelerate
5
  datasets
6
  safetensors
scripts/bootstrap.sh DELETED
@@ -1,20 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Fetch (or update) the code and start the pipeline detached from the calling shell.
3
- # bash bootstrap.sh run everything that is not done yet
4
- # STAGES="train eval_main" bash bootstrap.sh
5
- set -euo pipefail
6
- export EMC_ROOT="${EMC_ROOT:-$HOME/emc}"
7
- mkdir -p "$EMC_ROOT/logs"
8
- if [ -d "$EMC_ROOT/repo/.git" ]; then
9
- git -C "$EMC_ROOT/repo" pull -q --ff-only || true
10
- else
11
- git clone -q https://github.com/Mudassiruddin7/EMC.git "$EMC_ROOT/repo"
12
- fi
13
- if [ -f "$EMC_ROOT/pipeline.pid" ] && kill -0 "$(cat "$EMC_ROOT/pipeline.pid")" 2>/dev/null; then
14
- echo "pipeline already running (pid $(cat "$EMC_ROOT/pipeline.pid"))"; exit 0
15
- fi
16
- launcher=(nohup)
17
- command -v setsid >/dev/null && launcher=(setsid nohup)
18
- "${launcher[@]}" bash "$EMC_ROOT/repo/scripts/pipeline.sh" >> "$EMC_ROOT/logs/pipeline.out" 2>&1 < /dev/null &
19
- echo $! > "$EMC_ROOT/pipeline.pid"
20
- echo "pipeline started (pid $!); progress: tail -f $EMC_ROOT/logs/pipeline.log"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/collect.py CHANGED
@@ -49,10 +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
- for name in ("datagen_checks", ):
53
- p = RES / f"{name}.json"
54
- if p.exists():
55
- out[name] = json.loads(p.read_text())
56
  for p in sorted(ROOT.glob("runs/*/train_summary.json")):
57
  t = json.loads(p.read_text())
58
  out.setdefault("training", {})[p.parent.name] = {k: t.get(k) for k in ("data", "sim", "best_step", "train_seconds", "equalize", "export_fp8", "export_bf16")}
 
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
+ for p in sorted(RES.glob("*_checks.json")) + sorted(RES.glob("generation.json")):
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())
56
  out.setdefault("training", {})[p.parent.name] = {k: t.get(k) for k in ("data", "sim", "best_step", "train_seconds", "equalize", "export_fp8", "export_bf16")}
scripts/launch.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Start the unattended pipeline on a GPU machine, or show its status if it is already running.
2
+
3
+ From a notebook cell (or `python3 launch.py` in a shell):
4
+
5
+ import os as _os, urllib.request as _u
6
+ _os.environ["HF_TOKEN"] = "<Hugging Face write token>" # needed once; kept in a private file
7
+ exec(_u.urlopen("https://raw.githubusercontent.com/Mudassiruddin7/EMC/main/scripts/launch.py").read(),
8
+ {"__name__": "__main__"})
9
+
10
+ Picks the writable folder with the most free space, stores the token (mode 600), fetches the
11
+ `uv` tool if needed and starts scripts/supervise.py in its own session, so it keeps running
12
+ after the cell returns. Re-running the cell only prints the status.
13
+ """
14
+ import io
15
+ import os
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ import tarfile
21
+ import urllib.request
22
+ from pathlib import Path
23
+
24
+ SOURCE = "Mudassiruddin7/EMC"
25
+
26
+
27
+ def pick_root():
28
+ if os.environ.get("EMC_ROOT"):
29
+ return Path(os.environ["EMC_ROOT"])
30
+ for c in (Path.cwd(), Path.home(), Path("/workspace"), Path("/data"), Path("/mnt/data"), Path("/mnt"), Path("/tmp")):
31
+ if (c / "emc" / "supervisor.pid").exists():
32
+ return c / "emc"
33
+ best, free = Path.home(), -1
34
+ for c in (Path.cwd(), Path.home(), Path("/workspace"), Path("/data"), Path("/mnt/data"), Path("/mnt"), Path("/tmp")):
35
+ try:
36
+ if c.is_dir() and os.access(c, os.W_OK) and shutil.disk_usage(c).free > free:
37
+ best, free = c, shutil.disk_usage(c).free
38
+ except OSError:
39
+ pass
40
+ return best / "emc"
41
+
42
+
43
+ def get_uv(root):
44
+ found = shutil.which("uv")
45
+ if found:
46
+ return found
47
+ exe = root / "tools" / "uv"
48
+ if not exe.exists():
49
+ exe.parent.mkdir(parents=True, exist_ok=True)
50
+ url = "https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-unknown-linux-gnu.tar.gz"
51
+ with tarfile.open(fileobj=io.BytesIO(urllib.request.urlopen(url, timeout=300).read())) as tf:
52
+ for m in tf.getmembers():
53
+ if m.isfile() and Path(m.name).name in ("uv", "uvx"):
54
+ p = exe.parent / Path(m.name).name
55
+ p.write_bytes(tf.extractfile(m).read())
56
+ p.chmod(0o755)
57
+ return str(exe)
58
+
59
+
60
+ def alive(pidfile):
61
+ try:
62
+ os.kill(int(pidfile.read_text()), 0)
63
+ return True
64
+ except (OSError, ValueError):
65
+ return False
66
+
67
+
68
+ def status(root):
69
+ print(f"working folder : {root} ({shutil.disk_usage(root).free / 1e9:.0f} GB free)")
70
+ print(f"supervisor : {'running' if alive(root / 'supervisor.pid') else 'not running'}")
71
+ try:
72
+ print("GPU :", subprocess.run(["nvidia-smi", "--query-gpu=name,memory.used,memory.total,utilization.gpu",
73
+ "--format=csv,noheader"], capture_output=True, text=True,
74
+ timeout=20).stdout.strip())
75
+ except Exception: # noqa: BLE001
76
+ pass
77
+ done = sorted(p.stem for p in (root / "state").glob("*.done"))
78
+ failed = sorted(p.stem for p in (root / "state").glob("*.failed"))
79
+ print("stages done :", " ".join(done) or "-")
80
+ if failed:
81
+ print("stages failed :", " ".join(failed))
82
+ for name in ("pipeline.log", "supervisor.log"):
83
+ p = root / "logs" / name
84
+ if p.exists():
85
+ print(f"--- last lines of {name}")
86
+ print("\n".join(p.read_text(errors="replace").splitlines()[-12:]))
87
+
88
+
89
+ def main():
90
+ root = pick_root()
91
+ for sub in ("logs", "state", "tmp"):
92
+ (root / sub).mkdir(parents=True, exist_ok=True)
93
+ token = os.environ.get("HF_TOKEN", "").strip()
94
+ if token.startswith("hf_"):
95
+ p = root / ".hf_token"
96
+ p.write_text(token)
97
+ p.chmod(0o600)
98
+ if os.environ.get("EMC_SCRUB"):
99
+ (root / ".scrub").write_text(os.environ["EMC_SCRUB"])
100
+ if not alive(root / "supervisor.pid"):
101
+ uv = get_uv(root)
102
+ req = urllib.request.Request(f"https://github.com/{SOURCE}.git/info/refs?service=git-upload-pack",
103
+ headers={"User-Agent": "git/2.45.0"})
104
+ sha = re.search(r"([0-9a-f]{40}) refs/heads/main", urllib.request.urlopen(req, timeout=30)
105
+ .read().decode("latin-1")).group(1)
106
+ sup = root / "supervise.py"
107
+ sup.write_bytes(urllib.request.urlopen(
108
+ f"https://raw.githubusercontent.com/{SOURCE}/{sha}/scripts/supervise.py", timeout=60).read())
109
+ env = {k: v for k, v in os.environ.items() if k != "HF_TOKEN"}
110
+ env.update(EMC_ROOT=str(root), UV=uv, RUN_ID=os.environ.get("RUN_ID", "r1"))
111
+ with open(root / "logs" / "supervisor.log", "a") as out:
112
+ proc = subprocess.Popen([sys.executable, str(sup)], stdout=out, stderr=subprocess.STDOUT,
113
+ stdin=subprocess.DEVNULL, env=env, cwd=str(root), start_new_session=True)
114
+ (root / "supervisor.pid").write_text(str(proc.pid))
115
+ print(f"started the supervisor (pid {proc.pid}); re-run this cell any time to see progress\n")
116
+ status(root)
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()
scripts/pipeline.sh CHANGED
@@ -1,119 +1,155 @@
1
  #!/usr/bin/env bash
2
- # End-to-end pipeline on one GPU: environment -> baseline checks -> data -> training -> evaluation.
3
- # Every stage is resumable (state/<stage>.done) and logs to logs/<stage>.log; logs and results
4
- # are pushed to the Hugging Face dataset repo after each stage when a token is available.
5
- #
6
- # EMC_ROOT working folder (default: ~/emc)
7
- # STAGES optional space-separated subset of stages to run
8
- # GEN_MINUTES / TRAIN_MINUTES / GEN_BATCH / TRAIN_EPOCHS budgets (see emcdraft/*.py)
9
  set -uo pipefail
10
 
11
  export EMC_ROOT="${EMC_ROOT:-$HOME/emc}"
12
- REPO="$EMC_ROOT/repo"; KIT="$EMC_ROOT/kit"; MODELS="$EMC_ROOT/models"; WORK="$EMC_ROOT/work"
13
- TARGET="$MODELS/target"; BASELINE="$MODELS/baseline-mtp"; DATA="$EMC_ROOT/data"; RUNS="$EMC_ROOT/runs"
14
- STATE="$EMC_ROOT/state"; LOGS="$EMC_ROOT/logs"; VENV="$EMC_ROOT/venv"; RESULTS="$EMC_ROOT/results"
15
- mkdir -p "$MODELS" "$WORK" "$DATA" "$RUNS" "$STATE" "$LOGS" "$RESULTS"
16
- export PATH="$VENV/bin:$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
17
- export PYTHONPATH="$REPO${PYTHONPATH:+:$PYTHONPATH}" PYTHONUNBUFFERED=1
18
- export TOKENIZERS_PARALLELISM=false HF_HUB_DISABLE_TELEMETRY=1 EMC2_HOME="$KIT" EMC_RESULTS="$RESULTS"
19
- [ -f "$STATE/run_id" ] || date +%Y%m%d-%H%M > "$STATE/run_id"
20
- PY="$VENV/bin/python"
 
 
 
 
21
 
22
- log() { echo "[$(date +%H:%M:%S)] $*" | tee -a "$LOGS/pipeline.log"; }
23
- sync_hf() { [ -x "$PY" ] && "$PY" "$REPO/scripts/sync.py" "$@" >> "$LOGS/sync.log" 2>&1 || true; }
24
- wanted() { [ -z "${STAGES:-}" ] || [[ " $STAGES " == *" $1 "* ]]; }
25
 
26
- stage() { # stage <name> <required:0|1> <function>
27
- local name=$1 required=$2; shift 2
28
- wanted "$name" || return 0
29
- if [ -f "$STATE/$name.done" ]; then log "skip $name (already done)"; return 0; fi
30
- log "start $name"; local t0=$SECONDS rc=0
31
- ( set -e; "$@" ) > "$LOGS/$name.log" 2>&1
32
  rc=$?
33
  if [ "$rc" = 0 ]; then
34
  echo $((SECONDS - t0)) > "$STATE/$name.done"; rm -f "$STATE/$name.failed"
35
  log "done $name ($((SECONDS - t0))s)"
36
  else
37
- echo $((SECONDS - t0)) > "$STATE/$name.failed"
38
- log "FAIL $name ($((SECONDS - t0))s); last lines of logs/$name.log:"
39
- tail -n 30 "$LOGS/$name.log" | tee -a "$LOGS/pipeline.log"
40
- sync_hf
41
- if [ "$required" = 1 ]; then log "stopping: $name is required"; exit 1; fi
42
- return 1
43
  fi
44
  sync_hf
 
 
45
  }
46
 
47
- kit() {
48
- env EMC_TARGET="$TARGET" EMC_SUB="${SUB:-$BASELINE}" EMC2_WORK="$WORK" EMC_TAG="${EMC_TAG:-}" \
49
  "$PY" "$REPO/scripts/kit.py" "$@"
50
  }
51
 
52
  s_env() {
53
- nvidia-smi || true; df -h "$EMC_ROOT" || true; free -g || true; nproc || true
54
- if ! command -v uv >/dev/null; then
55
- python3 -m pip install -q --user uv || pip install -q uv || curl -LsSf https://astral.sh/uv/install.sh | sh
56
- fi
57
- [ -x "$PY" ] || uv venv --python 3.12 "$VENV"
58
- uv pip install --python "$PY" "vllm==0.31.0" --torch-backend=auto || uv pip install --python "$PY" "vllm==0.31.0"
59
- uv pip install --python "$PY" accelerate datasets safetensors numpy "huggingface_hub[cli]"
60
- "$PY" -c "import vllm, torch, transformers; print('vllm', vllm.__version__, '| torch', torch.__version__, '| cuda', torch.version.cuda, '| transformers', transformers.__version__); print(torch.cuda.get_device_name(0), round(torch.cuda.mem_get_info(0)[1] / 2**30, 1), 'GiB')"
61
- command -v gcc || echo "note: no gcc on PATH"
 
 
 
 
62
  }
63
 
64
  s_download() {
65
- [ -d "$KIT/.git" ] || git clone -q https://github.com/emc2-competition/emc2-kit.git "$KIT"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  local rev; rev=$("$PY" -c "import json; print(json.load(open('$KIT/target.json'))['revision'])")
67
  "$VENV/bin/hf" download Qwen/Qwen3.8-27B --revision "$rev" --local-dir "$TARGET" \
68
- || "$PY" -c "from huggingface_hub import snapshot_download; snapshot_download('Qwen/Qwen3.8-27B', revision='$rev', local_dir='$TARGET')"
69
- du -sh "$TARGET"
70
  }
71
 
72
- s_baseline() { kit prepare-baseline --models-dir "$MODELS" && SUB="$BASELINE" kit validate; }
73
  s_checkenv() { kit check-env; }
74
- s_probe() { "$PY" -m emcdraft.probe --target "$TARGET" --baseline "$BASELINE" --out "$MODELS/probe-fp8" && SUB="$MODELS/probe-fp8" kit validate; }
75
- s_smoke_base() { SUB="$BASELINE" EMC_TAG=smoke_baseline kit eval --limit-per-domain 2; }
76
- s_smoke_fp8() {
77
- SUB="$MODELS/probe-fp8" EMC_TAG=smoke_fp8 kit eval --limit-per-domain 2 || return 1
78
- "$PY" - <<EOF
79
- import json
80
- b = json.load(open("$RESULTS/smoke_baseline.json")); f = json.load(open("$RESULTS/smoke_fp8.json"))
 
 
81
  ratio = (f["acceptance_length"] - 1) / (b["acceptance_length"] - 1)
82
- print(f"FP8 probe: acceptance {f['acceptance_length']:.3f} vs baseline {b['acceptance_length']:.3f} (ratio {ratio:.3f})")
83
- if ratio >= 0.93: open("$STATE/fp8_ok", "w").write(f"{ratio:.4f}\n")
 
 
 
84
  EOF
85
  }
86
- s_datagen() { "$PY" -m emcdraft.datagen --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --out "$DATA" --results "$RESULTS"; }
 
 
 
87
  s_train() {
88
  local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"
89
- "$PY" -m emcdraft.train --target "$TARGET" --init "$BASELINE" --data "$DATA/train" --dev "$DATA/dev" --out "$RUNS/main" $qat \
90
- && for s in "$RUNS"/main/sub_*; do SUB="$s" kit validate; done
 
91
  }
92
  primary() { if [ -d "$RUNS/main/sub_fp8" ]; then echo "$RUNS/main/sub_fp8"; else echo "$RUNS/main/sub_bf16"; fi; }
93
- s_eval_main() { SUB="$(primary)" EMC_TAG="eval_$(basename "$(primary)" | sed 's/sub_/draft_/')" kit eval; }
94
- s_eval_baseline() { SUB="$BASELINE" EMC_TAG=eval_baseline kit eval; }
95
  s_eval_alt() {
96
- [ -d "$RUNS/main/sub_fp8" ] || { echo "no second variant"; return 0; }
97
- SUB="$RUNS/main/sub_bf16" EMC_TAG=eval_draft_bf16 kit eval
98
  }
99
  s_report() { "$PY" "$REPO/scripts/collect.py"; }
100
 
101
- log "pipeline start (root $EMC_ROOT, run $(cat "$STATE/run_id"))"
102
  stage env 1 s_env
103
  stage download 1 s_download
104
  stage baseline 1 s_baseline
105
- stage checkenv 0 s_checkenv
106
- stage probe 0 s_probe
107
- stage smoke_base 0 s_smoke_base
108
- stage smoke_fp8 0 s_smoke_fp8
109
- stage datagen 1 s_datagen
 
 
 
 
 
110
  stage train 1 s_train
111
  sync_hf --submissions
112
- stage eval_main 0 s_eval_main
113
- stage report_1 0 s_report
114
- stage eval_baseline 0 s_eval_baseline
115
- stage report_2 0 s_report
116
- stage eval_alt 0 s_eval_alt
117
- stage report 0 s_report
118
  sync_hf --submissions
119
  log "pipeline finished"
 
1
  #!/usr/bin/env bash
2
+ # End-to-end pipeline on one GPU:
3
+ # environment -> target + baseline -> engine checks -> prompts -> generation (engine)
4
+ # -> hidden states -> training -> official kit evaluation -> summary
5
+ # Each stage is resumable (state/<stage>.done) and logs to logs/<stage>.log. Logs and results
6
+ # are pushed to the Hugging Face dataset repo after every stage (scripts/sync.py).
7
+ # Normally started by scripts/supervise.py; can also be run directly.
 
8
  set -uo pipefail
9
 
10
  export EMC_ROOT="${EMC_ROOT:-$HOME/emc}"
11
+ REPO="${EMC_REPO:-$EMC_ROOT/repo}"
12
+ KIT="$EMC_ROOT/kit"; MODELS="$EMC_ROOT/models"; WORK="$EMC_ROOT/work"; DATA="$EMC_ROOT/data"
13
+ TARGET="$MODELS/target"; BASELINE="$MODELS/baseline-mtp"; PROBE="$MODELS/probe-fp8"
14
+ RUNS="$EMC_ROOT/runs"; STATE="$EMC_ROOT/state"; LOGS="$EMC_ROOT/logs"; RESULTS="$EMC_ROOT/results"
15
+ VENV="$EMC_ROOT/venv"; PY="$VENV/bin/python"; UV="${UV:-uv}"
16
+ KIT_SHA=de57e284ae1b3d72ed7e06f00e030b2ba797adf1
17
+ mkdir -p "$MODELS" "$WORK" "$DATA" "$RUNS" "$STATE" "$LOGS" "$RESULTS" "$EMC_ROOT/tmp"
18
+ export PATH="$VENV/bin:$PATH" PYTHONPATH="$REPO" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
19
+ export TOKENIZERS_PARALLELISM=false HF_HUB_DISABLE_TELEMETRY=1 HF_HUB_DISABLE_PROGRESS_BARS=1
20
+ export HF_HOME="$EMC_ROOT/hf" HF_XET_CHUNK_CACHE_SIZE_BYTES=0 TMPDIR="$EMC_ROOT/tmp"
21
+ export UV_CACHE_DIR="$EMC_ROOT/uv-cache" UV_PYTHON_INSTALL_DIR="$EMC_ROOT/uv-python" UV_LINK_MODE=copy
22
+ export EMC2_HOME="$KIT" EMC_RESULTS="$RESULTS"
23
+ [ -f "$STATE/run_id" ] || echo "${RUN_ID:-$(date +%Y%m%d-%H%M)}" > "$STATE/run_id"
24
 
25
+ log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOGS/pipeline.log"; }
26
+ sync_hf() { if [ -x "$PY" ]; then "$PY" "$REPO/scripts/sync.py" "$@" >> "$LOGS/sync.log" 2>&1 || true; fi; }
27
+ is_done() { [ -f "$STATE/$1.done" ]; }
28
 
29
+ stage() { # stage <name> <required: 0|1> <function>
30
+ local name=$1 required=$2 fn=$3 t0=$SECONDS rc
31
+ if is_done "$name"; then log "skip $name (done)"; return 0; fi
32
+ log "start $name"
33
+ ( set -e; "$fn" ) > "$LOGS/$name.log" 2>&1
 
34
  rc=$?
35
  if [ "$rc" = 0 ]; then
36
  echo $((SECONDS - t0)) > "$STATE/$name.done"; rm -f "$STATE/$name.failed"
37
  log "done $name ($((SECONDS - t0))s)"
38
  else
39
+ echo "exit $rc after $((SECONDS - t0))s" > "$STATE/$name.failed"
40
+ log "FAIL $name (exit $rc after $((SECONDS - t0))s); end of logs/$name.log:"
41
+ tail -n 25 "$LOGS/$name.log" | sed 's/^/ /' | tee -a "$LOGS/pipeline.log"
 
 
 
42
  fi
43
  sync_hf
44
+ if [ "$rc" != 0 ] && [ "$required" = 1 ]; then log "stopping: $name is required"; exit 1; fi
45
+ return "$rc"
46
  }
47
 
48
+ kit() { # the official kit commands (scripts/kit.py only maps its container paths)
49
+ env EMC_TARGET="$TARGET" EMC_SUB="${SUB:-$BASELINE}" EMC2_WORK="$WORK" EMC_TAG="${TAG:-}" \
50
  "$PY" "$REPO/scripts/kit.py" "$@"
51
  }
52
 
53
  s_env() {
54
+ nvidia-smi || true
55
+ df -h "$EMC_ROOT" || true; free -g || true; nproc || true
56
+ [ -x "$PY" ] || "$UV" venv --python 3.12 "$VENV"
57
+ "$UV" pip install --python "$PY" "vllm==0.31.0" accelerate datasets
58
+ "$UV" cache clean >/dev/null 2>&1 || true
59
+ "$PY" - <<'EOF'
60
+ import torch, transformers, vllm
61
+ print("vllm", vllm.__version__, "| torch", torch.__version__, "cuda", torch.version.cuda,
62
+ "| transformers", transformers.__version__)
63
+ print(torch.cuda.get_device_name(0), round(torch.cuda.mem_get_info(0)[1] / 2**30, 1), "GiB")
64
+ x = torch.randn(512, 512, device="cuda", dtype=torch.bfloat16)
65
+ print("bf16 matmul ok:", bool(torch.isfinite((x @ x).float()).all()))
66
+ EOF
67
  }
68
 
69
  s_download() {
70
+ if [ ! -f "$KIT/contract.json" ]; then
71
+ "$PY" - "https://codeload.github.com/emc2-competition/emc2-kit/tar.gz/$KIT_SHA" "$KIT" <<'EOF'
72
+ import io, sys, tarfile, urllib.request
73
+ from pathlib import Path
74
+ data = urllib.request.urlopen(sys.argv[1], timeout=300).read()
75
+ dst = Path(sys.argv[2]); dst.mkdir(parents=True, exist_ok=True)
76
+ with tarfile.open(fileobj=io.BytesIO(data)) as tf:
77
+ ms = []
78
+ for m in tf.getmembers():
79
+ if "/" in m.name and m.name.split("/", 1)[1]:
80
+ m.name = m.name.split("/", 1)[1]; ms.append(m)
81
+ try:
82
+ tf.extractall(dst, members=ms, filter="data")
83
+ except TypeError:
84
+ tf.extractall(dst, members=ms)
85
+ print("kit ready:", sorted(p.name for p in dst.iterdir()))
86
+ EOF
87
+ fi
88
  local rev; rev=$("$PY" -c "import json; print(json.load(open('$KIT/target.json'))['revision'])")
89
  "$VENV/bin/hf" download Qwen/Qwen3.8-27B --revision "$rev" --local-dir "$TARGET" \
90
+ || "$PY" -c "from huggingface_hub import snapshot_download as s; s('Qwen/Qwen3.8-27B', revision='$rev', local_dir='$TARGET')"
91
+ du -sh "$TARGET"; df -h "$EMC_ROOT"
92
  }
93
 
94
+ s_baseline() { kit prepare-baseline --models-dir "$MODELS"; SUB="$BASELINE" kit validate; }
95
  s_checkenv() { kit check-env; }
96
+ s_probe() {
97
+ "$PY" -m emcdraft.probe --target "$TARGET" --baseline "$BASELINE" --out "$PROBE"
98
+ SUB="$PROBE" kit validate
99
+ }
100
+ s_smoke_fp8() { # does the stock engine load an FP8-typed head, and what does rounding alone cost?
101
+ SUB="$PROBE" TAG=smoke_fp8 kit eval --limit-per-domain 2
102
+ "$PY" - "$RESULTS/smoke_fp8.json" "$KIT/data/dev/baseline.json" "$STATE/fp8_ok" <<'EOF'
103
+ import json, sys
104
+ f, b = json.load(open(sys.argv[1])), json.load(open(sys.argv[2]))
105
  ratio = (f["acceptance_length"] - 1) / (b["acceptance_length"] - 1)
106
+ print(f"FP8 probe acceptance {f['acceptance_length']:.3f} vs published baseline {b['acceptance_length']:.3f} (ratio {ratio:.3f})")
107
+ if ratio >= 0.85:
108
+ open(sys.argv[3], "w").write(f"{ratio:.4f}\n")
109
+ else:
110
+ print("acceptance collapsed: FP8 storage will not be used")
111
  EOF
112
  }
113
+ s_smoke_base() { SUB="$BASELINE" TAG=smoke_baseline kit eval --limit-per-domain 2; }
114
+ s_prompts() { "$PY" -m emcdraft.prompts --target "$TARGET" --kit "$KIT" --out "$DATA/prompts" --results "$RESULTS"; }
115
+ s_generate() { "$PY" -m emcdraft.gen_vllm --target "$TARGET" --prompts "$DATA/prompts" --out "$DATA/gen" --results "$RESULTS"; }
116
+ s_extract() { "$PY" -m emcdraft.extract --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --gen "$DATA/gen" --out "$DATA" --results "$RESULTS"; }
117
  s_train() {
118
  local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"
119
+ rm -rf "$RUNS/main"
120
+ "$PY" -m emcdraft.train --target "$TARGET" --init "$BASELINE" --data "$DATA/train" --dev "$DATA/dev" --out "$RUNS/main" $qat
121
+ for s in "$RUNS"/main/sub_*; do SUB="$s" kit validate; done
122
  }
123
  primary() { if [ -d "$RUNS/main/sub_fp8" ]; then echo "$RUNS/main/sub_fp8"; else echo "$RUNS/main/sub_bf16"; fi; }
124
+ s_eval_main() { local p; p=$(primary); SUB="$p" TAG="eval_draft_$(basename "$p" | sed 's/^sub_//')" kit eval; }
125
+ s_eval_baseline() { SUB="$BASELINE" TAG=eval_baseline kit eval; }
126
  s_eval_alt() {
127
+ if [ ! -d "$RUNS/main/sub_fp8" ]; then echo "only one variant"; return 0; fi
128
+ SUB="$RUNS/main/sub_bf16" TAG=eval_draft_bf16 kit eval
129
  }
130
  s_report() { "$PY" "$REPO/scripts/collect.py"; }
131
 
132
+ log "pipeline start: run $(cat "$STATE/run_id"), code $(cat "$REPO/.commit" 2>/dev/null | cut -c1-12)"
133
  stage env 1 s_env
134
  stage download 1 s_download
135
  stage baseline 1 s_baseline
136
+ prompts_pid=""
137
+ if ! is_done prompts; then (stage prompts 1 s_prompts) & prompts_pid=$!; fi
138
+ stage checkenv 0 s_checkenv || true
139
+ stage probe 0 s_probe || true
140
+ if is_done probe; then stage smoke_fp8 0 s_smoke_fp8 || true; fi
141
+ if ! is_done smoke_fp8; then stage smoke_base 1 s_smoke_base; fi # engine itself must work
142
+ if [ -n "$prompts_pid" ]; then wait "$prompts_pid"; fi
143
+ is_done prompts || { log "stopping: prompts failed"; exit 1; }
144
+ stage generate 1 s_generate
145
+ stage extract 1 s_extract
146
  stage train 1 s_train
147
  sync_hf --submissions
148
+ stage eval_main 0 s_eval_main || true
149
+ stage report_main 0 s_report || true
150
+ stage eval_baseline 0 s_eval_baseline || true
151
+ stage report_baseline 0 s_report || true
152
+ stage eval_alt 0 s_eval_alt || true
153
+ stage report 0 s_report || true
154
  sync_hf --submissions
155
  log "pipeline finished"
scripts/supervise.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Unattended driver for scripts/pipeline.sh (standard library only).
3
+
4
+ Every minute it asks the public code repository for the head of the branch. When it moved,
5
+ the new code is installed as a fresh snapshot behind the `repo` symlink (running processes are
6
+ not disturbed). It then applies control requests committed to the repository and (re)starts
7
+ the pipeline when it is not running and either the code changed or a reset asked for it:
8
+
9
+ control/reset.txt lines "<id> [kill] <stage> ..." - forget those stages so they run again
10
+ ("kill" first stops a running pipeline); each id is applied once
11
+ control/run.env KEY=VALUE lines passed to the pipeline (budgets etc.)
12
+
13
+ While the pipeline runs, logs are pushed every 10 minutes. Create $EMC_ROOT/STOP to end it.
14
+ """
15
+ import io
16
+ import os
17
+ import re
18
+ import shutil
19
+ import signal
20
+ import subprocess
21
+ import tarfile
22
+ import time
23
+ import urllib.request
24
+ from pathlib import Path
25
+
26
+ ROOT = Path(os.environ.get("EMC_ROOT", str(Path.home() / "emc"))).resolve()
27
+ SOURCE = os.environ.get("EMC_SOURCE", "Mudassiruddin7/EMC")
28
+ BRANCH = os.environ.get("EMC_BRANCH", "main")
29
+ UV = os.environ.get("UV", "uv")
30
+ LOGS, STATE, CODE = ROOT / "logs", ROOT / "state", ROOT / "code"
31
+ VENV_PY = ROOT / "venv" / "bin" / "python"
32
+
33
+
34
+ def log(msg):
35
+ print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}", flush=True)
36
+
37
+
38
+ def tool_env():
39
+ return dict(os.environ, UV_CACHE_DIR=str(ROOT / "uv-cache"), UV_PYTHON_INSTALL_DIR=str(ROOT / "uv-python"),
40
+ UV_LINK_MODE="copy", TMPDIR=str(ROOT / "tmp"), HF_HOME=str(ROOT / "hf"))
41
+
42
+
43
+ def remote_sha():
44
+ req = urllib.request.Request(f"https://github.com/{SOURCE}.git/info/refs?service=git-upload-pack",
45
+ headers={"User-Agent": "git/2.45.0"})
46
+ body = urllib.request.urlopen(req, timeout=30).read().decode("latin-1")
47
+ m = re.search(r"([0-9a-f]{40}) refs/heads/" + re.escape(BRANCH) + r"(?![\w./-])", body)
48
+ return m.group(1) if m else None
49
+
50
+
51
+ def install(sha):
52
+ dest = CODE / sha[:12]
53
+ if not dest.exists():
54
+ data = urllib.request.urlopen(f"https://codeload.github.com/{SOURCE}/tar.gz/{sha}", timeout=300).read()
55
+ tmp = CODE / f".{sha[:12]}.tmp"
56
+ shutil.rmtree(tmp, ignore_errors=True)
57
+ tmp.mkdir(parents=True)
58
+ with tarfile.open(fileobj=io.BytesIO(data)) as tf:
59
+ members = []
60
+ for m in tf.getmembers():
61
+ name = m.name.split("/", 1)[1] if "/" in m.name else ""
62
+ if name and not name.startswith("/") and ".." not in Path(name).parts:
63
+ m.name = name
64
+ members.append(m)
65
+ try:
66
+ tf.extractall(tmp, members=members, filter="data")
67
+ except TypeError:
68
+ tf.extractall(tmp, members=members)
69
+ (tmp / ".commit").write_text(sha + "\n")
70
+ tmp.rename(dest)
71
+ link = ROOT / "repo"
72
+ if link.exists() and not link.is_symlink():
73
+ link.rename(CODE / f"legacy-{int(time.time())}")
74
+ tmp_link = ROOT / ".repo-link"
75
+ if tmp_link.is_symlink() or tmp_link.exists():
76
+ tmp_link.unlink()
77
+ tmp_link.symlink_to(dest, target_is_directory=True)
78
+ os.replace(tmp_link, link)
79
+
80
+
81
+ def ensure_venv():
82
+ """A private Python with huggingface_hub, so logs can be pushed from the very first stage."""
83
+ if not VENV_PY.exists():
84
+ subprocess.run([UV, "venv", "--python", "3.12", str(ROOT / "venv")], check=True, env=tool_env())
85
+ subprocess.run([UV, "pip", "install", "--python", str(VENV_PY), "huggingface_hub"], check=True,
86
+ env=tool_env(), stdout=subprocess.DEVNULL)
87
+
88
+
89
+ def read_control():
90
+ env, resets = {}, []
91
+ p = ROOT / "repo" / "control" / "run.env"
92
+ if p.exists():
93
+ for line in p.read_text().splitlines():
94
+ line = line.strip()
95
+ if line and not line.startswith("#") and "=" in line:
96
+ k, v = line.split("=", 1)
97
+ env[k.strip()] = v.strip()
98
+ applied = set((STATE / "applied_resets").read_text().split()) if (STATE / "applied_resets").exists() else set()
99
+ p = ROOT / "repo" / "control" / "reset.txt"
100
+ if p.exists():
101
+ for line in p.read_text().splitlines():
102
+ parts = line.split()
103
+ if parts and not parts[0].startswith("#") and parts[0] not in applied:
104
+ resets.append((parts[0], "kill" in parts[1:], [s for s in parts[1:] if s != "kill"]))
105
+ return env, resets
106
+
107
+
108
+ def stop(proc):
109
+ try:
110
+ os.killpg(proc.pid, signal.SIGTERM)
111
+ proc.wait(timeout=90)
112
+ except subprocess.TimeoutExpired:
113
+ os.killpg(proc.pid, signal.SIGKILL)
114
+ proc.wait()
115
+ except ProcessLookupError:
116
+ pass
117
+
118
+
119
+ def sync():
120
+ if VENV_PY.exists() and (ROOT / "repo" / "scripts" / "sync.py").exists():
121
+ with open(LOGS / "sync.log", "a") as f:
122
+ subprocess.run([str(VENV_PY), str(ROOT / "repo" / "scripts" / "sync.py")], stdout=f,
123
+ stderr=subprocess.STDOUT, env=dict(tool_env(), EMC_ROOT=str(ROOT)), timeout=1200)
124
+
125
+
126
+ def start_pipeline(extra):
127
+ run_sh = ROOT / "pipeline.run.sh" # a copy: bash reads scripts while running them
128
+ shutil.copy(ROOT / "repo" / "scripts" / "pipeline.sh", run_sh)
129
+ env = tool_env()
130
+ env.update(extra)
131
+ env.update(EMC_ROOT=str(ROOT), EMC_REPO=str(ROOT / "repo"), UV=UV)
132
+ out = open(LOGS / "pipeline.out", "a")
133
+ return subprocess.Popen(["bash", str(run_sh)], stdout=out, stderr=subprocess.STDOUT,
134
+ stdin=subprocess.DEVNULL, env=env, cwd=str(ROOT), start_new_session=True)
135
+
136
+
137
+ def main():
138
+ for d in (LOGS, STATE, CODE, ROOT / "tmp"):
139
+ d.mkdir(parents=True, exist_ok=True)
140
+ (ROOT / "supervisor.pid").write_text(str(os.getpid()))
141
+ if os.environ.get("RUN_ID") and not (STATE / "run_id").exists():
142
+ (STATE / "run_id").write_text(os.environ["RUN_ID"] + "\n")
143
+ head = ROOT / "repo" / ".commit"
144
+ current = head.read_text().strip() if head.exists() else ""
145
+ ran = (STATE / "pipeline_commit").read_text().strip() if (STATE / "pipeline_commit").exists() else ""
146
+ # force: (re)start the pipeline once on every supervisor start - finished stages are skipped,
147
+ # and a machine restart in the middle of a stage resumes there.
148
+ proc, last_sync, force, reported, venv_ok = None, 0.0, True, True, False
149
+ log(f"supervisor started in {ROOT}")
150
+ while not (ROOT / "STOP").exists():
151
+ try:
152
+ sha = remote_sha()
153
+ if sha and sha != current:
154
+ install(sha)
155
+ current = sha
156
+ log(f"code updated to {sha[:12]}")
157
+ except Exception as e: # noqa: BLE001 - network hiccups are retried next minute
158
+ log(f"code check failed: {type(e).__name__}: {e}")
159
+ if not venv_ok:
160
+ try:
161
+ ensure_venv()
162
+ venv_ok = True
163
+ except Exception as e: # noqa: BLE001
164
+ log(f"python environment not ready yet: {e}")
165
+ env, resets = read_control()
166
+ running = proc is not None and proc.poll() is None
167
+ for rid, kill, stages in resets:
168
+ if running and not kill:
169
+ continue
170
+ if running:
171
+ stop(proc)
172
+ running = False
173
+ log("pipeline stopped for a reset")
174
+ for s in stages:
175
+ for suffix in ("done", "failed"):
176
+ (STATE / f"{s}.{suffix}").unlink(missing_ok=True)
177
+ with open(STATE / "applied_resets", "a") as f:
178
+ f.write(rid + "\n")
179
+ log(f"reset {rid}: {' '.join(stages)}")
180
+ force = True
181
+ if not running:
182
+ if proc is not None and not reported:
183
+ log(f"pipeline exited with code {proc.returncode}")
184
+ reported = True
185
+ sync()
186
+ if current and (current != ran or force) and (ROOT / "repo").exists():
187
+ proc = start_pipeline(env)
188
+ ran, force, reported, last_sync = current, False, False, time.time()
189
+ (STATE / "pipeline_commit").write_text(current + "\n")
190
+ log(f"pipeline started (pid {proc.pid}) at {current[:12]}")
191
+ elif time.time() - last_sync > 600:
192
+ try:
193
+ sync()
194
+ except Exception as e: # noqa: BLE001
195
+ log(f"log push failed: {e}")
196
+ last_sync = time.time()
197
+ time.sleep(60)
198
+ log("stop requested")
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()
scripts/sync.py CHANGED
@@ -1,11 +1,11 @@
1
  #!/usr/bin/env python3
2
- """Push logs, results and (optionally) submission folders to the Hugging Face dataset repo.
3
 
4
- Reads the token from $HF_TOKEN, $EMC_ROOT/.hf_token, ~/.hf_token or the hub's cached login;
5
- without a token it does nothing (the run itself never depends on the upload).
6
 
7
- sync.py logs + results + state for the current run
8
- sync.py --submissions additionally upload every runs/*/sub_* folder (weights)
9
  """
10
  import os
11
  import re
@@ -14,27 +14,39 @@ import socket
14
  import sys
15
  from pathlib import Path
16
 
17
- ROOT = Path(os.environ.get("EMC_ROOT", Path.home() / "emc"))
 
 
 
 
 
18
  REPO_ID = os.environ.get("HF_REPO", "mudassiruddin21/EMC")
19
- TEXT = {".log", ".out", ".json", ".md", ".txt", ".done", ".failed"}
20
  SCRUB = [(re.compile(r"hf_[A-Za-z0-9]{16,}"), "hf_***"),
 
21
  (re.compile(re.escape(str(ROOT))), "/workspace/emc"),
22
  (re.compile(re.escape(str(Path.home()))), "/workspace"),
23
- (re.compile(re.escape(socket.gethostname())), "gpu-node")]
 
 
 
 
 
 
 
 
24
 
25
 
26
  def token():
27
  if os.environ.get("HF_TOKEN"):
28
  return os.environ["HF_TOKEN"].strip()
29
- for p in (ROOT / ".hf_token", Path.home() / ".hf_token"):
30
- if p.exists():
31
- return p.read_text().strip()
32
- return None
33
 
34
 
35
  def scrub_copy(src: Path, dst: Path):
36
  dst.parent.mkdir(parents=True, exist_ok=True)
37
- if src.suffix in TEXT and src.stat().st_size < 64 * 2 ** 20:
38
  text = src.read_text(errors="replace")
39
  for pat, rep in SCRUB:
40
  text = pat.sub(rep, text)
@@ -44,35 +56,37 @@ def scrub_copy(src: Path, dst: Path):
44
 
45
 
46
  def main():
47
- from huggingface_hub import HfApi
48
  tok = token()
49
- api = HfApi(token=tok)
50
- try:
51
- api.whoami()
52
- except Exception: # noqa: BLE001
53
- print("no usable Hugging Face token: skipping upload")
54
  return 0
 
 
55
  run_id = (ROOT / "state" / "run_id").read_text().strip() if (ROOT / "state" / "run_id").exists() else "run"
56
- stage = ROOT / "export"
57
- shutil.rmtree(stage, ignore_errors=True)
58
- for pattern, sub in (("logs/*", "logs"), ("results/*.json", "results"), ("results/*.md", "results"),
59
- ("state/*", "state"), ("work/logs/*.log", "engine_logs"),
60
- ("work/results/*.json", "kit_results"), ("runs/*/train_summary.json", "training")):
61
- for p in sorted(ROOT.glob(pattern)):
62
- if p.is_file():
63
- name = f"{p.parent.name}-{p.name}" if sub == "training" else p.name
64
- scrub_copy(p, stage / sub / name)
65
- if stage.exists():
66
- api.upload_folder(folder_path=str(stage), repo_id=REPO_ID, repo_type="dataset",
67
- path_in_repo=f"runs/{run_id}", commit_message=f"Run {run_id}: logs and results")
68
- print(f"uploaded logs/results to {REPO_ID}:runs/{run_id}")
69
- if "--submissions" in sys.argv:
70
- for sub in sorted(ROOT.glob("runs/*/sub_*")):
71
- name = f"{sub.parent.name}-{sub.name[4:]}"
72
- api.upload_folder(folder_path=str(sub), repo_id=REPO_ID, repo_type="dataset",
73
- path_in_repo=f"submissions/{run_id}/{name}",
74
- commit_message=f"Run {run_id}: draft model {name}")
75
- print(f"uploaded {sub} to {REPO_ID}:submissions/{run_id}/{name}")
 
 
 
 
76
  return 0
77
 
78
 
 
1
  #!/usr/bin/env python3
2
+ """Push logs, results and (optionally) the draft-model folders to the Hugging Face dataset repo.
3
 
4
+ The token comes from $HF_TOKEN or $EMC_ROOT/.hf_token; without one nothing is uploaded (the run
5
+ never depends on the upload). Paths and host names are scrubbed from text files.
6
 
7
+ sync.py logs + results + state + generated token data of the current run
8
+ sync.py --submissions additionally every runs/*/sub_* folder (weights)
9
  """
10
  import os
11
  import re
 
14
  import sys
15
  from pathlib import Path
16
 
17
+ try:
18
+ import fcntl
19
+ except ImportError: # not on Linux: no cross-process lock
20
+ fcntl = None
21
+
22
+ ROOT = Path(os.environ.get("EMC_ROOT", str(Path.home() / "emc")))
23
  REPO_ID = os.environ.get("HF_REPO", "mudassiruddin21/EMC")
24
+ TEXT = {".log", ".out", ".json", ".jsonl", ".md", ".txt", ".done", ".failed", ""}
25
  SCRUB = [(re.compile(r"hf_[A-Za-z0-9]{16,}"), "hf_***"),
26
+ (re.compile(re.escape(str(ROOT.resolve()))), "/workspace/emc"),
27
  (re.compile(re.escape(str(ROOT))), "/workspace/emc"),
28
  (re.compile(re.escape(str(Path.home()))), "/workspace"),
29
+ (re.compile(r"\b" + re.escape(socket.gethostname()) + r"\b"), "gpu-node")]
30
+ # extra words to keep out of published logs (comma separated), set at launch time
31
+ _words = os.environ.get("EMC_SCRUB") or ((ROOT / ".scrub").read_text() if (ROOT / ".scrub").exists() else "")
32
+ _words = [w.strip() for w in _words.split(",") if w.strip()]
33
+ if _words:
34
+ SCRUB.append((re.compile("|".join(map(re.escape, _words)), re.I), "host"))
35
+ PATTERNS = (("logs/*", "logs"), ("results/*.json", "results"), ("results/*.md", "results"),
36
+ ("state/*", "state"), ("work/logs/*.log", "engine_logs"), ("work/results/*.json", "kit_results"),
37
+ ("runs/*/train_summary.json", "training"), ("data/gen/*.jsonl", "data/gen"))
38
 
39
 
40
  def token():
41
  if os.environ.get("HF_TOKEN"):
42
  return os.environ["HF_TOKEN"].strip()
43
+ p = ROOT / ".hf_token"
44
+ return p.read_text().strip() if p.exists() else None
 
 
45
 
46
 
47
  def scrub_copy(src: Path, dst: Path):
48
  dst.parent.mkdir(parents=True, exist_ok=True)
49
+ if src.suffix in TEXT and src.stat().st_size < 64 * 2 ** 20 and src.suffix != ".jsonl":
50
  text = src.read_text(errors="replace")
51
  for pat, rep in SCRUB:
52
  text = pat.sub(rep, text)
 
56
 
57
 
58
  def main():
 
59
  tok = token()
60
+ if not tok:
61
+ print("no Hugging Face token: skipping upload")
 
 
 
62
  return 0
63
+ from huggingface_hub import HfApi
64
+ api = HfApi(token=tok)
65
  run_id = (ROOT / "state" / "run_id").read_text().strip() if (ROOT / "state" / "run_id").exists() else "run"
66
+ with open(ROOT / ".sync.lock", "w") as lock:
67
+ if fcntl:
68
+ fcntl.flock(lock, fcntl.LOCK_EX)
69
+ stage = ROOT / f"export-{os.getpid()}"
70
+ shutil.rmtree(stage, ignore_errors=True)
71
+ try:
72
+ for pattern, sub in PATTERNS:
73
+ for p in sorted(ROOT.glob(pattern)):
74
+ if p.is_file() and not p.name.startswith("."):
75
+ name = f"{p.parent.name}-{p.name}" if sub == "training" else p.name
76
+ scrub_copy(p, stage / sub / name)
77
+ if stage.exists():
78
+ api.upload_folder(folder_path=str(stage), repo_id=REPO_ID, repo_type="dataset",
79
+ path_in_repo=f"runs/{run_id}", commit_message=f"Run {run_id}: logs and results")
80
+ print(f"uploaded logs/results to {REPO_ID}:runs/{run_id}")
81
+ if "--submissions" in sys.argv:
82
+ for sub in sorted(ROOT.glob("runs/*/sub_*")):
83
+ name = f"{sub.parent.name}-{sub.name[4:]}"
84
+ api.upload_folder(folder_path=str(sub), repo_id=REPO_ID, repo_type="dataset",
85
+ path_in_repo=f"submissions/{run_id}/{name}",
86
+ commit_message=f"Run {run_id}: draft model {name}")
87
+ print(f"uploaded {sub.name} to {REPO_ID}:submissions/{run_id}/{name}")
88
+ finally:
89
+ shutil.rmtree(stage, ignore_errors=True)
90
  return 0
91
 
92
 
tests/test_head.py CHANGED
@@ -9,7 +9,8 @@ Checks the pieces whose correctness the whole pipeline rests on:
9
  3. `equalize_` leaves the head's function unchanged;
10
  4. `walk` reproduces a hand-checked acceptance count;
11
  5. a few training steps run, reduce the loss, and the exported folders pass the kit's
12
- static validation (when a kit checkout is given via EMC2_HOME).
 
13
  """
14
  import json
15
  import os
@@ -163,6 +164,39 @@ def test_train_and_export(head, E, W):
163
  print(" export: FP8 and bf16 folders round-trip" + (" and pass the kit's validate" if os.environ.get("EMC2_HOME") else ""))
164
 
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  if __name__ == "__main__":
167
  head = MTPHead(C)
168
  for p in head.parameters():
@@ -174,4 +208,5 @@ if __name__ == "__main__":
174
  print("equalize"); test_equalize(head, E)
175
  print("walk"); test_walk()
176
  print("train/export"); test_train_and_export(head, E, W)
 
177
  print("ALL OK")
 
9
  3. `equalize_` leaves the head's function unchanged;
10
  4. `walk` reproduces a hand-checked acceptance count;
11
  5. a few training steps run, reduce the loss, and the exported folders pass the kit's
12
+ static validation (when a kit checkout is given via EMC2_HOME);
13
+ 6. prompt helpers, batching and the supervisor's branch lookup (needs network) behave.
14
  """
15
  import json
16
  import os
 
164
  print(" export: FP8 and bf16 folders round-trip" + (" and pass the kit's validate" if os.environ.get("EMC2_HOME") else ""))
165
 
166
 
167
+ def test_helpers():
168
+ from emcdraft.extract import make_batches
169
+ from emcdraft.prompts import CODE_T, clean_story_prompt, drop_dev_overlap, make_stub
170
+ x = torch.randn(3, 1000) * 0.3
171
+ assert torch.equal(e4m3_encode(x, chunk=777), e4m3_encode(x)), "chunked FP8 encoding differs"
172
+ stub = make_stub("Write a function to add two numbers.", "def add(a, b):\n return a + b\n")
173
+ assert stub.startswith("def add(a, b):") and '"""Write a function' in stub, stub
174
+ assert make_stub("too short", "def f(): pass") is None
175
+ assert clean_story_prompt("[ WP ] You 've won the lottery , but there 's a catch .") == \
176
+ "You've won the lottery, but there's a catch."
177
+ assert clean_story_prompt("[ EU ] fan fiction") is None
178
+ dev = ["Complete the following Python function.\n\n```python\ndef strlen(string: str) -> int:\n```",
179
+ "Ruby is 6 times older than Sam. In 9 years, Ruby will be 3 times as old as Sam. How old is Sam now?"]
180
+ train = [CODE_T.format(stub="def strlen(s):\n pass\n"), CODE_T.format(stub="def other(s):\n pass\n"),
181
+ "Ruby is 6 times older than Sam. In 9 years, Ruby will be 3 times as old as Sam. How old is Sam now?"
182
+ "\n\nSolve this step by step, then give the final answer on its own line as 'Answer: <number>'."]
183
+ kept = drop_dev_overlap(train, dev)
184
+ assert kept == [train[1]], kept
185
+ seqs = [{"ids": [0] * n} for n in (5, 50, 7, 49, 20, 3)]
186
+ b = make_batches(seqs, 100)
187
+ assert sorted(i for x in b for i in x) == list(range(6))
188
+ assert all(len(x) * max(len(seqs[i]["ids"]) for i in x) <= 100 for x in b), b
189
+ print(" prompts / batching helpers ok")
190
+ try:
191
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
192
+ import supervise
193
+ sha = supervise.remote_sha()
194
+ assert sha and len(sha) == 40
195
+ print(f" supervisor sees branch head {sha[:12]}")
196
+ except OSError as e:
197
+ print(" supervisor branch lookup skipped (no network):", e)
198
+
199
+
200
  if __name__ == "__main__":
201
  head = MTPHead(C)
202
  for p in head.parameters():
 
208
  print("equalize"); test_equalize(head, E)
209
  print("walk"); test_walk()
210
  print("train/export"); test_train_and_export(head, E, W)
211
+ print("helpers"); test_helpers()
212
  print("ALL OK")