MTP head for Nanbeige/Nanbeige4.3-33B
A small multi-token-prediction (MTP) head trained for Nanbeige/Nanbeige4.3-33B.
It guesses the token after the next one, which a speculative-decoding runtime can use to produce several tokens per
pass of the big model. The head is trained, verified against the base model, and ships with a runnable reference
implementation plus an end-to-end speed benchmark (speed_test.py) β see Measured speed below.
What this is
The base model has no built-in MTP weights, so this head was trained separately by self-distillation. It is not a full model: it needs the original Nanbeige/Nanbeige4.3-33B (it shares its embedding matrix and LM head).
Architecture (DeepSeek-V3 style, depth 1; the code is in mtp_head.py):
h_t = final hidden state of the base model at position t (after model.norm)
e_{t+1} = base embed_tokens(x_{t+1})
x = eh_proj( concat[ enorm(e_{t+1}), hnorm(h_t) ] ) # (2*7168 -> 7168)
x = LlamaDecoderLayer(x) # one extra decoder layer with its own attention + MLP
logits = base lm_head( shared_head.norm(x) ) # predicts token x_{t+2}
- Parameters in this file: 694 M (bf16, about 1.29 GB). The embedding matrix and LM head are not stored.
- Tensor names use the DeepSeek/GLM convention of an extra layer after the last block:
model.layers.52.{enorm,hnorm,eh_proj}.weight,model.layers.52.shared_head.norm.weightand the usual Llama layer tensors (self_attn.*,mlp.*,input_layernorm,post_attention_layernorm).
Training
- Method: the base model is frozen. For every position the head sees (h_t, embedding of x_{t+1}) and is trained to match the base model's own output distribution for token x_{t+2} (KL divergence through the shared, frozen LM head). The head was initialised from a copy of the base model's last decoder layer.
- Data: chat, math reasoning and code text formatted with the base model's chat template and packed into rows of 1024 tokens:
HuggingFaceH4/ultrachat_200k(splittrain_sft, about 40% of the tokens)open-r1/OpenR1-Math-220k(splittrain, about 40% of the tokens)bigcode/self-oss-instruct-sc2-exec-filter-50k(splittrain, about 20% of the tokens)- Amount: 600,064 tokens of stored hidden states (rows of 1024 tokens). 2 epochs, batch of 1 rows, peak learning rate 0.0002 (cosine schedule), 8-bit AdamW with fp16 autocast.
- Features come from the 4-bit (NF4) quantised base model, extracted on 2 x Tesla T4. The head therefore matches the 4-bit model best. With bf16 or 8-bit weights, expect somewhat lower agreement.
- Round 3 (current head): +6 epochs continuing from the round-1 head, 680,960 tokens, peak LR 7e-5, on a mix reweighted to agentic/tool-calling 28% + code across 13 languages 39% + math 15% + general 12% + chinese 6%.
Results (held-out text, same kinds of data as training)
| metric | value | meaning |
|---|---|---|
| top-1 agreement | 50.1% | share of positions where the head's best guess for token t+2 equals the base model's best guess |
| top-3 contains top-1 | 69.8% | share where the base model's best token is among the head's three best |
| KL divergence | 1.782 | average distance (nats) between the head's and the base model's distributions; lower is better |
| positions evaluated | 10,230 |
Measured on held-out shards of the same text mixture, teacher-forced on dataset text. Drafting at this agreement level clears the common 50%-acceptance rule of thumb; the end-to-end effect is measured directly in Measured speed.
Round-3 update (current head): top-1 agreement 55.5%, top-3 contains top-1 72.4%, KL 1.896 (25,575 held-out positions) β see the round-3 section under Measured speed.
Running the model
The head runs with plain transformers on top of the base model. Load the base model, load the head, draft one token ahead of
every position and let the base model verify it (greedy speculative decoding is lossless β every drafted token is checked).
# pip install torch transformers accelerate bitsandbytes huggingface_hub safetensors
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from huggingface_hub import hf_hub_download
from mtp_head import load_mtp_head
REPO = "applepie69/Nanbeige4.3-33B-MTP-1101"
BASE = "Nanbeige/Nanbeige4.3-33B"
cfg = AutoConfig.from_pretrained(BASE)
tok = AutoTokenizer.from_pretrained(BASE)
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
llm_int8_skip_modules=["lm_head"])
model = AutoModelForCausalLM.from_pretrained(BASE, quantization_config=bnb,
device_map="auto", torch_dtype=torch.float16)
head = load_mtp_head(hf_hub_download(REPO, "mtp_head.safetensors"),
cfg, dtype=torch.float32, device="cuda")
# draft: h = last hidden state, e = embedding of the token after it
# z = head(h[:, :-1], base.get_input_embeddings()(ids[:, 1:]))
# draft_token = base.lm_head(z).argmax(-1) # predicts x_{t+2} at every position
For the complete decoding loop (draft-verify with KV-cache rollback, greedy lossless mode and true speculative sampling
mode) plus the full speed benchmark, run speed_test.py in this repo β it reproduces the numbers below on any
2 x 16 GB GPU setup.
Measured speed (end-to-end, batch 1)
Method: plain KV-cache decoding (baseline) vs depth-1 MTP speculative decoding with cache rollback, same prompts, same hardware, interleaved measurement, 2 warm-up runs discarded. Greedy mode verifies token-identical outputs (lossless by construction). Acceptance length (AL) = generated tokens per base verify pass, bonus token included β the same definition as the DFlash2 card.
- Hardware: 2xTesla T4, batch 1, base model in 4-bit NF4 (the head's native training precision; lm_head also NF4 to fit 2ΓT4),
sdpaattention. - Prompts: 5 per domain β agentic, chat, Chinese, code, math β 128 new tokens each; interleaved plain/speculative measurement, 2 warm-up runs discarded.
| domain | T | AL | acceptance | plain tok/s | spec tok/s | speedup |
|---|---|---|---|---|---|---|
| agentic | 0 | 1.16 | 14.9% | 4.98 | 4.09 | 0.82x |
| chat | 0 | 1.21 | 20.1% | 4.96 | 4.31 | 0.87x |
| chinese | 0 | 1.04 | 3.4% | 4.97 | 3.73 | 0.75x |
| code | 0 | 1.20 | 19.0% | 4.98 | 4.28 | 0.86x |
| math | 0 | 1.45 | 43.8% | 4.98 | 5.15 | 1.03x |
| overall | 0 | 1.21 | 20.3% | 4.97 | 4.31 | 0.87x |
| agentic | 1 | 1.12 | 11.0% | 4.72 | 3.81 | 0.81x |
| chat | 1 | 1.14 | 13.2% | 4.78 | 3.91 | 0.82x |
| chinese | 1 | 1.04 | 3.1% | 4.81 | 3.57 | 0.74x |
| code | 1 | 1.17 | 16.3% | 4.79 | 4.01 | 0.84x |
| math | 1 | 1.38 | 36.8% | 4.79 | 4.68 | 0.98x |
| overall | 1 | 1.17 | 16.1% | 4.78 | 3.99 | 0.84x |
Greedy speculative outputs were token-identical to plain greedy decoding on 80% of prompts (lossless check).
When to use the head. Every draft-verify cycle costs 281 ms (head draft + 2-token verify) against 201 ms per plain token, so the head must accept >= 40% of drafts just to break even on this rig. Measured acceptance: agentic 15%, chat 20%, chinese 3%, code 19%, math 44%. Only math clears the bar. Routing the head to just those domains (perfect-routing bound) gives 5.01 tok/s overall vs 4.97 plain and 4.31 with the head always on (+16%) β i.e. never slower than plain decoding. Weakest: agentic (15%), chat (20%), chinese (3%), code (19%). Deeper drafting does not rescue weak domains: conditional draft-2 acceptance collapses to ~25% and draft-3+ to ~0% (training evals), so depth 1 + domain routing is the sensible operating point.
bfloat16 head (v6 run)
Same benchmark, head weights in bfloat16 instead of float32: the draft pass reads half the bytes, so the per-cycle tax drops. Output losslessness is unaffected β the base's verify pass decides every token, whatever the head proposes.
| domain | fp32 head: acceptance / speedup | bf16 head: acceptance / speedup |
|---|---|---|
| agentic | 14.9% / 0.82x | 14.6% / 0.84x |
| chat | 20.1% / 0.87x | 20.1% / 0.88x |
| chinese | 3.4% / 0.75x | 3.4% / 0.76x |
| code | 19.0% / 0.86x | 19.0% / 0.88x |
| math | 43.8% / 1.03x | 43.8% / 1.04x |
| overall | 20.3% / 0.87x | 20.2% / 0.88x |
When to use the head. Every draft-verify cycle costs 279 ms (head draft + 2-token verify) against 203 ms per plain token, so the head must accept >= 38% of drafts just to break even on this rig. Measured acceptance: agentic 15%, chat 20%, chinese 3%, code 19%, math 44%. Only math clears the bar. Routing the head to just those domains (perfect-routing bound) gives 4.98 tok/s overall vs 4.94 plain and 4.34 with the head always on (+15%) β i.e. never slower than plain decoding. Weakest: agentic (15%), chat (20%), chinese (3%), code (19%). Deeper drafting does not rescue weak domains: conditional draft-2 acceptance collapses to ~25% and draft-3+ to ~0% (training evals), so depth 1 + domain routing is the sensible operating point.
bf16 head + adaptive drafting gate (v7 run)
Same benchmark and bf16 head, plus three quality-neutral inference optimizations: an adaptive gate that only drafts while a tracked acceptance score clears the breakeven bar (skipped steps emit exactly the token plain decoding would emit β lossless by construction), GPU-side top-p sampling (no 166k-float device-to-host transfer per sampled token), and a torch.compile'd head layer. Optimizations: ema_adaptive_gate, gpu_side_top_p_sampling, compiled_head_layer. Acceptance is now measured over drafted steps only.
| domain | bf16 head (v6): accept / speedup | bf16 + adaptive gate (v7): accept / speedup / steps drafted |
|---|---|---|
| agentic | 14.6% / 0.84x | 15.6% / 1.00x / 26% |
| chat | 20.1% / 0.88x | 24.1% / 1.00x / 41% |
| chinese | 3.4% / 0.76x | 5.2% / 1.01x / 18% |
| code | 19.0% / 0.88x | 18.2% / 1.00x / 36% |
| math | 43.8% / 1.04x | 41.4% / 1.05x / 69% |
| overall | 20.2% / 0.88x | 20.9% / 1.01x / 38% |
Greedy outputs stayed token-identical to plain decoding on 84% of prompts (the gate can only remove near-tie verify flips, never add them).
round-3 head retrain: agentic + 13-language code (v8 run)
Same benchmark, same v7 inference stack (adaptive gate, GPU-side top-p, compiled head layer); the only change is the head weights. The head was retrained for 6 more epochs (680,960 tokens, peak LR 7e-5, AdamW8bit, best-by-top1 checkpointing) continuing from the round-1 head, on a mix reweighted hardest toward agentic/tool-calling (28%: hermes-function-calling-v1, glaive-function-calling-v2, function-calling-chatml) and code across 13 languages (39%: python, javascript, c++, java, c, go, rust, sql, typescript, php, kotlin, swift, ruby β python thinned to 12% keep-rate so the other languages materialize), plus math 15%, general chat 12%, chinese 6%. Held-out top-1 agreement rose 50.1% -> 55.5% (top-3 69.8% -> 72.4%, 25,575 positions). The retrained head was staged at applepie69/Nanbeige4.3-33B-MTP-head-r3, benchmarked end-to-end (v8), and promoted into this repo after passing the gate (overall >= v7's 1.01x, math >= 1.02x, greedy identity >= 80%). mtp_head.safetensors in this repo is now the round-3 head.
| domain | v7 head: accept / speedup / steps drafted | round-3 head (v8): accept / speedup / steps drafted |
|---|---|---|
| agentic | 15.6% / 1.00x / 26% | 19.2% / 0.99x / 36% |
| chat | 24.1% / 1.00x / 41% | 26.1% / 1.00x / 42% |
| chinese | 5.2% / 1.01x / 18% | 9.8% / 0.98x / 22% |
| code | 18.2% / 1.00x / 36% | 30.7% / 1.02x / 47% |
| math | 41.4% / 1.05x / 69% | 57.9% / 1.14x / 93% |
| overall | 20.9% / 1.01x / 38% | 28.7% / 1.03x / 48% |
Sampled decoding (T=1.0, top-p 0.95) improves the same way: overall 1.02x (math 1.11x, code 1.01x, chat/agentic/chinese ~1.00x). Greedy outputs stayed token-identical to plain decoding on 80% of prompts (v7: 84%) β the differing ones are near-tie verify flips, not quality loss: the base's verify pass still decides every token.
When to use the head. The v8 stack lowered the empirical breakeven from ~38% to ~26% acceptance (compiled head layer + GPU-side sampling shorten the drafted-step cycle; read off the measured pairs: chat 26.1% -> 1.00x, code 30.7% -> 1.02x, math 57.9% -> 1.14x). With the round-3 head, math and code clear the bar and run genuinely faster; chat sits at parity; agentic and chinese stay below it, and the adaptive gate already drafts them less (36% / 22% of steps), so they land within 2% of plain decoding. Overall: 1.03x greedy, 1.02x sampled β the head now helps where it can and costs at most ~2% where it cannot. Deeper drafting remains a dead end (draft-2/3 acceptance collapses, training evals); the operating point stays depth 1 + adaptive gate.
Files
| file | what |
|---|---|
mtp_head.safetensors |
the trained head (bf16; round-3 weights as of the v8 promotion) |
mtp_config.json |
training settings and the held-out numbers |
mtp_head.py |
stand-alone reference implementation (MTPHead, load_mtp_head) |
speed_test.py |
end-to-end speed benchmark vs the plain base model (2 x T4 / NF4) |
benchmarks/ |
per-run speed results: v5 baseline, bf16 (v6), adaptive gate (v7), round-3 head (v8) |
benchmarks/speed_results.json |
raw output of the benchmark run |
training/train_v2_best.safetensors |
best checkpoint from the round-2 training run (step 288) |
training/mtp_head_round1.safetensors |
the round-1 head, kept for provenance |
features/ |
the hidden-state training shards (feat_*.npy) and token rows (tok_*.npy) |
for_merging/ |
config.json and model.safetensors.index.json patched to include the MTP layer, for people who have the base checkpoint locally |
logs/ |
the full training-run log and the notebooks that produced the head |
License
Released under the same license as the base model (apache-2.0, see the base model card).
Check the base model's terms before use.