Skip to main content

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

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

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 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.

Metadata

Release files for mtpspec 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mtpspec 0.1.0
File Size Uploaded Provenance Actions
mtpspec-0.1.0.tar.gz 15.7 kB Without provenance Details for mtpspec-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mtpspec 0.1.0
File Interpreter ABI Platform Actions
mtpspec-0.1.0-py3-none-any.whl Python 3 none any Details for mtpspec-0.1.0-py3-none-any.whl

Total release size: 28.6 kB

Release files / mtpspec-0.1.0.tar.gz

Download URL mtpspec-0.1.0.tar.gz
Size 15.7 kB
Tags Source
SHA-256 checksum
How to use checksums
3afc7e33ede9ebe51d9c2171bfd52a2cdba388521f45931f9021287fe080ea6b
BLAKE2b-256 checksum
How to use checksums
880c5032c5c2c52ba734525da3917b2cb45d37b6bda144776e4aba1c86aef5d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / mtpspec-0.1.0-py3-none-any.whl

Download URL mtpspec-0.1.0-py3-none-any.whl
Size 12.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e9295b8eb9efa694425e64fd21b0a23bc215d240e502efcb14db7f0a07f6723
BLAKE2b-256 checksum
How to use checksums
7c50eeec53db2ec07f0af4c53e799552fbec592f1e94ad191bdfed1071312cb1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Security for mtpspec 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page