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

Draft-model pipeline for the Speculative Decoding Championship

Browse files
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .env
4
+ hf.env
5
+ *.safetensors
6
+ /data/
7
+ /models/
8
+ /runs/
9
+ /work/
10
+ /venv/
11
+ /export/
12
+ /logs/
13
+ /state/
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - speculative-decoding
7
+ - draft-model
8
+ - qwen
9
+ - vllm
10
+ pretty_name: EMC draft model - code, logs and results
11
+ ---
12
+
13
+ # EMC — a draft model for the Speculative Decoding Championship
14
+
15
+ Work for the **Speculative Decoding Championship** of the emc2 workshop at AAAI 2027:
16
+ build the best draft model for a fixed target (**Qwen3.8-27B**, bf16, 16K context) served by an
17
+ unmodified **vLLM v0.31.0**, with `K = 3` draft tokens per round.
18
+
19
+ ```
20
+ score = 100 × ( 0.50·(τ−1)/(τ_B−1) + 0.25·min(1.5, M_B/M) + 0.25·min(1.5, TPOT_B/TPOT) )
21
+ ```
22
+
23
+ τ is the acceptance length, M the draft memory (stored weight bytes + draft KV cache at 16K
24
+ tokens), TPOT the median time per output token; `B` is the baseline, the target's built-in
25
+ MTP head (τ_B = 2.802, M_B = 0.917 GB, score 100). A draft is ranked only if τ ≥ 0.9·τ_B.
26
+
27
+ **Hardware.** Everything here — data generation, training and every evaluation — runs on a
28
+ single **NVIDIA RTX PRO 6000 Blackwell (96 GB VRAM)**.
29
+
30
+ ## The draft
31
+
32
+ A **replacement MTP head in the baseline layout** (`method: mtp`): the same 15 `mtp.*`
33
+ tensors as the target's built-in head, the target's `config.json` unchanged, no code.
34
+
35
+ | | baseline head | this draft |
36
+ |---|---|---|
37
+ | layout | `mtp.*`, 424.7 M params | identical |
38
+ | weights | as shipped with the target | fine-tuned for 3-step recursive drafting on the target's own outputs |
39
+ | storage | bf16, 0.849 GB | large matrices in FP8 (E4M3), rest bf16: **0.540 GB** (a plain bf16 variant is exported too) |
40
+ | memory metric (weights + KV) | 0.917 GB | **0.607 GB** → M_B/M = 1.51, i.e. the 1.5 cap |
41
+
42
+ ### Why this design
43
+
44
+ Three things were read out of the engine source (`qwen3_5_mtp.py`, `llm_base_proposer.py`)
45
+ before choosing it:
46
+
47
+ 1. **The head's shape is fixed by the target.** vLLM builds the MTP module from the *target's*
48
+ config, not the submission's, so an `mtp` submission cannot be narrower or shallower. A
49
+ replacement head is therefore a question of *better weights*, and of how they are stored.
50
+ 2. **Drafting is recursive.** Step 1 sees the target's final hidden state; steps 2 and 3 feed the
51
+ head its *own* previous output (and write their own keys/values into the draft KV cache).
52
+ A head trained only for one-step prediction is off-distribution for two thirds of what it
53
+ is asked to do.
54
+ 3. **The LM head and embeddings are shared with the target**, so they cost nothing in the memory
55
+ metric, and the per-round draft cost is dominated by the three LM-head evaluations — the
56
+ head's own size barely moves TPOT. Higher acceptance is what moves 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
69
+ trained on the token the target really emitted; step 1 also distils the target's full
70
+ next-token distribution; later steps are weighted by whether the earlier ones were right,
71
+ because the engine only reaches them in that case.
72
+ * **FP8 with QAT.** An exact, function-preserving re-scaling (`equalize_`) first moves the big
73
+ matrices into the range where E4M3 has relative precision; they are then trained through
74
+ E4M3 rounding with a straight-through estimator, so the compact file is the model that was
75
+ optimised. The stock engine up-casts FP8 tensors to bf16 at load time — the saving is in
76
+ stored bytes, which is what the competition's memory metric counts (`emc2/submission.py`);
77
+ runtime GPU memory of the head is unchanged. Both variants are exported and reported.
78
+ * **Offline simulator.** `emcdraft.sim.simulate` replays greedy speculative decoding from stored
79
+ hidden states and returns τ without starting a server. It is checked against the kit's
80
+ measured baseline acceptance before any training, and used for checkpoint selection on a
81
+ held-out slice of the *training* data (the dev set is only reported, never selected on).
82
+
83
+ ## Results
84
+
85
+ Produced by `scripts/pipeline.sh`; raw kit outputs and logs are in `results/` and in the
86
+ dataset repo. *(Filled in by the run — see `results/summary.md`.)*
87
+
88
+ ## Layout
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
+
125
+ Each exported folder (`runs/main/sub_fp8`, `runs/main/sub_bf16`) contains `config.json` (the
126
+ target's, byte-identical), `model.safetensors` (only `mtp.*` tensors), `spec.json`
127
+ (`{"method": "mtp"}`) and `metadata.json`, and passes `emc2 validate`. No code, no pickle,
128
+ no state across requests; verification is untouched. The head is initialised from the
129
+ target's built-in MTP head (the baseline draft itself) and shares the target's embedding and
130
+ output layer, as the baseline does; no target decoder layers are copied.
131
+
132
+ ## License
133
+
134
+ Apache-2.0, like the target model and the engine.
emcdraft/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Draft-model toolkit for the Speculative Decoding Championship (emc2 workshop, AAAI 2027)."""
emcdraft/datagen.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/head.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training-time re-implementation of the Qwen3.5/3.8 multi-token-prediction (MTP) head.
2
+
3
+ The serving engine (vLLM v0.31.0, ``qwen3_5_mtp.py``) builds the head from the *target's*
4
+ config, so a replacement head must keep the baseline tensor layout exactly:
5
+
6
+ mtp.pre_fc_norm_embedding / mtp.pre_fc_norm_hidden RMSNorm (1 + w)
7
+ mtp.fc Linear(2H -> H)
8
+ mtp.layers.0 one gated full-attention block
9
+ mtp.norm RMSNorm (1 + w)
10
+
11
+ This module mirrors that computation in plain PyTorch (parameter names are identical to the
12
+ checkpoint names without the ``mtp.`` prefix) and adds what training needs:
13
+
14
+ * ``unroll`` - the K-step recursive drafting pass, vectorised over every position of a
15
+ sequence with the same key/value visibility the engine's draft KV cache has;
16
+ * ``e4m3_round`` - FP8 (E4M3) rounding with a straight-through estimator for QAT;
17
+ * ``equalize_`` - an exact, function-preserving re-scaling that moves weights into the range
18
+ where E4M3 has relative (not absolute) precision.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import struct
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+ # Tensors stored in FP8 in the compact variant (the big matrices); the rest stay bf16.
32
+ FP8_TENSORS = (
33
+ "layers.0.mlp.gate_proj.weight",
34
+ "layers.0.mlp.up_proj.weight",
35
+ "layers.0.mlp.down_proj.weight",
36
+ "layers.0.self_attn.o_proj.weight",
37
+ "layers.0.self_attn.k_proj.weight",
38
+ "layers.0.self_attn.v_proj.weight",
39
+ )
40
+
41
+
42
+ @dataclass
43
+ class HeadConfig:
44
+ hidden: int = 5120
45
+ inter: int = 17408
46
+ heads: int = 24
47
+ kv_heads: int = 4
48
+ head_dim: int = 256
49
+ rot_dim: int = 64
50
+ theta: float = 1e7
51
+ eps: float = 1e-6
52
+
53
+ @classmethod
54
+ def from_target(cls, cfg: dict) -> "HeadConfig":
55
+ t = cfg.get("text_config", cfg)
56
+ rp = t.get("rope_parameters") or {}
57
+ prf = rp.get("partial_rotary_factor", t.get("partial_rotary_factor", 1.0))
58
+ hd = t.get("head_dim") or t["hidden_size"] // t["num_attention_heads"]
59
+ return cls(hidden=t["hidden_size"], inter=t["intermediate_size"],
60
+ heads=t["num_attention_heads"],
61
+ kv_heads=t.get("num_key_value_heads", t["num_attention_heads"]),
62
+ head_dim=hd, rot_dim=int(hd * prf),
63
+ theta=float(rp.get("rope_theta", t.get("rope_theta", 10000.0))),
64
+ eps=float(t.get("rms_norm_eps", 1e-6)))
65
+
66
+
67
+ # --------------------------------------------------------------------------- FP8 (E4M3)
68
+ def e4m3_round(w: torch.Tensor) -> torch.Tensor:
69
+ """Round-to-nearest-even onto the finite FP8 E4M3 grid (saturating at 448)."""
70
+ a = w.detach().abs().float().clamp(max=448.0)
71
+ _, ex = torch.frexp(a) # a = m * 2**ex, m in [0.5, 1)
72
+ e = (ex - 1).clamp(min=-6).float() # binade; subnormals share e = -6
73
+ step = torch.exp2(e - 3.0) # 3 mantissa bits
74
+ q = (torch.round(a / step) * step).clamp(max=448.0)
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)
83
+ e = (ex - 1).clamp(min=-6)
84
+ normal = a >= 2.0 ** -6
85
+ mant_n = torch.round((a / torch.exp2(e.float()) - 1.0) * 8.0).long()
86
+ mant_s = torch.round(a * 2.0 ** 9).long()
87
+ bits = torch.where(normal, ((e.long() + 7) << 3) | mant_n, mant_s)
88
+ bits = bits | ((q < 0).long() << 7)
89
+ return bits.to(torch.uint8)
90
+
91
+
92
+ def e4m3_decode(b: torch.Tensor) -> torch.Tensor:
93
+ b = b.long()
94
+ sign = torch.where((b >> 7) > 0, -1.0, 1.0)
95
+ ef, m = (b >> 3) & 0xF, (b & 0x7).float()
96
+ val = torch.where(ef > 0, (1.0 + m / 8.0) * torch.exp2(ef.float() - 7.0), m * 2.0 ** -9)
97
+ return sign * val
98
+
99
+
100
+ class QLinear(nn.Linear):
101
+ """Bias-free linear layer; ``fq=True`` fake-quantises the weight to E4M3 (STE)."""
102
+
103
+ def __init__(self, i: int, o: int):
104
+ super().__init__(i, o, bias=False)
105
+ self.fq = False
106
+
107
+ def qweight(self) -> torch.Tensor:
108
+ w = self.weight
109
+ return w + (e4m3_round(w) - w).detach() if self.fq else w
110
+
111
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
112
+ return F.linear(x, self.qweight().to(x.dtype))
113
+
114
+
115
+ class GRMSNorm(nn.Module):
116
+ """RMSNorm with a (1 + w) gain, computed in fp32 (the engine's GemmaRMSNorm)."""
117
+
118
+ def __init__(self, dim: int, eps: float):
119
+ super().__init__()
120
+ self.weight = nn.Parameter(torch.zeros(dim))
121
+ self.eps = eps
122
+
123
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
124
+ xf = x.float()
125
+ xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
126
+ return (xf * (1.0 + self.weight.float())).to(x.dtype)
127
+
128
+
129
+ def rope(x: torch.Tensor, pos: torch.Tensor, rot_dim: int, theta: float) -> torch.Tensor:
130
+ """NeoX-style partial rotary embedding. x: [B, N, heads, head_dim], pos: [B, N]."""
131
+ half = rot_dim // 2
132
+ inv = 1.0 / (theta ** (torch.arange(0, rot_dim, 2, device=x.device, dtype=torch.float32) / rot_dim))
133
+ ang = pos.float()[..., None] * inv
134
+ cos, sin = ang.cos()[:, :, None, :], ang.sin()[:, :, None, :]
135
+ xf = x.float()
136
+ x1, x2 = xf[..., :half], xf[..., half:rot_dim]
137
+ out = torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin, xf[..., rot_dim:]], -1)
138
+ return out.to(x.dtype)
139
+
140
+
141
+ class Attention(nn.Module):
142
+ def __init__(self, c: HeadConfig):
143
+ super().__init__()
144
+ self.c = c
145
+ self.q_proj = QLinear(c.hidden, c.heads * c.head_dim * 2) # per head: [query | gate]
146
+ self.k_proj = QLinear(c.hidden, c.kv_heads * c.head_dim)
147
+ self.v_proj = QLinear(c.hidden, c.kv_heads * c.head_dim)
148
+ self.o_proj = QLinear(c.heads * c.head_dim, c.hidden)
149
+ self.q_norm = GRMSNorm(c.head_dim, c.eps)
150
+ self.k_norm = GRMSNorm(c.head_dim, c.eps)
151
+
152
+ def forward(self, x, pos, mem, mask):
153
+ c = self.c
154
+ B, N, _ = x.shape
155
+ qg = self.q_proj(x).view(B, N, c.heads, 2 * c.head_dim)
156
+ q, gate = qg[..., :c.head_dim], qg[..., c.head_dim:]
157
+ k = self.k_proj(x).view(B, N, c.kv_heads, c.head_dim)
158
+ v = self.v_proj(x).view(B, N, c.kv_heads, c.head_dim)
159
+ q = rope(self.q_norm(q), pos, c.rot_dim, c.theta).transpose(1, 2)
160
+ k = rope(self.k_norm(k), pos, c.rot_dim, c.theta).transpose(1, 2)
161
+ v = v.transpose(1, 2)
162
+ keys = torch.cat([m[0] for m in mem] + [k], 2)
163
+ vals = torch.cat([m[1] for m in mem] + [v], 2)
164
+ rep = c.heads // c.kv_heads
165
+ keys, vals = keys.repeat_interleave(rep, 1), vals.repeat_interleave(rep, 1)
166
+ o = F.scaled_dot_product_attention(q, keys, vals, attn_mask=mask)
167
+ o = o.transpose(1, 2) * torch.sigmoid(gate)
168
+ return self.o_proj(o.reshape(B, N, c.heads * c.head_dim)), (k, v)
169
+
170
+
171
+ class MLP(nn.Module):
172
+ def __init__(self, c: HeadConfig):
173
+ super().__init__()
174
+ self.gate_proj = QLinear(c.hidden, c.inter)
175
+ self.up_proj = QLinear(c.hidden, c.inter)
176
+ self.down_proj = QLinear(c.inter, c.hidden)
177
+
178
+ def forward(self, x):
179
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
180
+
181
+
182
+ class Layer(nn.Module):
183
+ def __init__(self, c: HeadConfig):
184
+ super().__init__()
185
+ self.self_attn = Attention(c)
186
+ self.mlp = MLP(c)
187
+ self.input_layernorm = GRMSNorm(c.hidden, c.eps)
188
+ self.post_attention_layernorm = GRMSNorm(c.hidden, c.eps)
189
+
190
+ def forward(self, h, pos, mem=(), mask=None):
191
+ a, kv = self.self_attn(self.input_layernorm(h), pos, list(mem), mask)
192
+ h = h + a
193
+ return h + self.mlp(self.post_attention_layernorm(h)), kv
194
+
195
+
196
+ class MTPHead(nn.Module):
197
+ def __init__(self, c: HeadConfig):
198
+ super().__init__()
199
+ self.c = c
200
+ self.pre_fc_norm_embedding = GRMSNorm(c.hidden, c.eps)
201
+ self.pre_fc_norm_hidden = GRMSNorm(c.hidden, c.eps)
202
+ self.fc = QLinear(2 * c.hidden, c.hidden)
203
+ self.layers = nn.ModuleList([Layer(c)])
204
+ self.norm = GRMSNorm(c.hidden, c.eps)
205
+
206
+ def step(self, emb, hid, pos, mem=(), mask=None):
207
+ """One drafting step. emb/hid: [B, N, H]; returns (post-norm hidden, (k, v))."""
208
+ x = torch.cat([self.pre_fc_norm_embedding(emb), self.pre_fc_norm_hidden(hid)], -1)
209
+ h, kv = self.layers[0](self.fc(x), pos, mem, mask)
210
+ return self.norm(h), kv
211
+
212
+ def set_fake_quant(self, on: bool, names=FP8_TENSORS):
213
+ mods = dict(self.named_modules())
214
+ for n in names:
215
+ mods[n.rsplit(".", 1)[0]].fq = on
216
+
217
+
218
+ def unroll(head: MTPHead, embed, tokens: torch.Tensor, hidden: torch.Tensor, K: int = 3):
219
+ """Vectorised K-step drafting for every base position of a batch of sequences.
220
+
221
+ tokens [B, T]; hidden [B, T-1, H] = target final hidden states h_0..h_{T-2}.
222
+ Step k (1-based) at base index i consumes token x_{i+k} and predicts x_{i+1+k}; it sees
223
+ the "verified" keys/values of positions <= i (step-1 pass, true hidden states), plus the
224
+ keys/values written by the earlier steps of the same round and its own - exactly what the
225
+ engine's draft KV cache holds at that moment. Returns a generator of step outputs so the
226
+ caller can interleave losses (and use correctness of step k-1 to weight step k).
227
+ """
228
+ B, T = tokens.shape
229
+ N = T - 1
230
+ dev = tokens.device
231
+ base = torch.arange(N, device=dev)
232
+ pos = base[None].expand(B, N)
233
+ tri = torch.ones(N, N, dtype=torch.bool, device=dev).tril()
234
+ eye = torch.eye(N, dtype=torch.bool, device=dev)
235
+ mem, hid = [], hidden
236
+ for k in range(1, K + 1):
237
+ tok_k = tokens[:, (base + k).clamp(max=T - 1)]
238
+ mask = torch.cat([tri] + [eye] * (k - 1), 1)[None, None]
239
+ out, kv = head.step(embed(tok_k), hid, pos + (k - 1), mem, mask)
240
+ mem.append(kv)
241
+ hid = out
242
+ yield k, out
243
+
244
+
245
+ def walk(correct, P: int, T: int, K: int = 3):
246
+ """Greedy speculative decoding over per-position correctness flags.
247
+
248
+ correct[k][i] says whether draft step k+1 at base index i matched the target's token.
249
+ Returns (accepted draft tokens, drafting rounds) for one sequence of T tokens whose first
250
+ P tokens are the prompt; acceptance length = 1 + accepted / rounds.
251
+ """
252
+ acc = drafts = 0
253
+ cur = P
254
+ while cur <= T - 2:
255
+ i, n = cur - 1, 0
256
+ for k in range(K):
257
+ if i + 2 + k > T - 1 or not correct[k][i]:
258
+ break
259
+ n += 1
260
+ drafts += 1
261
+ acc += n
262
+ cur += n + 1
263
+ return acc, drafts
264
+
265
+
266
+ # --------------------------------------------------------------------------- equalisation
267
+ @torch.no_grad()
268
+ def equalize_(head: MTPHead, r: float = 0.25) -> dict:
269
+ """Exact re-scaling that brings every FP8 tensor to RMS ~= r (function unchanged).
270
+
271
+ Uses the scale symmetries of the block: RMSNorm inputs are scale-free, so the residual
272
+ stream can be scaled by s (fc, o_proj, down_proj); value/output and up/down projections
273
+ trade scale; the norm gains absorb a common factor of everything that reads them.
274
+ """
275
+ L = head.layers[0]
276
+ A, M = L.self_attn, L.mlp
277
+ rms = lambda w: w.float().pow(2).mean().sqrt().item()
278
+ g = r / rms(M.gate_proj.weight)
279
+ gam = rms(M.gate_proj.weight) / rms(M.up_proj.weight)
280
+ s = r * gam / rms(M.down_proj.weight)
281
+ beta = s * rms(A.o_proj.weight) / r
282
+ cc = r / (rms(A.v_proj.weight) * beta)
283
+ ak = r / rms(A.k_proj.weight)
284
+ M.gate_proj.weight.mul_(g)
285
+ M.up_proj.weight.mul_(g * gam)
286
+ M.down_proj.weight.mul_(s / gam)
287
+ L.post_attention_layernorm.weight.copy_((1 + L.post_attention_layernorm.weight) / g - 1)
288
+ A.q_proj.weight.mul_(cc)
289
+ A.v_proj.weight.mul_(cc * beta)
290
+ A.o_proj.weight.mul_(s / beta)
291
+ A.k_proj.weight.mul_(ak)
292
+ L.input_layernorm.weight.copy_((1 + L.input_layernorm.weight) / cc - 1)
293
+ head.fc.weight.mul_(s)
294
+ return dict(g=g, gamma=gam, s=s, beta=beta, c=cc, a_k=ak)
295
+
296
+
297
+ # --------------------------------------------------------------------------- checkpoint IO
298
+ def read_safetensors(path, names=None, prefix=None) -> dict:
299
+ from safetensors import safe_open
300
+ out = {}
301
+ with safe_open(str(path), framework="pt") as f:
302
+ for n in f.keys():
303
+ if (names is None or n in names) and (prefix is None or n.startswith(prefix)):
304
+ out[n] = f.get_tensor(n)
305
+ return out
306
+
307
+
308
+ def load_target_tensors(target_dir, names) -> dict:
309
+ """Read named tensors straight from the target's shards (no model instantiation)."""
310
+ target_dir = Path(target_dir)
311
+ index = json.loads((target_dir / "model.safetensors.index.json").read_text())["weight_map"]
312
+ out = {}
313
+ for shard in sorted({index[n] for n in names}):
314
+ out.update(read_safetensors(target_dir / shard, names=set(names)))
315
+ return out
316
+
317
+
318
+ def load_mtp_state(src) -> dict:
319
+ """mtp.* tensors (prefix stripped) from a submission folder or the target folder."""
320
+ src = Path(src)
321
+ if (src / "model.safetensors.index.json").exists():
322
+ index = json.loads((src / "model.safetensors.index.json").read_text())["weight_map"]
323
+ raw = {}
324
+ for shard in sorted({f for n, f in index.items() if n.startswith("mtp.")}):
325
+ raw.update(read_safetensors(src / shard, prefix="mtp."))
326
+ else:
327
+ raw = {}
328
+ for p in sorted(src.glob("*.safetensors")):
329
+ raw.update(read_safetensors(p, prefix="mtp."))
330
+ return {n[4:]: (e4m3_decode(t.view(torch.uint8)) if "float8" in str(t.dtype) else t.float())
331
+ for n, t in raw.items()}
332
+
333
+
334
+ def build_head(state: dict, cfg: HeadConfig, device="cpu") -> MTPHead:
335
+ head = MTPHead(cfg)
336
+ head.load_state_dict(state, strict=True)
337
+ return head.to(device)
338
+
339
+
340
+ def save_safetensors_raw(path, tensors: dict):
341
+ """Minimal safetensors writer (lets us emit F8_E4M3 without relying on torch float8)."""
342
+ header, blobs, off = {}, [], 0
343
+ for name, (dtype, shape, data) in tensors.items():
344
+ header[name] = {"dtype": dtype, "shape": list(shape), "data_offsets": [off, off + len(data)]}
345
+ blobs.append(data)
346
+ off += len(data)
347
+ hj = json.dumps(header, separators=(",", ":")).encode()
348
+ hj += b" " * ((8 - len(hj) % 8) % 8)
349
+ with open(path, "wb") as f:
350
+ f.write(struct.pack("<Q", len(hj)))
351
+ f.write(hj)
352
+ for b in blobs:
353
+ f.write(b)
354
+
355
+
356
+ @torch.no_grad()
357
+ def export_submission(head: MTPHead, out_dir, target_config, fp8: bool, metadata: dict,
358
+ fp8_names=FP8_TENSORS) -> dict:
359
+ """Write a kit-format submission folder: config.json, model.safetensors, spec, metadata."""
360
+ out_dir = Path(out_dir)
361
+ out_dir.mkdir(parents=True, exist_ok=True)
362
+ tensors, nbytes = {}, 0
363
+ for name, p in head.state_dict().items():
364
+ w = p.detach().float().cpu()
365
+ if fp8 and name in fp8_names:
366
+ data = e4m3_encode(w).numpy().tobytes()
367
+ tensors["mtp." + name] = ("F8_E4M3", w.shape, data)
368
+ else:
369
+ data = w.to(torch.bfloat16).view(torch.int16).numpy().tobytes()
370
+ tensors["mtp." + name] = ("BF16", w.shape, data)
371
+ nbytes += len(data)
372
+ save_safetensors_raw(out_dir / "model.safetensors", tensors)
373
+ (out_dir / "config.json").write_bytes(Path(target_config).read_bytes())
374
+ (out_dir / "spec.json").write_text(json.dumps({"method": "mtp"}) + "\n")
375
+ (out_dir / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n")
376
+ return {"weight_bytes": nbytes, "tensors": len(tensors)}
emcdraft/probe.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Engine probe: the unmodified baseline head, exactly re-scaled and stored in FP8 (no training).
2
+
3
+ Evaluating this folder with the kit answers two questions before any training time is spent:
4
+ does the stock engine load FP8-typed MTP tensors, and how much acceptance does plain rounding
5
+ cost on its own.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ from pathlib import Path
12
+
13
+ from .head import HeadConfig, build_head, equalize_, export_submission, load_mtp_state
14
+
15
+
16
+ def main():
17
+ ap = argparse.ArgumentParser()
18
+ ap.add_argument("--target", required=True)
19
+ ap.add_argument("--baseline", required=True)
20
+ ap.add_argument("--out", required=True)
21
+ a = ap.parse_args()
22
+ cfg = HeadConfig.from_target(json.loads((Path(a.target) / "config.json").read_text()))
23
+ head = build_head(load_mtp_state(a.baseline), cfg)
24
+ factors = equalize_(head)
25
+ info = export_submission(head, a.out, Path(a.target) / "config.json", True,
26
+ {"team_id": "probe", "method_description": "baseline head, FP8 storage, untrained",
27
+ "training_data": "none"})
28
+ print(json.dumps({"equalize": factors, **info}, indent=2))
29
+
30
+
31
+ if __name__ == "__main__":
32
+ main()
emcdraft/prompts.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}```")
14
+ MATH_T = ("{q}\n\nSolve this step by step, then give the final answer on its own line as "
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"),
22
+ (" 'll", "'ll"), (" 'd", "'d"), (" ,", ","), (" .", "."), (" ?", "?"), (" !", "!"),
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)
39
+ if len(out) >= n:
40
+ break
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):
59
+ m = TAG_RE.match(p)
60
+ if not m or m.group(1).upper() != "WP":
61
+ return None
62
+ p = p[m.end():]
63
+ for a, b in DETOK:
64
+ p = p.replace(a, b)
65
+ p = re.sub(r"\s+", " ", p).strip()
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:
108
+ raise ValueError(domain)
109
+ out = list(dict.fromkeys(out))
110
+ rng.shuffle(out)
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
emcdraft/sim.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline acceptance simulator and feature-shard helpers.
2
+
3
+ Given target hidden states for a token sequence, `simulate` replays greedy speculative
4
+ decoding with K draft tokens exactly as the engine's proposer does (recursive use of the
5
+ head's own hidden state, verified keys/values for the prefix) and returns the acceptance
6
+ length tau = 1 + accepted / rounds - the same quantity the kit reads from the engine's
7
+ counters. It needs no server start, so it is used for validation during training.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections import defaultdict
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torch.nn.functional as F
18
+
19
+ from .head import unroll, walk
20
+
21
+ DOMAINS = ("chat", "code", "math", "longform")
22
+
23
+
24
+ def save_shard(stem: str, seqs: list[dict]):
25
+ """seqs: dicts with tokens [T] (long), hidden [T-1, H] (bf16), P, domain, optional id."""
26
+ toks = torch.cat([s["tokens"] for s in seqs]).to(torch.int32).cpu().numpy()
27
+ hid = torch.cat([s["hidden"] for s in seqs]).to(torch.bfloat16).cpu()
28
+ np.save(stem + ".tok.npy", toks)
29
+ np.save(stem + ".hid.npy", hid.view(torch.int16).numpy())
30
+ meta = {"T": [int(s["tokens"].numel()) for s in seqs], "P": [int(s["P"]) for s in seqs],
31
+ "domain": [s["domain"] for s in seqs], "id": [s.get("id", "") for s in seqs]}
32
+ Path(stem + ".json").write_text(json.dumps(meta))
33
+
34
+
35
+ def load_shards(data_dir, device, max_tokens: int | None = None) -> list[dict]:
36
+ seqs, total = [], 0
37
+ for meta_path in sorted(Path(data_dir).glob("*.json")):
38
+ stem = str(meta_path)[:-5]
39
+ meta = json.loads(meta_path.read_text())
40
+ tok = torch.from_numpy(np.load(stem + ".tok.npy").astype(np.int64)).to(device)
41
+ hid = torch.from_numpy(np.load(stem + ".hid.npy")).view(torch.bfloat16).to(device)
42
+ to = ho = 0
43
+ for T, P, dom, sid in zip(meta["T"], meta["P"], meta["domain"], meta["id"]):
44
+ seqs.append({"tokens": tok[to:to + T], "hidden": hid[ho:ho + T - 1], "P": P, "T": T,
45
+ "domain": dom, "id": sid})
46
+ to, ho, total = to + T, ho + T - 1, total + T
47
+ if max_tokens and total >= max_tokens:
48
+ break
49
+ return seqs
50
+
51
+
52
+ def collate(seqs: list[dict], pad: int = 0):
53
+ B, Tm = len(seqs), max(s["T"] for s in seqs)
54
+ dev = seqs[0]["tokens"].device
55
+ H = seqs[0]["hidden"].shape[-1]
56
+ tokens = torch.full((B, Tm), pad, dtype=torch.long, device=dev)
57
+ hidden = torch.zeros((B, Tm - 1, H), dtype=seqs[0]["hidden"].dtype, device=dev)
58
+ for b, s in enumerate(seqs):
59
+ tokens[b, :s["T"]] = s["tokens"]
60
+ hidden[b, :s["T"] - 1] = s["hidden"]
61
+ P = torch.tensor([s["P"] for s in seqs], device=dev)
62
+ T = torch.tensor([s["T"] for s in seqs], device=dev)
63
+ return tokens, hidden, P, T
64
+
65
+
66
+ def batches(seqs: list[dict], max_tokens: int, shuffle_rng=None) -> list[list[dict]]:
67
+ """Length-bucketed batches with at most `max_tokens` padded positions each."""
68
+ order = sorted(seqs, key=lambda s: s["T"])
69
+ out, cur, cur_max = [], [], 0
70
+ for s in order:
71
+ if cur and max(cur_max, s["T"]) * (len(cur) + 1) > max_tokens:
72
+ out.append(cur)
73
+ cur, cur_max = [], 0
74
+ cur.append(s)
75
+ cur_max = max(cur_max, s["T"])
76
+ if cur:
77
+ out.append(cur)
78
+ if shuffle_rng is not None:
79
+ shuffle_rng.shuffle(out)
80
+ return out
81
+
82
+
83
+ def argmax_logits(h: torch.Tensor, W: torch.Tensor, chunk: int = 4096) -> torch.Tensor:
84
+ return torch.cat([F.linear(h[i:i + chunk], W).float().argmax(-1) for i in range(0, h.shape[0], chunk)])
85
+
86
+
87
+ @torch.no_grad()
88
+ def simulate(head, embed, W, seqs: list[dict], K: int = 3, max_tokens: int = 12000) -> dict:
89
+ """Acceptance length per domain and overall, plus per-step conditional accuracies."""
90
+ was_training = head.training
91
+ head.eval()
92
+ acc, drafts = defaultdict(int), defaultdict(int)
93
+ hit, tot = [0] * K, [0] * K
94
+ cuda = W.is_cuda
95
+ for group in batches(seqs, max_tokens):
96
+ tokens, hidden, P, T = collate(group)
97
+ B, Tm = tokens.shape
98
+ N = Tm - 1
99
+ base = torch.arange(N, device=tokens.device)
100
+ flags = []
101
+ with torch.autocast("cuda" if cuda else "cpu", dtype=torch.bfloat16, enabled=cuda):
102
+ for k, out in unroll(head, embed, tokens, hidden, K):
103
+ lab = tokens[:, (base + 1 + k).clamp(max=Tm - 1)]
104
+ pred = argmax_logits(out.reshape(B * N, -1), W).view(B, N)
105
+ flags.append(pred == lab)
106
+ prev = None
107
+ for k in range(K):
108
+ valid = (base[None] >= (P[:, None] - 1)) & ((base[None] + 2 + k) <= (T[:, None] - 1))
109
+ reach = valid if prev is None else valid & prev
110
+ hit[k] += int((flags[k] & reach).sum())
111
+ tot[k] += int(reach.sum())
112
+ prev = flags[k] if prev is None else prev & flags[k]
113
+ cpu_flags = [f.cpu() for f in flags]
114
+ for b, s in enumerate(group):
115
+ a, d = walk([f[b].tolist() for f in cpu_flags], s["P"], s["T"], K)
116
+ acc[s["domain"]] += a
117
+ drafts[s["domain"]] += d
118
+ head.train(was_training)
119
+ res = {"acceptance_by_domain": {d: 1 + acc[d] / drafts[d] for d in acc if drafts[d]},
120
+ "acceptance_length": 1 + sum(acc.values()) / max(1, sum(drafts.values())),
121
+ "step_accuracy": [hit[k] / max(1, tot[k]) for k in range(K)],
122
+ "rounds": sum(drafts.values()), "sequences": len(seqs)}
123
+ return res
emcdraft/target.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
19
+ import transformers
20
+ errs = []
21
+ for name in ("AutoModelForImageTextToText", "AutoModelForCausalLM"):
22
+ cls = getattr(transformers, name, None)
23
+ if cls is None:
24
+ continue
25
+ for dk in ("dtype", "torch_dtype"):
26
+ try:
27
+ model = cls.from_pretrained(path, device_map={"": 0}, **{dk: torch.bfloat16})
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))
35
+
36
+
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
emcdraft/train.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fine-tune the MTP head on the target's own outputs.
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),
10
+ after an exact re-scaling that puts them in E4M3's relative-precision range, so the compact
11
+ on-disk variant is the model that was actually optimised.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import math
18
+ import os
19
+ import random
20
+ import time
21
+ from pathlib import Path
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+
26
+ from .head import (FP8_TENSORS, HeadConfig, build_head, e4m3_round, equalize_, export_submission,
27
+ load_mtp_state, load_target_tensors, unroll)
28
+ from .sim import DOMAINS, batches, collate, load_shards, simulate
29
+
30
+
31
+ def log(msg):
32
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
33
+
34
+
35
+ def head_loss(o, W, y, w, teach, beta, chunk=2048):
36
+ """Weighted CE (+ beta * soft-target CE) through the frozen LM head, in memory-bounded
37
+ chunks. Returns a surrogate whose gradient w.r.t. `o` equals the loss gradient."""
38
+ n = o.shape[0]
39
+ denom = w.sum().clamp(min=1.0)
40
+ surrogate = torch.zeros((), device=o.device)
41
+ ce_sum = 0.0
42
+ correct = torch.zeros(n, dtype=torch.bool, device=o.device)
43
+ for s in range(0, n, chunk):
44
+ e = min(n, s + chunk)
45
+ z = o[s:e].detach().requires_grad_(True)
46
+ logits = F.linear(z, W.to(z.dtype)).float()
47
+ logp = F.log_softmax(logits, -1)
48
+ ce = F.nll_loss(logp, y[s:e], reduction="none")
49
+ loss = (ce * w[s:e]).sum()
50
+ if teach is not None and beta > 0:
51
+ with torch.no_grad():
52
+ tp = F.softmax(F.linear(teach[s:e], W.to(teach.dtype)).float(), -1)
53
+ loss = loss + beta * (-(tp * logp).sum(-1) * w[s:e]).sum()
54
+ (g,) = torch.autograd.grad(loss / denom, z)
55
+ surrogate = surrogate + (o[s:e].float() * g.float()).sum()
56
+ ce_sum += float((ce.detach() * w[s:e]).sum())
57
+ correct[s:e] = logits.argmax(-1) == y[s:e]
58
+ return surrogate, ce_sum / float(denom), correct
59
+
60
+
61
+ def train_step(head, embed, W, batch, a, K=3):
62
+ tokens, hidden, P, T = batch
63
+ B, Tm = tokens.shape
64
+ N = Tm - 1
65
+ base = torch.arange(N, device=tokens.device)[None]
66
+ total = torch.zeros((), device=tokens.device)
67
+ info, prev = {}, None
68
+ cuda = tokens.is_cuda
69
+ with torch.autocast("cuda" if cuda else "cpu", dtype=torch.bfloat16, enabled=cuda):
70
+ for k, out in unroll(head, embed, tokens, hidden, K):
71
+ valid = (base >= (P[:, None] - 1)) & ((base + 1 + k) <= (T[:, None] - 1))
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)
79
+ full[bi, ni] = corr
80
+ reach = valid if prev is None else valid & prev
81
+ info[f"ce{k}"] = ce_k
82
+ info[f"acc{k}"] = float((full & reach).sum()) / max(1.0, float(reach.sum()))
83
+ prev = full if prev is None else prev & full
84
+ return total, info
85
+
86
+
87
+ def split_val(seqs, frac, rng):
88
+ by = {}
89
+ for s in seqs:
90
+ by.setdefault(s["domain"], []).append(s)
91
+ train, val = [], []
92
+ for d, v in by.items():
93
+ rng.shuffle(v)
94
+ n = max(4, min(40, int(len(v) * frac))) if len(v) >= 16 else 0
95
+ val += v[:n]
96
+ train += v[n:]
97
+ if not val: # tiny smoke-test datasets: validate on a training slice
98
+ val = train[:8]
99
+ return train, val
100
+
101
+
102
+ def main():
103
+ ap = argparse.ArgumentParser()
104
+ ap.add_argument("--target", required=True)
105
+ ap.add_argument("--init", required=True, help="folder with the starting mtp.* weights")
106
+ ap.add_argument("--data", required=True)
107
+ ap.add_argument("--dev", default=None)
108
+ ap.add_argument("--out", required=True)
109
+ ap.add_argument("--qat", action="store_true")
110
+ ap.add_argument("--epochs", type=float, default=float(os.environ.get("TRAIN_EPOCHS", 2)))
111
+ ap.add_argument("--max-minutes", type=float, default=float(os.environ.get("TRAIN_MINUTES", 22)))
112
+ ap.add_argument("--batch-tokens", type=int, default=int(os.environ.get("TRAIN_BATCH_TOKENS", 8192)))
113
+ ap.add_argument("--rel-lr", type=float, default=float(os.environ.get("TRAIN_REL_LR", 1e-3)),
114
+ help="peak Adam step as a fraction of each tensor's RMS")
115
+ ap.add_argument("--beta", type=float, default=0.5)
116
+ ap.add_argument("--floor", type=float, default=0.3)
117
+ ap.add_argument("--step-w", type=float, nargs=3, default=[1.0, 0.7, 0.5])
118
+ ap.add_argument("--eval-every", type=int, default=60)
119
+ ap.add_argument("--seed", type=int, default=0)
120
+ ap.add_argument("--team", default=os.environ.get("TEAM_ID", "mudassiruddin"))
121
+ a = ap.parse_args()
122
+ out = Path(a.out)
123
+ out.mkdir(parents=True, exist_ok=True)
124
+ rng = random.Random(a.seed)
125
+ torch.manual_seed(a.seed)
126
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
127
+ t_start = time.time()
128
+
129
+ cfg = HeadConfig.from_target(json.loads((Path(a.target) / "config.json").read_text()))
130
+ names = ["lm_head.weight", "model.language_model.embed_tokens.weight"]
131
+ tt = load_target_tensors(a.target, names)
132
+ W = tt[names[0]].to(dev)
133
+ E = tt[names[1]].to(dev)
134
+ embed = lambda ids: F.embedding(ids, E)
135
+ head = build_head(load_mtp_state(a.init), cfg, dev)
136
+
137
+ seqs = load_shards(a.data, dev)
138
+ train, val = split_val(seqs, 0.05, rng)
139
+ dev_seqs = load_shards(a.dev, dev) if a.dev and Path(a.dev).exists() else []
140
+ tok_by = {d: sum(s["T"] - s["P"] for s in seqs if s["domain"] == d) for d in DOMAINS}
141
+ log(f"data: {len(train)} train / {len(val)} val sequences, generated tokens by domain {tok_by}")
142
+ summary = {"args": vars(a), "data": {"train_sequences": len(train), "val_sequences": len(val),
143
+ "generated_tokens": tok_by}, "sim": {}}
144
+
145
+ def sims(tag):
146
+ r = {"val": simulate(head, embed, W, val)}
147
+ if dev_seqs:
148
+ r["dev"] = simulate(head, embed, W, dev_seqs)
149
+ summary["sim"][tag] = r
150
+ log(f"[{tag}] val tau {r['val']['acceptance_length']:.4f}"
151
+ + (f" | dev tau {r['dev']['acceptance_length']:.4f} "
152
+ f"{ {d: round(v, 3) for d, v in r['dev']['acceptance_by_domain'].items()} } "
153
+ f"steps {[round(x, 3) for x in r['dev']['step_accuracy']]}" if dev_seqs else ""))
154
+ return r
155
+
156
+ sims("baseline")
157
+ if a.qat:
158
+ probe = collate(val[:2])
159
+ with torch.no_grad():
160
+ ref, _ = head.step(embed(probe[0][:, 1:]).float(), probe[1].float(),
161
+ torch.arange(probe[0].shape[1] - 1, device=dev)[None].expand(2, -1))
162
+ summary["equalize"] = equalize_(head)
163
+ new, _ = head.step(embed(probe[0][:, 1:]).float(), probe[1].float(),
164
+ torch.arange(probe[0].shape[1] - 1, device=dev)[None].expand(2, -1))
165
+ drift = float((new - ref).abs().max() / ref.abs().max())
166
+ summary["equalize"]["max_rel_drift"] = drift
167
+ log(f"equalisation factors {summary['equalize']} (must be function-preserving)")
168
+ if drift > 1e-2:
169
+ raise SystemExit(f"equalisation changed the head's output (drift {drift:.3g})")
170
+ sims("equalized")
171
+ head.set_fake_quant(True)
172
+ sims("fp8_untrained")
173
+
174
+ groups = []
175
+ for n, p in head.named_parameters():
176
+ eff = (1 + p.detach()) if p.ndim == 1 else p.detach()
177
+ groups.append({"params": [p], "base": a.rel_lr * float(eff.float().pow(2).mean().sqrt()), "lr": 0.0})
178
+ opt = torch.optim.AdamW(groups, betas=(0.9, 0.95), eps=1e-10, weight_decay=0.0)
179
+
180
+ per_epoch = len(batches(train, a.batch_tokens))
181
+ total_steps = max(1, int(per_epoch * a.epochs))
182
+ warm = max(5, total_steps // 30)
183
+ key = "val"
184
+ best = {"tau": summary["sim"]["fp8_untrained" if a.qat else "baseline"][key]["acceptance_length"],
185
+ "step": 0, "state": {k: v.detach().clone() for k, v in head.state_dict().items()}}
186
+ log(f"training: {total_steps} steps planned ({per_epoch}/epoch), qat={a.qat}")
187
+ step, t0, hist = 0, time.time(), []
188
+ head.train()
189
+ done = False
190
+ while not done:
191
+ for group in batches(train, a.batch_tokens, rng):
192
+ if step == 12:
193
+ per = (time.time() - t0) / 12
194
+ fit = int((a.max_minutes * 60 - (time.time() - t_start) - 240) / max(per, 1e-3))
195
+ if fit < total_steps - step:
196
+ total_steps = max(step + 20, step + fit)
197
+ log(f"{per:.2f}s/step: shortening the schedule to {total_steps} steps to fit the budget")
198
+ f = (step + 1) / warm if step < warm else 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (step - warm) / max(1, total_steps - warm)))
199
+ for g in opt.param_groups:
200
+ g["lr"] = g["base"] * f
201
+ loss, info = train_step(head, embed, W, collate(group), a)
202
+ opt.zero_grad(set_to_none=True)
203
+ loss.backward()
204
+ torch.nn.utils.clip_grad_norm_(head.parameters(), 1.0)
205
+ opt.step()
206
+ step += 1
207
+ if step % 10 == 0 or step == 1:
208
+ est = 1 + info["acc1"] * (1 + info["acc2"] * (1 + info["acc3"]))
209
+ log(f"step {step}/{total_steps} ce {info['ce1']:.3f}/{info['ce2']:.3f}/{info['ce3']:.3f} "
210
+ f"acc {info['acc1']:.3f}/{info['acc2']:.3f}/{info['acc3']:.3f} batch-tau~{est:.3f} "
211
+ f"lr x{f:.2f} {(time.time() - t0) / step:.2f}s/step")
212
+ if step % a.eval_every == 0 or step >= total_steps:
213
+ r = simulate(head, embed, W, val)
214
+ d = simulate(head, embed, W, dev_seqs[::4]) if dev_seqs else None
215
+ hist.append({"step": step, "val": r["acceptance_length"],
216
+ "dev_quarter": d["acceptance_length"] if d else None})
217
+ log(f"eval step {step}: val tau {r['acceptance_length']:.4f}"
218
+ + (f" | dev(1/4) tau {d['acceptance_length']:.4f}" if d else "")
219
+ + f" (best {best['tau']:.4f} @ {best['step']})")
220
+ if r["acceptance_length"] > best["tau"]:
221
+ best = {"tau": r["acceptance_length"], "step": step,
222
+ "state": {k: v.detach().clone() for k, v in head.state_dict().items()}}
223
+ head.train()
224
+ if step >= total_steps:
225
+ done = True
226
+ break
227
+ head.load_state_dict(best["state"])
228
+ head.eval()
229
+ summary["history"] = hist
230
+ summary["best_step"] = best["step"]
231
+ summary["train_seconds"] = round(time.time() - t0, 1)
232
+ log(f"best checkpoint: step {best['step']} (val tau {best['tau']:.4f})")
233
+
234
+ meta = {"team_id": a.team,
235
+ "method_description": ("Replacement MTP head in the baseline layout, initialised from the target's "
236
+ "built-in head and fine-tuned with a 3-step recursive drafting objective"
237
+ + (" and FP8 (E4M3) quantisation-aware training" if a.qat else "")),
238
+ "training_data": ("Greedy answers of the target itself (with its hidden states) to public "
239
+ "instruction prompts: GSM8K/MetaMathQA, WritingPrompts, UltraChat/Alpaca/Dolly, "
240
+ "Python instruction sets; dev prompts excluded")}
241
+ tcfg = Path(a.target) / "config.json"
242
+ if a.qat:
243
+ sims("final_fp8")
244
+ summary["export_fp8"] = export_submission(head, out / "sub_fp8", tcfg, True, meta)
245
+ back = load_mtp_state(out / "sub_fp8")
246
+ for n in FP8_TENSORS:
247
+ want = e4m3_round(head.state_dict()[n].float().cpu())
248
+ assert torch.equal(back[n], want), f"FP8 round trip mismatch in {n}"
249
+ head.set_fake_quant(False)
250
+ sims("final_bf16")
251
+ summary["export_bf16"] = export_submission(head, out / "sub_bf16", tcfg, False, meta)
252
+ summary["total_seconds"] = round(time.time() - t_start, 1)
253
+ (out / "train_summary.json").write_text(json.dumps(summary, indent=2, default=str))
254
+ log("training finished")
255
+
256
+
257
+ if __name__ == "__main__":
258
+ main()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # engine (pinned by the competition kit)
2
+ vllm==0.31.0
3
+ # offline data generation / training
4
+ accelerate
5
+ datasets
6
+ safetensors
7
+ numpy
8
+ huggingface_hub
results/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Kit outputs and summaries written by `scripts/pipeline.sh` (see `scripts/collect.py`).
scripts/bootstrap.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Collect kit results into results/summary.json and results/summary.md.
3
+
4
+ Two scores are reported for every evaluated draft:
5
+ * official - the kit's own score against the organizers' published baseline numbers;
6
+ * same-GPU - the same formula against the baseline as measured in this run on this GPU
7
+ (only when a full baseline evaluation is available).
8
+ """
9
+ import json
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ ROOT = Path(os.environ.get("EMC_ROOT", Path.home() / "emc"))
15
+ KIT = Path(os.environ.get("EMC2_HOME", ROOT / "kit"))
16
+ RES = ROOT / "results"
17
+
18
+
19
+ def score(m, base, cfg):
20
+ w, cap = cfg["weights"], cfg["cap"]
21
+ s_acc = (m["acceptance_length"] - 1) / (base["acceptance_length"] - 1)
22
+ s_mem = min(cap, base["memory_bytes"] / m["memory_bytes"])
23
+ s_tpot = min(cap, base["tpot_median_s"] / m["tpot_median_s"])
24
+ return {"score": round(100 * (w["acceptance"] * s_acc + w["memory"] * s_mem + w["tpot"] * s_tpot), 2),
25
+ "s_acceptance": round(s_acc, 4), "s_memory": round(s_mem, 4), "s_tpot": round(s_tpot, 4),
26
+ "ranked": m["acceptance_length"] >= cfg["acceptance_gate"] * base["acceptance_length"]}
27
+
28
+
29
+ def main():
30
+ cfg = json.loads((KIT / "contract.json").read_text())["score"]
31
+ runs = {}
32
+ for p in sorted(RES.glob("*.json")):
33
+ d = json.loads(p.read_text())
34
+ if "acceptance_length" in d and "per_prompt" in d:
35
+ runs[p.stem] = d
36
+ local_base = runs.get("eval_baseline")
37
+ rows, out = [], {"runs": {}}
38
+ for tag, m in runs.items():
39
+ e = {k: m.get(k) for k in ("method", "prompts", "acceptance_length", "acceptance_by_domain",
40
+ "tpot_median_s", "ttft_median_s", "memory_bytes", "weight_bytes",
41
+ "kv_cache_bytes", "decode_total_s", "engine")}
42
+ e["official_score"] = m.get("score")
43
+ if local_base and m["prompts"] == local_base["prompts"]:
44
+ e["same_gpu_score"] = score(m, local_base, cfg)
45
+ out["runs"][tag] = e
46
+ off = (m.get("score") or {}).get("score")
47
+ same = (e.get("same_gpu_score") or {}).get("score")
48
+ rows.append(f"| {tag} | {m['prompts']} | {m['acceptance_length']:.3f} | "
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")}
59
+ (RES / "summary.json").write_text(json.dumps(out, indent=2))
60
+ md = ["| run | prompts | acceptance | chat / code / math / longform | TPOT ms | memory GB | score (official) | score (same GPU) |",
61
+ "|---|---|---|---|---|---|---|---|", *rows]
62
+ (RES / "summary.md").write_text("\n".join(md) + "\n")
63
+ print("\n".join(md))
64
+ return 0
65
+
66
+
67
+ if __name__ == "__main__":
68
+ sys.exit(main())
scripts/kit.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run the official emc2 kit commands without a container runtime.
3
+
4
+ The kit expects fixed container paths (/models/target, /submission, /work). This launcher
5
+ points those names at local folders and then calls the kit's own entry point unchanged, so
6
+ validation, the engine command line, the metrics and the score are exactly the kit's.
7
+
8
+ EMC2_HOME kit checkout EMC_TARGET target model folder
9
+ EMC_SUB submission folder EMC2_WORK scratch / logs / results
10
+ EMC_TAG optional: copy the newest result file to $EMC_RESULTS/<tag>.json
11
+ """
12
+ import os
13
+ import shutil
14
+ import sys
15
+ import time
16
+ from pathlib import Path
17
+
18
+ kit = Path(os.environ["EMC2_HOME"]).resolve()
19
+ work = Path(os.environ.get("EMC2_WORK", "emc2-work")).resolve()
20
+ work.mkdir(parents=True, exist_ok=True)
21
+ cache = work / "cache"
22
+ os.environ.update({
23
+ "EMC2_HOME": str(kit), "EMC2_WORK": str(work), "PYTHONDONTWRITEBYTECODE": "1",
24
+ "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", "VLLM_NO_USAGE_STATS": "1", "DO_NOT_TRACK": "1",
25
+ "XDG_CACHE_HOME": str(cache), "HF_HOME": str(cache / "hf"), "VLLM_CACHE_ROOT": str(cache / "vllm"),
26
+ "TORCHINDUCTOR_CACHE_DIR": str(cache / "inductor"), "TRITON_CACHE_DIR": str(cache / "triton"),
27
+ "EMC2_IMAGE_USED": os.environ.get("EMC2_IMAGE_USED", "pip:vllm==0.31.0"),
28
+ "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", ""),
29
+ })
30
+ sys.path.insert(0, str(kit))
31
+
32
+ from emc2 import common, evaluate, organizer, server # noqa: E402
33
+ from emc2 import __main__ as cli # noqa: E402
34
+
35
+ target = Path(os.environ["EMC_TARGET"]).resolve() if os.environ.get("EMC_TARGET") else common.TARGET_DIR
36
+ sub = Path(os.environ["EMC_SUB"]).resolve() if os.environ.get("EMC_SUB") else common.SUBMISSION_DIR
37
+ for mod in (common, evaluate, organizer, server, cli):
38
+ for name, value in (("TARGET_DIR", target), ("SUBMISSION_DIR", sub), ("WORK", work)):
39
+ if hasattr(mod, name):
40
+ setattr(mod, name, value)
41
+ evaluate.TARGET_ONLY_LOCAL = work / "target_only_local.json"
42
+
43
+ started = time.time()
44
+ sys.argv = ["emc2", *sys.argv[1:]]
45
+ code = 0
46
+ try:
47
+ cli.main()
48
+ except SystemExit as e:
49
+ code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
50
+ tag, dest = os.environ.get("EMC_TAG"), os.environ.get("EMC_RESULTS")
51
+ if tag and dest and code == 0:
52
+ new = [p for p in (work / "results").glob("*.json") if p.stat().st_mtime >= started]
53
+ if new:
54
+ Path(dest).mkdir(parents=True, exist_ok=True)
55
+ shutil.copy(max(new, key=lambda p: p.stat().st_mtime), Path(dest) / f"{tag}.json")
56
+ sys.exit(code)
scripts/pipeline.sh ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
scripts/sync.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
12
+ import shutil
13
+ 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)
41
+ dst.write_text(text)
42
+ else:
43
+ shutil.copy(src, dst)
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
+
79
+ if __name__ == "__main__":
80
+ sys.exit(main())
tests/test_head.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU self-test with tiny dimensions: no GPU, no model download.
2
+
3
+ python tests/test_head.py
4
+
5
+ Checks the pieces whose correctness the whole pipeline rests on:
6
+ 1. FP8 (E4M3) rounding / encoding round-trips and matches torch's own float8 cast;
7
+ 2. the vectorised K-step `unroll` equals a literal step-by-step emulation of the engine's
8
+ drafting loop with a key/value cache;
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
16
+ import random
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+ from types import SimpleNamespace
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+
25
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
26
+ from emcdraft.head import (FP8_TENSORS, HeadConfig, MTPHead, e4m3_decode, e4m3_encode, e4m3_round, # noqa: E402
27
+ equalize_, export_submission, load_mtp_state, unroll, walk)
28
+ from emcdraft.sim import batches, collate, simulate # noqa: E402
29
+ from emcdraft.train import train_step # noqa: E402
30
+
31
+ torch.manual_seed(0)
32
+ C = HeadConfig(hidden=48, inter=96, heads=6, kv_heads=2, head_dim=16, rot_dim=4, theta=1e4, eps=1e-6)
33
+ V = 211
34
+
35
+
36
+ def test_fp8():
37
+ x = torch.cat([torch.randn(20000) * 0.02, torch.randn(20000) * 0.3, torch.randn(2000) * 50,
38
+ torch.tensor([0.0, 448.0, -448.0, 1e4, 2.0 ** -9, 2.0 ** -10, 3e-4, 2.0 ** -6, 0.99, 1.0])])
39
+ q = e4m3_round(x)
40
+ assert torch.equal(e4m3_round(q), q), "rounding must be idempotent"
41
+ assert torch.equal(e4m3_decode(e4m3_encode(x)), q), "encode/decode must round-trip"
42
+ rel = ((q - x).abs() / x.abs().clamp(min=2.0 ** -6))[x.abs() <= 448]
43
+ assert rel.max() <= 0.0626, rel.max()
44
+ try:
45
+ ref = x.clamp(-448, 448).to(torch.float8_e4m3fn)
46
+ assert torch.equal(ref.float(), q.clamp(-448, 448)), "values differ from torch's float8 cast"
47
+ bits = torch.arange(256, dtype=torch.uint8)
48
+ dec = bits.view(torch.float8_e4m3fn).float()
49
+ ok = dec == dec # skip the two NaN patterns
50
+ assert torch.equal(dec[ok], e4m3_decode(bits)[ok]), "decoder differs from torch's float8 decode"
51
+ print(" fp8: rounding and all 254 finite bit patterns agree with torch.float8_e4m3fn")
52
+ except (RuntimeError, TypeError, AttributeError) as e:
53
+ print(" fp8: torch float8 cast unavailable here, skipped cross-check:", type(e).__name__)
54
+
55
+
56
+ def sequential(head, E, tokens, hidden, i, K=3):
57
+ """Literal emulation of the engine for one round starting at base index i."""
58
+ T = tokens.numel()
59
+ pos = torch.arange(i + 1)[None]
60
+ tri = torch.ones(i + 1, i + 1, dtype=torch.bool).tril()[None, None]
61
+ out, kv = head.step(E[tokens[1:i + 2]][None], hidden[None, :i + 1], pos, (), tri) # verified prefix
62
+ cache_k, cache_v = kv
63
+ h, outs = out[:, -1:], [out[0, -1]]
64
+ for k in range(2, K + 1):
65
+ if i + k > T - 1:
66
+ break
67
+ tok = tokens[i + k]
68
+ n_keys = cache_k.shape[2] + 1
69
+ o, kv = head.step(E[tok][None, None], h, torch.tensor([[i + k - 1]]), [(cache_k, cache_v)],
70
+ torch.ones(1, 1, 1, n_keys, dtype=torch.bool))
71
+ cache_k, cache_v = torch.cat([cache_k, kv[0]], 2), torch.cat([cache_v, kv[1]], 2)
72
+ h = o
73
+ outs.append(o[0, 0])
74
+ return outs
75
+
76
+
77
+ def test_unroll(head, E):
78
+ T = 14
79
+ tokens = torch.randint(0, V, (T,))
80
+ hidden = torch.randn(T - 1, C.hidden)
81
+ par = [o for _, o in unroll(head, lambda ids: E[ids], tokens[None], hidden[None], 3)]
82
+ worst = 0.0
83
+ for i in range(T - 1):
84
+ for k, o in enumerate(sequential(head, E, tokens, hidden, i)):
85
+ worst = max(worst, float((par[k][0, i] - o).abs().max()))
86
+ assert worst < 1e-4, worst
87
+ print(f" unroll == step-by-step cache emulation (max abs diff {worst:.2e})")
88
+
89
+
90
+ def test_equalize(head, E):
91
+ tokens = torch.randint(0, V, (3, 12))
92
+ hidden = torch.randn(3, 11, C.hidden)
93
+ before = [o for _, o in unroll(head, lambda ids: E[ids], tokens, hidden, 3)]
94
+ factors = equalize_(head)
95
+ after = [o for _, o in unroll(head, lambda ids: E[ids], tokens, hidden, 3)]
96
+ drift = max(float((a - b).abs().max() / b.abs().max()) for a, b in zip(after, before))
97
+ assert drift < 1e-3, drift
98
+ rms = {n: round(float(dict(head.named_parameters())[n].pow(2).mean().sqrt()), 3) for n in FP8_TENSORS}
99
+ assert all(abs(v - 0.25) < 1e-3 for v in rms.values()), rms
100
+ print(f" equalize: function preserved (rel drift {drift:.1e}), FP8 tensors at RMS 0.25, s={factors['s']:.2f}")
101
+
102
+
103
+ def test_walk():
104
+ T, P = 12, 4 # tokens 4..11 generated
105
+ c = [[False] * T for _ in range(3)]
106
+ c[0][3] = c[1][3] = True # round at base 3: tokens 5, 6 accepted, 7 rejected
107
+ c[0][6] = c[1][6] = c[2][6] = True # next round at base 6 (cur=7): 8, 9, 10 accepted
108
+ acc, drafts = walk(c, P, T)
109
+ assert (acc, drafts) == (5, 2), (acc, drafts)
110
+ print(" walk: hand-checked example ok")
111
+
112
+
113
+ def test_train_and_export(head, E, W):
114
+ rng = random.Random(0)
115
+ seqs = []
116
+ for d in ("chat", "code", "math", "longform"):
117
+ for _ in range(6):
118
+ T, P = rng.randint(14, 22), rng.randint(3, 6)
119
+ tok = torch.randint(0, V, (T,))
120
+ seqs.append({"tokens": tok, "hidden": torch.randn(T - 1, C.hidden), "P": P, "T": T, "domain": d})
121
+ a = SimpleNamespace(beta=0.5, floor=0.3, step_w=[1.0, 0.7, 0.5])
122
+ head.set_fake_quant(True)
123
+ opt = torch.optim.AdamW(head.parameters(), lr=2e-3)
124
+ embed = lambda ids: F.embedding(ids, E)
125
+ first = last = None
126
+ for it in range(30):
127
+ loss, info = train_step(head, embed, W, collate(seqs), a)
128
+ opt.zero_grad()
129
+ loss.backward()
130
+ opt.step()
131
+ first = info["ce1"] if first is None else first
132
+ last = info["ce1"]
133
+ assert last < first, (first, last)
134
+ sim = simulate(head, embed, W, seqs)
135
+ assert 1.0 <= sim["acceptance_length"] <= 4.0 and len(batches(seqs, 60)) > 1
136
+ print(f" train: ce1 {first:.3f} -> {last:.3f} with FP8 fake-quant; memorised tau {sim['acceptance_length']:.2f}")
137
+ with tempfile.TemporaryDirectory() as tmp:
138
+ cfg = Path(tmp) / "config.json"
139
+ cfg.write_text(json.dumps({"text_config": {"max_position_embeddings": 262144, "mtp_num_hidden_layers": 1,
140
+ "num_attention_heads": 6, "num_key_value_heads": 2, "head_dim": 16}}))
141
+ meta = {"team_id": "t", "method_description": "m", "training_data": "d"}
142
+ for name, fp8 in (("sub_fp8", True), ("sub_bf16", False)):
143
+ info = export_submission(head, Path(tmp) / name, cfg, fp8, meta)
144
+ back = load_mtp_state(Path(tmp) / name)
145
+ for n, p in head.state_dict().items():
146
+ want = e4m3_round(p.float()) if (fp8 and n in FP8_TENSORS) else p.float().to(torch.bfloat16).float()
147
+ assert torch.equal(back[n], want), n
148
+ try:
149
+ from safetensors import safe_open
150
+ with safe_open(str(Path(tmp) / name / "model.safetensors"), framework="pt") as f:
151
+ t = f.get_tensor("mtp." + FP8_TENSORS[0])
152
+ assert ("float8" in str(t.dtype)) == fp8
153
+ except ImportError:
154
+ pass
155
+ kit = os.environ.get("EMC2_HOME")
156
+ if kit:
157
+ sys.path.insert(0, kit)
158
+ from emc2 import submission
159
+ errors, kinfo = submission.check(Path(tmp) / name, json.loads((Path(kit) / "contract.json").read_text()),
160
+ json.loads((Path(kit) / "target.json").read_text()))
161
+ assert not errors, errors
162
+ assert kinfo["weight_bytes"] == info["weight_bytes"]
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():
169
+ torch.nn.init.normal_(p, std=0.08 if p.ndim == 2 else 0.05)
170
+ E, W = torch.randn(V, C.hidden) * 0.5, torch.randn(V, C.hidden) * 0.3
171
+ print("fp8"); test_fp8()
172
+ with torch.no_grad():
173
+ print("unroll"); test_unroll(head, E)
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")