mtpspec 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mtpspec-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mycomputercrashsalot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mtpspec-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: mtpspec
3
+ Version: 0.1.0
4
+ Summary: greedy-exact speculative decoding off a model's own MTP head
5
+ Author: mycomputercrashsalot
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/mycomputercrashsalot/mtpspec
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: torch>=2.0
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest; extra == "test"
14
+ Requires-Dist: transformers; extra == "test"
15
+ Dynamic: license-file
16
+
17
+ # mtpspec
18
+
19
+ greedy-exact speculative decoding off a model's own MTP head.
20
+
21
+ an MTP (multi-token prediction) head — the deepseek-v3-style chain that
22
+ some checkpoints and trainers attach as `model.mtp_layers` — predicts
23
+ several tokens ahead from the trunk's hidden state at one position. that
24
+ is exactly a drafter for speculative decoding: no separate draft model,
25
+ no extra weights to serve, nothing new at inference time.
26
+
27
+ ## the guarantee
28
+
29
+ the loop drafts k proposals from the chain, runs ONE trunk forward over
30
+ [pending, drafts], and accepts the longest prefix that matches the trunk's
31
+ greedy argmax. every emitted token is the trunk's argmax or a draft that
32
+ equaled it, so output is token-for-token identical to plain greedy
33
+ decoding. the head can only change SPEED, never the result. the test
34
+ suite proves this with random heads (accept nothing) and degenerate
35
+ heads — if the verify gate survives those, it survives anything.
36
+
37
+ acceptance stats come back with every call so the speed/tradeoff is
38
+ visible, not vibes.
39
+
40
+ ## install
41
+
42
+ ```
43
+ pip install mtpspec
44
+ ```
45
+
46
+ core dependency is torch alone. transformers is only needed to load
47
+ models with it (and for the test suite).
48
+
49
+ ## use
50
+
51
+ ```python
52
+ from mtpspec import has_mtp, spec_generate, spec_generate_stream
53
+
54
+ model = load_your_model_somehow() # any HF-style causal LM
55
+ if has_mtp(model): # finds model.mtp_layers
56
+ ids, stats = spec_generate(model, input_ids, max_new_tokens=200, k=4)
57
+ print(stats["accepted"], "/", stats["drafted"], "drafts accepted")
58
+
59
+ for piece in spec_generate_stream(model, tokenizer, input_ids, 200, k=4):
60
+ print(piece, end="", flush=True)
61
+ ```
62
+
63
+ `spec_generate_cycles` is the underlying generator if you want tokens per
64
+ cycle instead of the whole tensor.
65
+
66
+ ## sampled mode too
67
+
68
+ ```python
69
+ from mtpspec import spec_generate_sampled
70
+
71
+ ids, stats = spec_generate_sampled(model, input_ids, 200, k=4,
72
+ temperature=1.0, generator=torch.Generator().manual_seed(0))
73
+ ```
74
+
75
+ rejection sampling off the same chain: per slot the depth's proposal
76
+ distribution q is tested against the trunk's conditional p, accept with
77
+ probability min(1, p/q), resample from the residual on rejection.
78
+ completion distribution matches sampling from the trunk directly at the
79
+ same temperature.
80
+
81
+ ## what heads work
82
+
83
+ any chain attached as `mtp_layers` (on the causal-lm wrapper, the bare
84
+ family model, or the top object) where depth module j is callable as
85
+ `m(h, token_emb) -> (h', kv)`:
86
+
87
+ - `h` — trunk final hidden state at one position, `[1, 1, hidden]`
88
+ - `token_emb` — embedding of the token at that position, `[1, 1, hidden]`
89
+ - output predicts the token `j+1` positions ahead of the anchor
90
+
91
+ that's the deepseek-v3 layout, and it's what
92
+ [single-gpu-llm-toolkit](https://github.com/mycomputercrashsalot/single-gpu-llm-toolkit)
93
+ builds (mtp_head.py builds the weights, modeling_custom trains them,
94
+ this package serves them). a shared final norm setattr'd on the
95
+ modulelist (`mtp_layers.norm`) is tolerated and not counted as a depth.
96
+
97
+ the decode loop itself needs no attention-mask plumbing and no family
98
+ knowledge — resolvers find the embed/lm_head/mtp chain, the loop only
99
+ needs `output_hidden_states`, `use_cache`, and a croppable kv cache
100
+ (`DynamicCache.crop`, present in recent transformers).
101
+
102
+ ## the cached chain
103
+
104
+ each MTP depth carries its own KV cache across cycles. every cycle, the
105
+ newly accepted-and-fed positions are pushed through the chain (the
106
+ trunk hiddens come out of the verify forward for free) and each depth's
107
+ output at the new anchor is the next draft base — the ingest IS the
108
+ draft computation. only accepted positions are ingested, so the chain
109
+ stays aligned with the trunk's accepted prefix; rejected drafts never
110
+ touch it. drafting happens in the same full-context regime the chain is
111
+ trained in. on a memorized-trajectory test setup this took the accept
112
+ rate from 0.16 (stateless drafting) to 0.95.
113
+
114
+ ## honest limits
115
+
116
+ - speedup numbers need real hardware and a trained head. correctness is
117
+ what the test suite proves; `bench/mtp_bench.py` turns the accept rate
118
+ into tok/s and tok/cycle (measured against the geometric acceptance
119
+ model) on whatever box you run it. note the loader gotcha: plain
120
+ `AutoModelForCausalLM.from_pretrained` drops `mtp_layers` weights as
121
+ unexpected keys — load with code that knows the chain (the toolkit's
122
+ loader, or trust_remote_code with its modeling file).
123
+ - within a cycle, the k proposals come from the chain's depth outputs at
124
+ one anchor: depth j's distribution does not condition on the tokens
125
+ sampled at depths < j. the rejection-sampling math handles
126
+ history-independent proposals fine (each slot's test uses the
127
+ distribution the token was actually drawn from), but drafts would be
128
+ stronger still with a fully autoregressive drafter.
129
+ - the draft loop uses modules 1..k of the chain: module 0 anchored at
130
+ the last fed position re-proposes the pending token, so it is skipped.
131
+ a chain of D depths drafts at most D-1 tokens per cycle. this was once
132
+ a silent off-by-one (modules 0..k-1, every draft one slot early —
133
+ exact output, chance accept rate, no speedup); the trained-drafter
134
+ test exists so it cannot come back.
135
+
136
+ ## develop
137
+
138
+ ```
139
+ pip install -e '.[test]'
140
+ pytest
141
+ ```
142
+
143
+ mit license.
@@ -0,0 +1,127 @@
1
+ # mtpspec
2
+
3
+ greedy-exact speculative decoding off a model's own MTP head.
4
+
5
+ an MTP (multi-token prediction) head — the deepseek-v3-style chain that
6
+ some checkpoints and trainers attach as `model.mtp_layers` — predicts
7
+ several tokens ahead from the trunk's hidden state at one position. that
8
+ is exactly a drafter for speculative decoding: no separate draft model,
9
+ no extra weights to serve, nothing new at inference time.
10
+
11
+ ## the guarantee
12
+
13
+ the loop drafts k proposals from the chain, runs ONE trunk forward over
14
+ [pending, drafts], and accepts the longest prefix that matches the trunk's
15
+ greedy argmax. every emitted token is the trunk's argmax or a draft that
16
+ equaled it, so output is token-for-token identical to plain greedy
17
+ decoding. the head can only change SPEED, never the result. the test
18
+ suite proves this with random heads (accept nothing) and degenerate
19
+ heads — if the verify gate survives those, it survives anything.
20
+
21
+ acceptance stats come back with every call so the speed/tradeoff is
22
+ visible, not vibes.
23
+
24
+ ## install
25
+
26
+ ```
27
+ pip install mtpspec
28
+ ```
29
+
30
+ core dependency is torch alone. transformers is only needed to load
31
+ models with it (and for the test suite).
32
+
33
+ ## use
34
+
35
+ ```python
36
+ from mtpspec import has_mtp, spec_generate, spec_generate_stream
37
+
38
+ model = load_your_model_somehow() # any HF-style causal LM
39
+ if has_mtp(model): # finds model.mtp_layers
40
+ ids, stats = spec_generate(model, input_ids, max_new_tokens=200, k=4)
41
+ print(stats["accepted"], "/", stats["drafted"], "drafts accepted")
42
+
43
+ for piece in spec_generate_stream(model, tokenizer, input_ids, 200, k=4):
44
+ print(piece, end="", flush=True)
45
+ ```
46
+
47
+ `spec_generate_cycles` is the underlying generator if you want tokens per
48
+ cycle instead of the whole tensor.
49
+
50
+ ## sampled mode too
51
+
52
+ ```python
53
+ from mtpspec import spec_generate_sampled
54
+
55
+ ids, stats = spec_generate_sampled(model, input_ids, 200, k=4,
56
+ temperature=1.0, generator=torch.Generator().manual_seed(0))
57
+ ```
58
+
59
+ rejection sampling off the same chain: per slot the depth's proposal
60
+ distribution q is tested against the trunk's conditional p, accept with
61
+ probability min(1, p/q), resample from the residual on rejection.
62
+ completion distribution matches sampling from the trunk directly at the
63
+ same temperature.
64
+
65
+ ## what heads work
66
+
67
+ any chain attached as `mtp_layers` (on the causal-lm wrapper, the bare
68
+ family model, or the top object) where depth module j is callable as
69
+ `m(h, token_emb) -> (h', kv)`:
70
+
71
+ - `h` — trunk final hidden state at one position, `[1, 1, hidden]`
72
+ - `token_emb` — embedding of the token at that position, `[1, 1, hidden]`
73
+ - output predicts the token `j+1` positions ahead of the anchor
74
+
75
+ that's the deepseek-v3 layout, and it's what
76
+ [single-gpu-llm-toolkit](https://github.com/mycomputercrashsalot/single-gpu-llm-toolkit)
77
+ builds (mtp_head.py builds the weights, modeling_custom trains them,
78
+ this package serves them). a shared final norm setattr'd on the
79
+ modulelist (`mtp_layers.norm`) is tolerated and not counted as a depth.
80
+
81
+ the decode loop itself needs no attention-mask plumbing and no family
82
+ knowledge — resolvers find the embed/lm_head/mtp chain, the loop only
83
+ needs `output_hidden_states`, `use_cache`, and a croppable kv cache
84
+ (`DynamicCache.crop`, present in recent transformers).
85
+
86
+ ## the cached chain
87
+
88
+ each MTP depth carries its own KV cache across cycles. every cycle, the
89
+ newly accepted-and-fed positions are pushed through the chain (the
90
+ trunk hiddens come out of the verify forward for free) and each depth's
91
+ output at the new anchor is the next draft base — the ingest IS the
92
+ draft computation. only accepted positions are ingested, so the chain
93
+ stays aligned with the trunk's accepted prefix; rejected drafts never
94
+ touch it. drafting happens in the same full-context regime the chain is
95
+ trained in. on a memorized-trajectory test setup this took the accept
96
+ rate from 0.16 (stateless drafting) to 0.95.
97
+
98
+ ## honest limits
99
+
100
+ - speedup numbers need real hardware and a trained head. correctness is
101
+ what the test suite proves; `bench/mtp_bench.py` turns the accept rate
102
+ into tok/s and tok/cycle (measured against the geometric acceptance
103
+ model) on whatever box you run it. note the loader gotcha: plain
104
+ `AutoModelForCausalLM.from_pretrained` drops `mtp_layers` weights as
105
+ unexpected keys — load with code that knows the chain (the toolkit's
106
+ loader, or trust_remote_code with its modeling file).
107
+ - within a cycle, the k proposals come from the chain's depth outputs at
108
+ one anchor: depth j's distribution does not condition on the tokens
109
+ sampled at depths < j. the rejection-sampling math handles
110
+ history-independent proposals fine (each slot's test uses the
111
+ distribution the token was actually drawn from), but drafts would be
112
+ stronger still with a fully autoregressive drafter.
113
+ - the draft loop uses modules 1..k of the chain: module 0 anchored at
114
+ the last fed position re-proposes the pending token, so it is skipped.
115
+ a chain of D depths drafts at most D-1 tokens per cycle. this was once
116
+ a silent off-by-one (modules 0..k-1, every draft one slot early —
117
+ exact output, chance accept rate, no speedup); the trained-drafter
118
+ test exists so it cannot come back.
119
+
120
+ ## develop
121
+
122
+ ```
123
+ pip install -e '.[test]'
124
+ pytest
125
+ ```
126
+
127
+ mit license.
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mtpspec"
7
+ version = "0.1.0"
8
+ description = "greedy-exact speculative decoding off a model's own MTP head"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "mycomputercrashsalot" }]
13
+ dependencies = ["torch>=2.0"]
14
+
15
+ [project.optional-dependencies]
16
+ test = ["pytest", "transformers"]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/mycomputercrashsalot/mtpspec"
20
+
21
+ [tool.setuptools.packages.find]
22
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,34 @@
1
+ """mtpspec — greedy-exact speculative decoding off a model's own MTP head.
2
+
3
+ An MTP (multi-token prediction) head — the DeepSeek-V3-style chain some
4
+ checkpoints and trainers attach as `model.mtp_layers` — predicts several
5
+ tokens ahead from the trunk's hidden state at one position. That is
6
+ exactly a drafter for speculative decoding: no separate draft model, no
7
+ extra weights to serve.
8
+
9
+ The loop drafts k proposals from the chain, runs ONE trunk forward over
10
+ [pending, drafts], and accepts the longest prefix that matches the trunk's
11
+ argmax. Greedy output is token-for-token identical to plain greedy
12
+ decoding — the head can only change SPEED, never the result.
13
+
14
+ Core dependency is torch alone; transformers is only needed if you load
15
+ models with it (and for the test suite).
16
+ """
17
+
18
+ from .core import spec_generate, spec_generate_cycles
19
+ from .resolve import has_mtp, resolve_embed, resolve_lm_head, resolve_mtp
20
+ from .sampled import spec_generate_sampled
21
+ from .stream import spec_generate_stream
22
+
23
+ __version__ = "0.1.0"
24
+
25
+ __all__ = [
26
+ "has_mtp",
27
+ "resolve_mtp",
28
+ "resolve_embed",
29
+ "resolve_lm_head",
30
+ "spec_generate",
31
+ "spec_generate_cycles",
32
+ "spec_generate_stream",
33
+ "spec_generate_sampled",
34
+ ]
@@ -0,0 +1,179 @@
1
+ """The verify-gated decode loop.
2
+
3
+ One function does everything: `spec_generate_cycles` is a generator that
4
+ runs draft/verify cycles and yields each cycle's proven tokens. Everything
5
+ else (`spec_generate`, `mtpspec.stream.spec_generate_stream`) is a thin
6
+ consumer of it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import torch
12
+
13
+ from .resolve import resolve_embed, resolve_lm_head, resolve_mtp
14
+
15
+
16
+ def _call_depth(mod, h, token_emb, past_key_value=None):
17
+ """Call one MTP depth module with the package's chain contract.
18
+
19
+ Preferred signature: mod(h, token_emb, past_key_value=kv) -> (h', kv).
20
+ Modules with the older two-argument signature still work — they are
21
+ simply drafted statelessly (no cross-cycle context; exactness is never
22
+ affected, only the accept rate).
23
+ """
24
+ try:
25
+ return mod(h, token_emb, past_key_value=past_key_value)
26
+ except TypeError:
27
+ return mod(h, token_emb)
28
+
29
+
30
+ def spec_generate_cycles(model, input_ids, max_new_tokens, k=None):
31
+ """Generator: run spec-decode cycles, yielding (emitted, stats) per cycle.
32
+
33
+ `emitted` is the list of new token ids this cycle proved (the accepted
34
+ drafts plus the correction; the bootstrap pending comes out as the
35
+ first yield). `stats` is one live dict mutated in place — read it after
36
+ the generator is exhausted.
37
+
38
+ Contract on the MTP chain (the DeepSeek-V3-style layout): depth module
39
+ j is callable as `m(h, token_emb) -> (h', kv)` where `h` is the trunk's
40
+ final hidden state at one position, `token_emb` the embedding of the
41
+ token at that position, and the module's output predicts the token
42
+ `j+1` positions ahead of the anchor. The toolkit's modeling_custom and
43
+ mtp_head build exactly this shape.
44
+
45
+ Greedy exactness: every emitted token is the trunk's argmax or a draft
46
+ that equaled it, so the output is token-for-token identical to plain
47
+ greedy decoding. The head can only change SPEED, never the result.
48
+ """
49
+ mtp, _norm = resolve_mtp(model)
50
+ if mtp is None:
51
+ raise ValueError(
52
+ "this model has no MTP head (no mtp_layers found) — spec decoding "
53
+ "needs a checkpoint with an MTP chain attached")
54
+ depths = len(mtp)
55
+ # Draft slots are x_{L+1}..x_{L+k}. Module j anchored at the last fed
56
+ # position L-1 predicts x_{L+j} (shift j+1 — the training objective in
57
+ # shift_labels), so module 0's proposal is the pending itself (already
58
+ # decided) and the USABLE proposals for those slots come from modules
59
+ # 1..k. A head shallower than 2 depths cannot draft anything the trunk
60
+ # has not already decided.
61
+ k = min(k if k else depths - 1, depths - 1)
62
+ if k < 1:
63
+ raise ValueError(
64
+ "the MTP chain needs at least 2 depths to draft (module 0 only "
65
+ "re-proposes the pending token); this model has " + str(depths))
66
+ embed = resolve_embed(model)
67
+ lm_head = resolve_lm_head(model)
68
+
69
+ stats = {"cycles": 0, "drafted": 0, "accepted": 0, "emitted": 0,
70
+ "depths": depths, "k": k}
71
+
72
+ with torch.no_grad():
73
+ # ── prefill: trunk over the prompt; everything anchors here
74
+ out = model(input_ids=input_ids, use_cache=True,
75
+ output_hidden_states=True, return_dict=True)
76
+ cache = out.past_key_values
77
+ L = input_ids.shape[1] # cache length == accepted prefix length
78
+ pending = out.logits[:, -1, :].argmax(dim=-1) # token for position L
79
+
80
+ # ── chain prefill: ingest the prompt positions through the MTP
81
+ # chain, one KV cache per depth. Each depth's block sees the full
82
+ # ingested history — the same contiguous-positions context the
83
+ # chain is trained with — so drafting happens in distribution.
84
+ # The ingest IS the draft computation: module j's output at the
85
+ # last ingested position (the anchor) is its proposal base for
86
+ # x_{anchor+j+1}.
87
+ chain_caches = [None] * depths
88
+ h_batch = out.hidden_states[-1] # [1, L, H]
89
+ emb_batch = embed(input_ids) # [1, L, H]
90
+ draft_h = [None] * depths # per-depth anchor outputs
91
+ for i, mod in enumerate(mtp):
92
+ h_batch, kv = _call_depth(mod, h_batch, emb_batch, chain_caches[i])
93
+ chain_caches[i] = kv
94
+ draft_h[i] = h_batch[:, -1:, :] # [1,1,H] at the anchor
95
+
96
+ # the first pending is the only token no previous cycle emitted
97
+ stats["emitted"] = 1
98
+ yield [pending.item()], stats
99
+
100
+ while stats["emitted"] < max_new_tokens:
101
+ # ── draft: modules 1..k from the chain's anchor outputs. Module
102
+ # j anchored at the last fed position L-1 predicts x_{L+j}
103
+ # (shift j+1, the training objective), so module 0 re-proposes
104
+ # the pending and modules 1..k propose x_{L+1}..x_{L+k} —
105
+ # exactly the slots the verify step below assigns them.
106
+ # Semantically aligned drafts are what make the accept rate
107
+ # meaningful; misaligned drafts would still verify exactly (the
108
+ # gate compares values, not meanings) but accept at chance.
109
+ drafts = []
110
+ for i in range(1, k + 1):
111
+ logits_i = lm_head(draft_h[i]) # [1,1,V]
112
+ drafts.append(logits_i[:, -1, :].argmax(dim=-1))
113
+
114
+ # ── verify: one trunk forward over [pending, d_1..d_k]
115
+ feed = torch.cat([pending.unsqueeze(0)]
116
+ + [d.unsqueeze(0) for d in drafts], dim=1)
117
+ out = model(input_ids=feed, past_key_values=cache, use_cache=True,
118
+ output_hidden_states=True, return_dict=True)
119
+ # fed position j holds the token at position L+j; its logits are
120
+ # the distribution for x_{L+j+1}. t_1 comes from feeding pending;
121
+ # t_{j+1} from feeding d_j.
122
+ verify_argmax = out.logits[:, :, :].argmax(dim=-1) # [1, k+1]
123
+
124
+ m = 0
125
+ while m < k and drafts[m].item() == verify_argmax[0, m].item():
126
+ m += 1
127
+ correction = verify_argmax[0, m:m + 1] # t_{m+1}, always exists
128
+
129
+ # ── emit: d_1..d_m + correction (m+1 tokens). the pending itself
130
+ # was already emitted — by the previous cycle's correction (or by
131
+ # the prefill bootstrap for the first one).
132
+ emitted = [d.item() for d in drafts[:m]] + [correction.item()]
133
+ stats["cycles"] += 1
134
+ stats["drafted"] += k
135
+ stats["accepted"] += m
136
+ stats["emitted"] += len(emitted)
137
+ yield emitted, stats
138
+
139
+ # ── roll state forward
140
+ # the trunk cache now holds 0..L+k (it was fed pending + all k
141
+ # drafts). accepted-and-fed: through position L+m (pending at L,
142
+ # d_1..d_m at L+1..L+m) — crop the rejected tail. The correction
143
+ # sits at position L+m+1: it is accepted but NOT fed, so it
144
+ # becomes the new pending.
145
+ new_L = L + m + 1
146
+ cache.crop(new_L)
147
+
148
+ # ── chain ingest: push the accepted-and-fed positions L..L+m
149
+ # through the MTP chain (trunk hiddens for them came out of the
150
+ # verify forward). Only accepted positions are ingested, so the
151
+ # chain stays exactly aligned with the trunk's accepted prefix —
152
+ # rejected drafts never touch the chain KV. Each depth's output
153
+ # at the new anchor becomes the next cycle's draft base.
154
+ h_new = out.hidden_states[-1][:, 0:m + 1, :] # [1, m+1, H]
155
+ emb_new = embed(feed[:, 0:m + 1]) # [1, m+1, H]
156
+ for i, mod in enumerate(mtp):
157
+ h_new, kv = _call_depth(mod, h_new, emb_new, chain_caches[i])
158
+ chain_caches[i] = kv
159
+ draft_h[i] = h_new[:, -1:, :]
160
+
161
+ pending = correction
162
+ L = new_L
163
+
164
+
165
+ def spec_generate(model, input_ids, max_new_tokens, k=None):
166
+ """Greedy speculative decoding. Returns (generated_ids, stats).
167
+
168
+ generated_ids: 1-D LongTensor of at most max_new_tokens tokens, exactly
169
+ what plain greedy decoding would emit.
170
+ stats: dict with cycles, drafted, accepted, emitted, depths, k.
171
+ """
172
+ out_tokens = []
173
+ stats = None
174
+ for emitted, stats in spec_generate_cycles(model, input_ids, max_new_tokens, k):
175
+ out_tokens.extend(emitted)
176
+ if len(out_tokens) > max_new_tokens:
177
+ out_tokens = out_tokens[:max_new_tokens]
178
+ stats["emitted"] = max_new_tokens
179
+ return torch.tensor(out_tokens, dtype=torch.long), stats
@@ -0,0 +1,63 @@
1
+ """Find the MTP chain and the trunk's embedding / lm_head on any HF-style model.
2
+
3
+ Family variance lives here, not in the decode loop: if a new model family
4
+ attaches its MTP head somewhere new, this is the only file that changes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+
10
+ def resolve_mtp(model):
11
+ """Return (list_of_MTP_depth_modules, shared_final_norm_or_None).
12
+
13
+ Looks for `mtp_layers` on the CausalLM wrapper, the bare family model
14
+ (Llama's `.model`, GPT-2's `.transformer`), or the top object —
15
+ whichever carries it. The chain is expected as a ModuleList whose
16
+ integer-keyed entries are the depth modules, in order. A shared final
17
+ norm hung on the ModuleList itself (`mtp_layers.norm`, the pattern the
18
+ single-gpu-llm-toolkit's modeling_custom uses) is returned separately
19
+ so it does not count as a depth.
20
+
21
+ Returns (None, None) when the model has no MTP head.
22
+ """
23
+ candidates = [
24
+ getattr(model, "mtp_layers", None),
25
+ getattr(getattr(model, "model", None), "mtp_layers", None),
26
+ getattr(getattr(model, "transformer", None), "mtp_layers", None),
27
+ ]
28
+ mods = next((c for c in candidates if c is not None), None)
29
+ if mods is None:
30
+ return None, None
31
+ norm = getattr(mods, "norm", None)
32
+ # nn.ModuleList.__iter__ yields _modules.values(), which includes any
33
+ # attribute registered on it — a shared final norm setattr'd there would
34
+ # silently count as a depth. Keep only the integer-keyed list entries.
35
+ inner = getattr(mods, "_modules", None)
36
+ if inner is not None:
37
+ # dict insertion order is '0','1',… then any setattr'd extras
38
+ mods = [v for k, v in inner.items() if k.isdigit()]
39
+ else:
40
+ mods = list(mods)
41
+ return mods, norm
42
+
43
+
44
+ def has_mtp(model) -> bool:
45
+ """True when this model carries an MTP chain spec decoding can draft from."""
46
+ return resolve_mtp(model)[0] is not None
47
+
48
+
49
+ def resolve_embed(model):
50
+ """The token-embedding module (Llama/Gemma embed_tokens, GPT-2 wte, ...)."""
51
+ for holder in (getattr(model, "model", None), getattr(model, "transformer", None), model):
52
+ for name in ("embed_tokens", "wte", "word_embeddings", "embed_in"):
53
+ m = getattr(holder, name, None)
54
+ if m is not None:
55
+ return m
56
+ raise ValueError("cannot find the token-embedding module on this model")
57
+
58
+
59
+ def resolve_lm_head(model):
60
+ m = getattr(model, "lm_head", None)
61
+ if m is None:
62
+ raise ValueError("cannot find lm_head on this model")
63
+ return m
@@ -0,0 +1,155 @@
1
+ """Sampled speculative decoding (rejection sampling).
2
+
3
+ The greedy loop proves exactness; this extends the same verify-gated
4
+ structure to sampling. Per slot j the chain's depth output gives a
5
+ proposal distribution q_j (softmax of lm_head at temperature); the trunk
6
+ verify forward gives the target conditional p_j. A proposal x_j ~ q_j is
7
+ accepted with probability min(1, p_j(x_j)/q_j(x_j)); on the first
8
+ rejection the correction is resampled from norm(max(p_j - q_j, 0)).
9
+ Every accepted-or-resampled token is distributed exactly per the trunk,
10
+ so completions match sampling from the trunk directly at the same
11
+ temperature.
12
+
13
+ The chain's per-slot proposals are computed from the cached chain state
14
+ before the cycle's samples exist, so q_j does not depend on the earlier
15
+ samples within the cycle — a history-independent proposal, which the
16
+ sequential rejection identity handles fine: each slot's test uses the
17
+ q_j the token was actually drawn from.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+
25
+ from .core import _call_depth
26
+ from .resolve import resolve_embed, resolve_lm_head, resolve_mtp
27
+
28
+
29
+ def _probs(logits, temperature):
30
+ """[B, V] or [1, 1, V] logits -> [V] probabilities at temperature."""
31
+ v = logits.reshape(-1, logits.shape[-1])
32
+ return F.softmax(v[0] / max(temperature, 1e-8), dim=-1)
33
+
34
+
35
+ def _sample(probs, generator):
36
+ idx = torch.multinomial(probs, 1, generator=generator)
37
+ return idx
38
+
39
+
40
+ def spec_generate_sampled(model, input_ids, max_new_tokens, k=None,
41
+ temperature=1.0, generator=None):
42
+ """Sampled speculative decoding. Returns (generated_ids, stats).
43
+
44
+ generated_ids: 1-D LongTensor of at most max_new_tokens tokens whose
45
+ distribution matches sampling from the trunk at `temperature`.
46
+ stats additionally carries `resampled`: corrections drawn from the
47
+ residual distribution (i.e. draft rejections).
48
+ """
49
+ mtp, _norm = resolve_mtp(model)
50
+ if mtp is None:
51
+ raise ValueError("this model has no MTP head (no mtp_layers found)")
52
+ depths = len(mtp)
53
+ k = min(k if k else depths - 1, depths - 1)
54
+ if k < 1:
55
+ raise ValueError(
56
+ "the MTP chain needs at least 2 depths to draft (module 0 only "
57
+ "re-proposes the pending token); this model has " + str(depths))
58
+ embed = resolve_embed(model)
59
+ lm_head = resolve_lm_head(model)
60
+
61
+ stats = {"cycles": 0, "drafted": 0, "accepted": 0, "emitted": 0,
62
+ "resampled": 0, "depths": depths, "k": k}
63
+
64
+ out_tokens = []
65
+
66
+ with torch.no_grad():
67
+ # ── prefill
68
+ out = model(input_ids=input_ids, use_cache=True,
69
+ output_hidden_states=True, return_dict=True)
70
+ cache = out.past_key_values
71
+ L = input_ids.shape[1]
72
+ pending_dist = _probs(out.logits[:, -1, :], temperature)
73
+ pending = _sample(pending_dist, generator)
74
+
75
+ # ── chain prefill (mirrors the greedy loop)
76
+ chain_caches = [None] * depths
77
+ h_batch = out.hidden_states[-1]
78
+ emb_batch = embed(input_ids)
79
+ draft_h = [None] * depths
80
+ for i, mod in enumerate(mtp):
81
+ h_batch, kv = _call_depth(mod, h_batch, emb_batch, chain_caches[i])
82
+ chain_caches[i] = kv
83
+ draft_h[i] = h_batch[:, -1:, :]
84
+
85
+ stats["emitted"] = 1
86
+ out_tokens.append(pending.item())
87
+
88
+ while stats["emitted"] < max_new_tokens:
89
+ # ── draft: sample from each depth's proposal distribution
90
+ drafts = []
91
+ draft_dists = []
92
+ for i in range(1, k + 1):
93
+ q = _probs(lm_head(draft_h[i]), temperature)
94
+ draft_dists.append(q)
95
+ drafts.append(_sample(q, generator))
96
+
97
+ # ── verify: one trunk forward over [pending, drafts]
98
+ feed = torch.cat([pending.unsqueeze(0)]
99
+ + [d.unsqueeze(0) for d in drafts], dim=1)
100
+ out = model(input_ids=feed, past_key_values=cache, use_cache=True,
101
+ output_hidden_states=True, return_dict=True)
102
+ # target conditionals: fed position j gives p(·|prefix, x_<=j)
103
+ target_dists = [_probs(out.logits[:, j, :], temperature)
104
+ for j in range(k + 1)]
105
+
106
+ # ── sequential acceptance
107
+ m = 0
108
+ while m < k:
109
+ d = drafts[m]
110
+ p_at_d = target_dists[m][d]
111
+ q_at_d = draft_dists[m][d]
112
+ if torch.rand(1, generator=generator).item() < min(
113
+ 1.0, (p_at_d / q_at_d).item()):
114
+ m += 1
115
+ else:
116
+ break
117
+
118
+ if m < k:
119
+ # rejected at slot m: resample from the residual
120
+ residual = torch.clamp(target_dists[m] - draft_dists[m], min=0)
121
+ total = residual.sum()
122
+ if total > 0:
123
+ correction = _sample(residual / total, generator)
124
+ stats["resampled"] += 1
125
+ else:
126
+ # q dominated p everywhere at this slot (can happen at
127
+ # low temperature): fall back to the target itself
128
+ correction = _sample(target_dists[m], generator)
129
+ else:
130
+ # all drafts accepted: bonus token from the last target
131
+ correction = _sample(target_dists[k], generator)
132
+
133
+ emitted = [d.item() for d in drafts[:m]] + [correction.item()]
134
+ stats["cycles"] += 1
135
+ stats["drafted"] += k
136
+ stats["accepted"] += m
137
+ stats["emitted"] += len(emitted)
138
+ out_tokens.extend(emitted)
139
+
140
+ # ── roll: crop trunk cache, ingest accepted positions
141
+ new_L = L + m + 1
142
+ cache.crop(new_L)
143
+ h_new = out.hidden_states[-1][:, 0:m + 1, :]
144
+ emb_new = embed(feed[:, 0:m + 1])
145
+ for i, mod in enumerate(mtp):
146
+ h_new, kv = _call_depth(mod, h_new, emb_new, chain_caches[i])
147
+ chain_caches[i] = kv
148
+ draft_h[i] = h_new[:, -1:, :]
149
+ pending = correction
150
+ L = new_L
151
+
152
+ if len(out_tokens) > max_new_tokens:
153
+ out_tokens = out_tokens[:max_new_tokens]
154
+ stats["emitted"] = max_new_tokens
155
+ return torch.tensor(out_tokens, dtype=torch.long), stats
@@ -0,0 +1,31 @@
1
+ """Streaming decode on top of the cycle generator.
2
+
3
+ The contract matches the usual HF streamer pattern: a generator of str
4
+ pieces that concatenate to the full completion.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from .core import spec_generate_cycles
10
+
11
+
12
+ def spec_generate_stream(model, tokenizer, input_ids, max_new_tokens, k=None):
13
+ """Yield decoded text fragments as spec cycles prove tokens.
14
+
15
+ Decoding is a full-decode diff with a trailing replacement-character
16
+ holdback, so a multi-byte sequence split across cycle boundaries is
17
+ never emitted half-formed: if the current full decode ends in U+FFFD,
18
+ that character is held back until the next cycle either resolves it
19
+ or the decode ends there.
20
+ """
21
+ all_ids = []
22
+ sent_upto = 0
23
+ for emitted, _stats in spec_generate_cycles(model, input_ids,
24
+ max_new_tokens, k):
25
+ all_ids.extend(emitted[:max_new_tokens - len(all_ids)])
26
+ text = tokenizer.decode(all_ids, skip_special_tokens=True)
27
+ if text.endswith("\ufffd"):
28
+ text = text[:-1] # may resolve once more tokens arrive
29
+ if len(text) > sent_upto:
30
+ yield text[sent_upto:]
31
+ sent_upto = len(text)
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: mtpspec
3
+ Version: 0.1.0
4
+ Summary: greedy-exact speculative decoding off a model's own MTP head
5
+ Author: mycomputercrashsalot
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/mycomputercrashsalot/mtpspec
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: torch>=2.0
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest; extra == "test"
14
+ Requires-Dist: transformers; extra == "test"
15
+ Dynamic: license-file
16
+
17
+ # mtpspec
18
+
19
+ greedy-exact speculative decoding off a model's own MTP head.
20
+
21
+ an MTP (multi-token prediction) head — the deepseek-v3-style chain that
22
+ some checkpoints and trainers attach as `model.mtp_layers` — predicts
23
+ several tokens ahead from the trunk's hidden state at one position. that
24
+ is exactly a drafter for speculative decoding: no separate draft model,
25
+ no extra weights to serve, nothing new at inference time.
26
+
27
+ ## the guarantee
28
+
29
+ the loop drafts k proposals from the chain, runs ONE trunk forward over
30
+ [pending, drafts], and accepts the longest prefix that matches the trunk's
31
+ greedy argmax. every emitted token is the trunk's argmax or a draft that
32
+ equaled it, so output is token-for-token identical to plain greedy
33
+ decoding. the head can only change SPEED, never the result. the test
34
+ suite proves this with random heads (accept nothing) and degenerate
35
+ heads — if the verify gate survives those, it survives anything.
36
+
37
+ acceptance stats come back with every call so the speed/tradeoff is
38
+ visible, not vibes.
39
+
40
+ ## install
41
+
42
+ ```
43
+ pip install mtpspec
44
+ ```
45
+
46
+ core dependency is torch alone. transformers is only needed to load
47
+ models with it (and for the test suite).
48
+
49
+ ## use
50
+
51
+ ```python
52
+ from mtpspec import has_mtp, spec_generate, spec_generate_stream
53
+
54
+ model = load_your_model_somehow() # any HF-style causal LM
55
+ if has_mtp(model): # finds model.mtp_layers
56
+ ids, stats = spec_generate(model, input_ids, max_new_tokens=200, k=4)
57
+ print(stats["accepted"], "/", stats["drafted"], "drafts accepted")
58
+
59
+ for piece in spec_generate_stream(model, tokenizer, input_ids, 200, k=4):
60
+ print(piece, end="", flush=True)
61
+ ```
62
+
63
+ `spec_generate_cycles` is the underlying generator if you want tokens per
64
+ cycle instead of the whole tensor.
65
+
66
+ ## sampled mode too
67
+
68
+ ```python
69
+ from mtpspec import spec_generate_sampled
70
+
71
+ ids, stats = spec_generate_sampled(model, input_ids, 200, k=4,
72
+ temperature=1.0, generator=torch.Generator().manual_seed(0))
73
+ ```
74
+
75
+ rejection sampling off the same chain: per slot the depth's proposal
76
+ distribution q is tested against the trunk's conditional p, accept with
77
+ probability min(1, p/q), resample from the residual on rejection.
78
+ completion distribution matches sampling from the trunk directly at the
79
+ same temperature.
80
+
81
+ ## what heads work
82
+
83
+ any chain attached as `mtp_layers` (on the causal-lm wrapper, the bare
84
+ family model, or the top object) where depth module j is callable as
85
+ `m(h, token_emb) -> (h', kv)`:
86
+
87
+ - `h` — trunk final hidden state at one position, `[1, 1, hidden]`
88
+ - `token_emb` — embedding of the token at that position, `[1, 1, hidden]`
89
+ - output predicts the token `j+1` positions ahead of the anchor
90
+
91
+ that's the deepseek-v3 layout, and it's what
92
+ [single-gpu-llm-toolkit](https://github.com/mycomputercrashsalot/single-gpu-llm-toolkit)
93
+ builds (mtp_head.py builds the weights, modeling_custom trains them,
94
+ this package serves them). a shared final norm setattr'd on the
95
+ modulelist (`mtp_layers.norm`) is tolerated and not counted as a depth.
96
+
97
+ the decode loop itself needs no attention-mask plumbing and no family
98
+ knowledge — resolvers find the embed/lm_head/mtp chain, the loop only
99
+ needs `output_hidden_states`, `use_cache`, and a croppable kv cache
100
+ (`DynamicCache.crop`, present in recent transformers).
101
+
102
+ ## the cached chain
103
+
104
+ each MTP depth carries its own KV cache across cycles. every cycle, the
105
+ newly accepted-and-fed positions are pushed through the chain (the
106
+ trunk hiddens come out of the verify forward for free) and each depth's
107
+ output at the new anchor is the next draft base — the ingest IS the
108
+ draft computation. only accepted positions are ingested, so the chain
109
+ stays aligned with the trunk's accepted prefix; rejected drafts never
110
+ touch it. drafting happens in the same full-context regime the chain is
111
+ trained in. on a memorized-trajectory test setup this took the accept
112
+ rate from 0.16 (stateless drafting) to 0.95.
113
+
114
+ ## honest limits
115
+
116
+ - speedup numbers need real hardware and a trained head. correctness is
117
+ what the test suite proves; `bench/mtp_bench.py` turns the accept rate
118
+ into tok/s and tok/cycle (measured against the geometric acceptance
119
+ model) on whatever box you run it. note the loader gotcha: plain
120
+ `AutoModelForCausalLM.from_pretrained` drops `mtp_layers` weights as
121
+ unexpected keys — load with code that knows the chain (the toolkit's
122
+ loader, or trust_remote_code with its modeling file).
123
+ - within a cycle, the k proposals come from the chain's depth outputs at
124
+ one anchor: depth j's distribution does not condition on the tokens
125
+ sampled at depths < j. the rejection-sampling math handles
126
+ history-independent proposals fine (each slot's test uses the
127
+ distribution the token was actually drawn from), but drafts would be
128
+ stronger still with a fully autoregressive drafter.
129
+ - the draft loop uses modules 1..k of the chain: module 0 anchored at
130
+ the last fed position re-proposes the pending token, so it is skipped.
131
+ a chain of D depths drafts at most D-1 tokens per cycle. this was once
132
+ a silent off-by-one (modules 0..k-1, every draft one slot early —
133
+ exact output, chance accept rate, no speedup); the trained-drafter
134
+ test exists so it cannot come back.
135
+
136
+ ## develop
137
+
138
+ ```
139
+ pip install -e '.[test]'
140
+ pytest
141
+ ```
142
+
143
+ mit license.
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/mtpspec/__init__.py
5
+ src/mtpspec/core.py
6
+ src/mtpspec/resolve.py
7
+ src/mtpspec/sampled.py
8
+ src/mtpspec/stream.py
9
+ src/mtpspec.egg-info/PKG-INFO
10
+ src/mtpspec.egg-info/SOURCES.txt
11
+ src/mtpspec.egg-info/dependency_links.txt
12
+ src/mtpspec.egg-info/requires.txt
13
+ src/mtpspec.egg-info/top_level.txt
14
+ tests/test_accept.py
15
+ tests/test_exact.py
16
+ tests/test_sampled.py
17
+ tests/test_stream.py
@@ -0,0 +1,5 @@
1
+ torch>=2.0
2
+
3
+ [test]
4
+ pytest
5
+ transformers
@@ -0,0 +1 @@
1
+ mtpspec
@@ -0,0 +1,123 @@
1
+ """Accept-rate semantics: a drafter trained on the trunk's own greedy
2
+ trajectory must actually get accepted — and a misaligned drafter must not.
3
+
4
+ This is the test that pins the draft/verify SLOT ALIGNMENT. Module j
5
+ anchored at the last fed position proposes the slot j+1 ahead (shift
6
+ j+1 — the training objective). The historical bug drafted with modules
7
+ 0..k-1 instead of 1..k, landing every proposal one slot early: output
8
+ stays greedy-exact (the gate compares values, not meanings) but
9
+ acceptance collapses and the head never speeds anything up.
10
+ Degenerate-head exactness tests cannot see this; only a trained
11
+ drafter on a DIVERSE trajectory can.
12
+
13
+ Why the construction is what it is:
14
+
15
+ - an untrained tiny model's greedy generations are extremely repetitive
16
+ (80%+ adjacent-equal) — on those, predicting slot j and slot j+1
17
+ barely differ and even a misaligned drafter scores high. so the trunk
18
+ is first taught a fixed sequence with NO adjacent repeats; its greedy
19
+ replay from the 16-token prefix then regenerates that sequence
20
+ exactly (verified in-test).
21
+ - the MTP chain is trained on that same trajectory with the standard
22
+ shift objective, which on the trunk's own greedy replay coincides
23
+ with "predict the trunk's argmax for that slot".
24
+ - stateless drafting evaluates each depth at a single position, while
25
+ training gave the depth blocks full-sequence context — so even the
26
+ aligned accept rate is modest. that is the documented
27
+ stateless-drafts limitation, visible here as a number; the cached
28
+ chain (when it lands) should push this toward 1.0 on the same test.
29
+
30
+ Verified against the historical bug: aligned ~0.16, misaligned 0.00,
31
+ outputs identical (the gate holds either way).
32
+ """
33
+
34
+ import copy
35
+
36
+ import pytest
37
+ import torch
38
+ import torch.nn.functional as F
39
+
40
+ from mtpspec import resolve_mtp, spec_generate
41
+
42
+ from conftest import RefMTPModule, RefRMSNorm, build_tiny_model_with_mtp
43
+
44
+ SEQ_LEN = 96
45
+ PROMPT_LEN = 16
46
+ TRUNK_STEPS = 1500
47
+ CHAIN_STEPS = 1500
48
+ LR = 3e-3
49
+
50
+
51
+ def _diverse_sequence(seed=11, length=SEQ_LEN):
52
+ """Random tokens with no adjacent repeats — makes slot j and slot j+1
53
+ genuinely different predictions."""
54
+ g = torch.Generator().manual_seed(seed)
55
+ seq = []
56
+ while len(seq) < length:
57
+ t = torch.randint(0, 512, (1,), generator=g).item()
58
+ if not seq or t != seq[-1]:
59
+ seq.append(t)
60
+ return torch.tensor(seq)
61
+
62
+
63
+ def _memorize_trunk(model, seq, steps=TRUNK_STEPS):
64
+ opt = torch.optim.Adam(model.parameters(), lr=LR)
65
+ for _ in range(steps):
66
+ out = model(input_ids=seq.unsqueeze(0))
67
+ loss = F.cross_entropy(out.logits[0, :-1], seq[1:])
68
+ opt.zero_grad()
69
+ loss.backward()
70
+ opt.step()
71
+
72
+
73
+ def _train_chain_on_trajectory(model, seq, steps=CHAIN_STEPS):
74
+ mods, _norm = resolve_mtp(model)
75
+ opt = torch.optim.Adam([p for m in mods for p in m.parameters()], lr=LR)
76
+ embed, lm_head = model.transformer.wte, model.lm_head
77
+ for _ in range(steps):
78
+ with torch.no_grad():
79
+ h = model(input_ids=seq.unsqueeze(0), output_hidden_states=True,
80
+ return_dict=True).hidden_states[-1]
81
+ emb = embed(seq.unsqueeze(0))
82
+ loss, depth_h = 0.0, h
83
+ for j, mod in enumerate(mods):
84
+ depth_h, _kv = mod(depth_h, emb)
85
+ logits_j = lm_head(depth_h)[0]
86
+ shift = j + 1
87
+ if len(seq) - shift >= 2:
88
+ loss = loss + F.cross_entropy(logits_j[: len(seq) - shift],
89
+ seq[shift:])
90
+ opt.zero_grad()
91
+ loss.backward()
92
+ opt.step()
93
+ return loss.item()
94
+
95
+
96
+ @pytest.mark.slow
97
+ def test_trained_drafter_accepts_and_misalignment_would_not():
98
+ torch.manual_seed(3)
99
+ model = build_tiny_model_with_mtp(depths=3, seed=3)
100
+ seq = _diverse_sequence()
101
+
102
+ _memorize_trunk(model, seq)
103
+ # the greedy replay must regenerate the diverse sequence: this is what
104
+ # makes one-slot-early predictions actually wrong
105
+ with torch.no_grad():
106
+ gen = model.generate(input_ids=seq[:PROMPT_LEN].unsqueeze(0),
107
+ max_new_tokens=SEQ_LEN - PROMPT_LEN,
108
+ do_sample=False, num_beams=1)[0]
109
+ assert (gen[PROMPT_LEN:] == seq[PROMPT_LEN:]).all(), \
110
+ "trunk did not memorize the trajectory; test setup is broken"
111
+
112
+ chain_loss = _train_chain_on_trajectory(model, seq)
113
+ assert chain_loss < 1.0, f"chain training did not converge ({chain_loss})"
114
+
115
+ prompt = seq[:PROMPT_LEN].unsqueeze(0)
116
+ _ids, stats = spec_generate(model, prompt, 60, k=2)
117
+ rate = stats["accepted"] / max(stats["drafted"], 1)
118
+ chance = 1.0 / 512
119
+ # aligned + cached-chain drafting accepts at the rate an in-distribution
120
+ # drafter should (measured 0.95 on this memorized-trajectory setup;
121
+ # stateless drafting measured 0.16; the historical one-slot-early bug
122
+ # scored 0.00)
123
+ assert rate > 0.5, f"accept rate {rate:.3f} — cached chain not engaged?"
@@ -0,0 +1,63 @@
1
+ """Greedy-exactness: spec output must equal plain model.generate, always.
2
+
3
+ These run on CPU with tiny models. They prove the verify gate, not speed:
4
+ a random head (accepts nothing) and a degenerate head (eh_proj zeroed so
5
+ every depth sees the same input) must both still produce greedy-exact
6
+ output — the strongest form of the "the head can only change SPEED" claim.
7
+ """
8
+
9
+ import pytest
10
+ import torch
11
+
12
+ from mtpspec import has_mtp, spec_generate
13
+
14
+
15
+ def _greedy_reference(model, input_ids, max_new_tokens):
16
+ return model.generate(
17
+ input_ids=input_ids,
18
+ max_new_tokens=max_new_tokens,
19
+ do_sample=False,
20
+ num_beams=1,
21
+ )[0, input_ids.shape[1]:]
22
+
23
+
24
+ @pytest.mark.parametrize("k", [1, 2, 3])
25
+ def test_random_head_is_greedy_exact(tiny_model, k):
26
+ model = tiny_model
27
+ assert has_mtp(model)
28
+ prompt = torch.randint(0, 512, (1, 10))
29
+ spec_ids, stats = spec_generate(model, prompt, 40, k=k)
30
+ ref = _greedy_reference(model, prompt, 40)
31
+ assert spec_ids.tolist() == ref.tolist()
32
+ # stats sanity: every cycle drafts the effective k (module 0 re-proposes
33
+ # the pending, so a 3-depth chain drafts at most 2 usable tokens)
34
+ eff_k = min(k, 3 - 1)
35
+ assert stats["k"] == eff_k
36
+ assert stats["emitted"] == 40
37
+ assert stats["drafted"] == stats["cycles"] * eff_k
38
+ assert stats["accepted"] <= stats["drafted"]
39
+
40
+
41
+ @pytest.mark.parametrize("k", [1, 3])
42
+ def test_degenerate_head_is_greedy_exact(zeroed_model, k):
43
+ model = zeroed_model
44
+ prompt = torch.randint(0, 512, (1, 12))
45
+ spec_ids, stats = spec_generate(model, prompt, 30, k=k)
46
+ ref = _greedy_reference(model, prompt, 30)
47
+ assert spec_ids.tolist() == ref.tolist()
48
+
49
+
50
+ def test_max_new_tokens_is_respected(tiny_model):
51
+ prompt = torch.randint(0, 512, (1, 8))
52
+ spec_ids, stats = spec_generate(tiny_model, prompt, 17, k=3)
53
+ assert len(spec_ids) == 17
54
+ assert stats["emitted"] == 17
55
+
56
+
57
+ def test_no_mtp_head_raises_cleanly():
58
+ from transformers import GPT2Config, GPT2LMHeadModel
59
+ cfg = GPT2Config(vocab_size=128, n_positions=64, n_embd=16, n_layer=1, n_head=2)
60
+ plain = GPT2LMHeadModel(cfg)
61
+ assert not has_mtp(plain)
62
+ with pytest.raises(ValueError, match="no MTP head"):
63
+ spec_generate(plain, torch.zeros(1, 4, dtype=torch.long), 5)
@@ -0,0 +1,73 @@
1
+ """Sampled mode: distribution match against plain trunk sampling.
2
+
3
+ Both samplers run with fixed seeds, so the comparison is deterministic —
4
+ no flakes, just bounds tuned with headroom around the measured distance
5
+ of a correct implementation.
6
+ """
7
+
8
+ import torch
9
+
10
+ from mtpspec import spec_generate_sampled
11
+
12
+ from conftest import build_tiny_model_with_mtp
13
+
14
+ N_SAMPLES = 400
15
+
16
+
17
+ def _frequencies(model, prompt, sampler, n=N_SAMPLES):
18
+ counts = {}
19
+ for s in range(n):
20
+ g = torch.Generator().manual_seed(5000 + s)
21
+ ids, _ = sampler(model, prompt, 1, k=1, generator=g)
22
+ t = ids[0].item()
23
+ counts[t] = counts.get(t, 0) + 1
24
+ return counts
25
+
26
+
27
+ def _plain_sample(model, prompt, max_new, k, generator):
28
+ torch.manual_seed(generator.initial_seed())
29
+ # top_k=0 / top_p=1.0: sample the FULL softmax, matching the spec
30
+ # sampler — HF's default top_k=50 would truncate the distribution and
31
+ # the comparison would measure truncation, not correctness
32
+ out = model.generate(input_ids=prompt, max_new_tokens=max_new,
33
+ do_sample=True, temperature=1.0, top_k=0, top_p=1.0,
34
+ num_beams=1)
35
+ return out[0][prompt.shape[1]:], None
36
+
37
+
38
+ def test_sampled_distribution_matches_trunk_sampling():
39
+ model = build_tiny_model_with_mtp(depths=3, seed=0)
40
+ prompt = torch.randint(0, 512, (1, 16))
41
+
42
+ spec_counts = _frequencies(
43
+ model, prompt,
44
+ lambda m, p, n, k, generator: spec_generate_sampled(
45
+ m, p, n, k=k, temperature=1.0, generator=generator))
46
+ ref_counts = _frequencies(model, prompt, _plain_sample)
47
+
48
+ tokens = sorted(set(spec_counts) | set(ref_counts))
49
+ tv = 0.5 * sum(abs(spec_counts.get(t, 0) - ref_counts.get(t, 0))
50
+ for t in tokens) / N_SAMPLES
51
+ # a correct rejection sampler draws from the same distribution; two
52
+ # 400-sample empiricals of the same distribution sit well under this
53
+ assert tv < 0.25, f"total variation {tv:.3f} too large"
54
+
55
+
56
+ def test_sampled_is_reproducible_with_seed():
57
+ model = build_tiny_model_with_mtp(depths=3, seed=0)
58
+ prompt = torch.randint(0, 512, (1, 12))
59
+ g1 = torch.Generator().manual_seed(42)
60
+ g2 = torch.Generator().manual_seed(42)
61
+ a, _ = spec_generate_sampled(model, prompt, 30, k=2, generator=g1)
62
+ b, _ = spec_generate_sampled(model, prompt, 30, k=2, generator=g2)
63
+ assert a.tolist() == b.tolist()
64
+
65
+
66
+ def test_sampled_accepts_and_emits():
67
+ model = build_tiny_model_with_mtp(depths=3, seed=0)
68
+ prompt = torch.randint(0, 512, (1, 12))
69
+ g = torch.Generator().manual_seed(9)
70
+ ids, stats = spec_generate_sampled(model, prompt, 40, k=2, generator=g)
71
+ assert len(ids) == 40
72
+ assert stats["emitted"] == 40
73
+ assert stats["accepted"] + stats["resampled"] >= stats["cycles"]
@@ -0,0 +1,32 @@
1
+ """Stream + cycles consumers: the pieces must reassemble to the whole.
2
+ """
3
+
4
+ import torch
5
+
6
+ from mtpspec import spec_generate, spec_generate_cycles, spec_generate_stream
7
+
8
+
9
+ class _StubTok:
10
+ """decode() maps ids to distinct single characters — good enough to
11
+ prove reassembly without a real tokenizer's vocab."""
12
+
13
+ def decode(self, ids, skip_special_tokens=True):
14
+ return "".join(chr(97 + (i % 26)) for i in ids)
15
+
16
+
17
+ def test_stream_pieces_concatenate_to_full_decode(tiny_model):
18
+ prompt = torch.randint(0, 512, (1, 10))
19
+ ids, _ = spec_generate(tiny_model, prompt, 20, k=2)
20
+ tok = _StubTok()
21
+ pieces = list(spec_generate_stream(tiny_model, tok, prompt, 20, k=2))
22
+ assert "".join(pieces) == tok.decode(ids.tolist())
23
+
24
+
25
+ def test_cycles_sum_equals_spec_generate(tiny_model):
26
+ prompt = torch.randint(0, 512, (1, 12))
27
+ ids, _ = spec_generate(tiny_model, prompt, 25, k=3)
28
+ collected, stats = [], None
29
+ for emitted, stats in spec_generate_cycles(tiny_model, prompt, 25, k=3):
30
+ collected.extend(emitted)
31
+ assert collected[:25] == ids.tolist()
32
+ assert stats["emitted"] >= 25