mtpspec 0.1.0__py3-none-any.whl
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/__init__.py +34 -0
- mtpspec/core.py +179 -0
- mtpspec/resolve.py +63 -0
- mtpspec/sampled.py +155 -0
- mtpspec/stream.py +31 -0
- mtpspec-0.1.0.dist-info/METADATA +143 -0
- mtpspec-0.1.0.dist-info/RECORD +10 -0
- mtpspec-0.1.0.dist-info/WHEEL +5 -0
- mtpspec-0.1.0.dist-info/licenses/LICENSE +21 -0
- mtpspec-0.1.0.dist-info/top_level.txt +1 -0
mtpspec/__init__.py
ADDED
|
@@ -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
|
+
]
|
mtpspec/core.py
ADDED
|
@@ -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
|
mtpspec/resolve.py
ADDED
|
@@ -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
|
mtpspec/sampled.py
ADDED
|
@@ -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
|
mtpspec/stream.py
ADDED
|
@@ -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,10 @@
|
|
|
1
|
+
mtpspec/__init__.py,sha256=BCtjg02UV01CtyFQNfC4gSwUAKkFPzQG-mb9e87CIZY,1222
|
|
2
|
+
mtpspec/core.py,sha256=CZT4rgkQsPADr3mSbbHxEpY93S8NTjcEAdefl3OB-r8,8671
|
|
3
|
+
mtpspec/resolve.py,sha256=ywgM5aapx9INfvJqB39uhgADUD1AKE9QycWvHFaY0M0,2531
|
|
4
|
+
mtpspec/sampled.py,sha256=VX-ACVcyB7Egv1e0ElBoYghYb9QlbLrlQom6A37xO0I,6367
|
|
5
|
+
mtpspec/stream.py,sha256=KAGfioZ_s3eDrZ5AdvhHc2_C68A3q3WuglfIqaxwB_o,1234
|
|
6
|
+
mtpspec-0.1.0.dist-info/licenses/LICENSE,sha256=VvhwUFrHyB5H1pXA5CeMHkEfjduTM1X5JQtUSfxUOnE,1077
|
|
7
|
+
mtpspec-0.1.0.dist-info/METADATA,sha256=6ypgC5uDwlJB7nL1ZO1b1fYA2LGEOHBRSms7C39avJM,5761
|
|
8
|
+
mtpspec-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
mtpspec-0.1.0.dist-info/top_level.txt,sha256=By0bn8a-RA1cGwqdN1NprAn3hO6cSdOYhdWS1KOTKbM,8
|
|
10
|
+
mtpspec-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mtpspec
|