Metadata-Version: 2.4
Name: mtpspec
Version: 0.1.1
Summary: greedy-exact speculative decoding off a model's own MTP head
Author: mycomputercrashsalot
License: MIT
Project-URL: Homepage, https://github.com/mycomputercrashsalot/mtpspec
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: transformers; extra == "test"
Dynamic: license-file

# mtpspec

greedy-exact speculative decoding off a model's own MTP head.

an MTP (multi-token prediction) head — the deepseek-v3-style chain that
some checkpoints and trainers attach as `model.mtp_layers` — predicts
several tokens ahead from the trunk's hidden state at one position. that
is exactly a drafter for speculative decoding: no separate draft model,
no extra weights to serve, nothing new at inference time.

## the guarantee

the loop drafts k proposals from the chain, runs ONE trunk forward over
[pending, drafts], and accepts the longest prefix that matches the trunk's
greedy argmax. every emitted token is the trunk's argmax or a draft that
equaled it, so output is token-for-token identical to plain greedy
decoding. the head can only change SPEED, never the result. the test
suite proves this with random heads (accept nothing) and degenerate
heads — if the verify gate survives those, it survives anything.

acceptance stats come back with every call so the speed/tradeoff is
visible, not vibes.

## install

```
pip install mtpspec
```

core dependency is torch alone. transformers is only needed to load
models with it (and for the test suite).

## use

```python
from mtpspec import has_mtp, spec_generate, spec_generate_stream

model = load_your_model_somehow()   # any HF-style causal LM
if has_mtp(model):                  # finds model.mtp_layers
    ids, stats = spec_generate(model, input_ids, max_new_tokens=200, k=4)
    print(stats["accepted"], "/", stats["drafted"], "drafts accepted")

    for piece in spec_generate_stream(model, tokenizer, input_ids, 200, k=4):
        print(piece, end="", flush=True)
```

`spec_generate_cycles` is the underlying generator if you want tokens per
cycle instead of the whole tensor.

## sampled mode too

```python
from mtpspec import spec_generate_sampled

ids, stats = spec_generate_sampled(model, input_ids, 200, k=4,
                                   temperature=1.0, generator=torch.Generator().manual_seed(0))
```

rejection sampling off the same chain: per slot the depth's proposal
distribution q is tested against the trunk's conditional p, accept with
probability min(1, p/q), resample from the residual on rejection.
completion distribution matches sampling from the trunk directly at the
same temperature.

## what heads work

any chain attached as `mtp_layers` (on the causal-lm wrapper, the bare
family model, or the top object) where depth module j is callable as
`m(h, token_emb) -> (h', kv)`:

- `h` — trunk final hidden state at one position, `[1, 1, hidden]`
- `token_emb` — embedding of the token at that position, `[1, 1, hidden]`
- output predicts the token `j+1` positions ahead of the anchor

that's the deepseek-v3 layout, and it's what
[single-gpu-llm-toolkit](https://github.com/mycomputercrashsalot/single-gpu-llm-toolkit)
builds (mtp_head.py builds the weights, modeling_custom trains them,
this package serves them). a shared final norm setattr'd on the
modulelist (`mtp_layers.norm`) is tolerated and not counted as a depth.

the decode loop itself needs no attention-mask plumbing and no family
knowledge — resolvers find the embed/lm_head/mtp chain, the loop only
needs `output_hidden_states`, `use_cache`, and a croppable kv cache
(`DynamicCache.crop`, present in recent transformers).

## the cached chain

each MTP depth carries its own KV cache across cycles. every cycle, the
newly accepted-and-fed positions are pushed through the chain (the
trunk hiddens come out of the verify forward for free) and each depth's
output at the new anchor is the next draft base — the ingest IS the
draft computation. only accepted positions are ingested, so the chain
stays aligned with the trunk's accepted prefix; rejected drafts never
touch it. drafting happens in the same full-context regime the chain is
trained in. on a memorized-trajectory test setup this took the accept
rate from 0.16 (stateless drafting) to 0.95.

## honest limits

- speedup numbers need real hardware and a trained head. correctness is
  what the test suite proves; `bench/mtp_bench.py` turns the accept rate
  into tok/s and tok/cycle (measured against the geometric acceptance
  model) on whatever box you run it. note the loader gotcha: plain
  `AutoModelForCausalLM.from_pretrained` drops `mtp_layers` weights as
  unexpected keys — load with code that knows the chain (the toolkit's
  loader, or trust_remote_code with its modeling file).
- within a cycle, the k proposals come from the chain's depth outputs at
  one anchor: depth j's distribution does not condition on the tokens
  sampled at depths < j. the rejection-sampling math handles
  history-independent proposals fine (each slot's test uses the
  distribution the token was actually drawn from), but drafts would be
  stronger still with a fully autoregressive drafter.
- the draft loop uses modules 1..k of the chain: module 0 anchored at
  the last fed position re-proposes the pending token, so it is skipped.
  a chain of D depths drafts at most D-1 tokens per cycle. this was once
  a silent off-by-one (modules 0..k-1, every draft one slot early —
  exact output, chance accept rate, no speedup); the trained-drafter
  test exists so it cannot come back.

## develop

```
pip install -e '.[test]'
pytest
```

mit license.
