The previous lessons were about the middle of the network — attention, MoE, recurrent state, the residual stream. This one is about its two ends. At the output end: what the model is trained to predict, and how a second prediction head turns into a free draft model at inference. At the input end: how big the vocabulary should be, whether input and output embeddings should share weights, and a newer idea — hashed n-gram tables that add tens of billions of parameters at almost no FLOPs.
Next-token prediction leaves signal on the table
The standard objective gives each position one target, . A forward pass over tokens produces training signals, each about the immediate next token. Multi-token prediction (MTP) asks each position to also predict further ahead.
Parallel heads (Gloeckle et al. 2024). A shared trunk produces ; independent output heads predict from it:
With their 13B code models solved 12% more HumanEval and 17% more MBPP problems than next-token baselines, and 4-token models were up to 3× faster at inference when the extra heads drafted for themselves. The catch: head predicts the marginal — it cannot condition on what actually turned out to be.
Sequential modules (DeepSeek-V3). Depth takes the previous depth’s representation and the embedding of the true token , runs one Transformer block, and predicts with the shared output head:
Each depth keeps a complete causal chain — it predicts the token after the one it was shown — so at inference it is a proper conditional drafter: fed the token just sampled, it proposes the next one. V3 uses , for the first 10T tokens and for the last 4.8T; the released checkpoint is 685B = 671B main model + 14B MTP module. The V3 lesson has the figure; the motivations the report gives are a denser training signal and representations that “pre-plan” for future tokens. The cost is one extra block per depth, about of the forward pass.
How the labs use it:
| Model | MTP design | Training | Inference use |
|---|---|---|---|
| DeepSeek-V3 | 1 sequential module (14B) | λ 0.3 → 0.1 | 2nd-token acceptance 85–90%, 1.8× TPS |
| MiMo-V2-Flash | light blocks (dense FFN + SWA, 0.33B each) | 1 block in pre-training (λ 0.3 → 0.1), 3 in post-training | mean accept length fits in next-token CE |
| MiniMax-M2 | DeepSeek-style | 1 module, expanded to 3 by copying weights; main model frozen until MTP loss settles, then joint | Forge co-trains MTP with the RL policy (top-K KL) |
| Nemotron 3 Ultra | 2 blocks (attention + MoE) with shared weights, applied recursively | loss 0.1 (0.05 per block) | RL rollouts 1.46× at k = 5; deployment drafting |
| Qwen3-Next / 3.5 / 3.8 | MTP with multi-step training (3.8: 4B params) | — | Qwen3.8: 4-step mean accepted length 4.06 |
| DeepSeek-V4.1-Flash | no MTP | a separate drafter (DSpark) trained after pre-training | — |
MTP as a drafter: the acceptance math
Speculative decoding drafts tokens cheaply and verifies them with one main-model forward pass (inference lesson, speculative decoding). The rule that keeps sampling exact: draft , accept with probability , otherwise sample from normalised. The probability of acceptance is
and the output is distributed exactly as . With drafts whose acceptance probabilities (given all earlier ones were accepted) are , verification stops at the first rejection, so one step yields
the leading 1 being the corrected (or bonus) token the main model always contributes. With constant this is . Two things make the per-depth fall: drafts at depth condition on earlier drafts, not the truth, while training used teacher forcing; and deeper predictions are simply harder. Multi-step training (Qwen) and one recursively applied head (Nemotron) attack the first. If a draft step costs of a main decode step and verifying tokens costs about one step (true in the memory-bound decode regime), the speedup is about .
앞의 레슨들은 네트워크의 가운데 — attention, MoE, 순환 상태, residual stream — 를 다뤘다. 이 레슨은 양 끝을 본다. 출력 쪽에서는 모델이 무엇을 예측하도록 학습되는지, 그리고 두 번째 예측 head가 추론 때 어떻게 공짜 draft 모델이 되는지. 입력 쪽에서는 어휘가 얼마나 커야 하는지, 입력과 출력 임베딩이 가중치를 공유해야 하는지, 그리고 더 새로운 생각인 해시 n-gram 테이블, 즉 FLOPs를 거의 쓰지 않고 수백억 파라미터를 더하는 방법이다.
next-token prediction은 신호를 남긴다
표준 목적함수는 위치마다 목표를 하나 준다. . 토큰의 forward 한 번이 바로 다음 토큰에 대한 학습 신호 개를 만든다. multi-token prediction(MTP)은 각 위치에 더 먼 토큰도 예측하게 한다.
병렬 head (Gloeckle et al. 2024). 공유 trunk가 를 만들고, 독립적인 출력 head 개가 그것으로 을 예측한다.
에서 그들의 13B 코드 모델은 next-token baseline보다 HumanEval 문제를 12%, MBPP를 17% 더 풀었고, 추가 head가 스스로 draft를 만들면 4-token 모델이 추론에서 최대 3배 빨랐다. 함정은 head 가 주변분포 를 예측한다는 점이다. 이 실제로 무엇이었는지에 조건을 걸 수 없다.
순차 모듈 (DeepSeek-V3). 깊이 는 이전 깊이의 표현과 정답 토큰 의 임베딩을 받아 Transformer 블록 하나를 돌리고, 공유 출력 head로 을 예측한다.
각 깊이가 완전한 causal 사슬을 유지하므로(보여 준 토큰의 다음을 예측한다) 추론 때 제대로 된 조건부 drafter가 된다. 방금 샘플한 토큰을 넣으면 그다음을 제안한다. V3는 , 처음 10T 토큰 동안 , 마지막 4.8T 동안 을 쓰고, 공개 체크포인트는 685B = 본 모델 671B + MTP 모듈 14B다. 그림은 V3 레슨에 있다. 보고서가 드는 동기는 더 촘촘한 학습 신호와, 미래 토큰을 위해 표현을 “미리 계획”하게 만드는 것이다. 비용은 깊이마다 블록 하나, forward의 약 이다.
연구소들의 사용법:
| 모델 | MTP 설계 | 학습 | 추론 활용 |
|---|---|---|---|
| DeepSeek-V3 | 순차 모듈 1개 (14B) | λ 0.3 → 0.1 | 두 번째 토큰 수락률 85–90%, TPS 1.8배 |
| MiMo-V2-Flash | 가벼운 블록 (dense FFN + SWA, 블록당 0.33B) | 사전학습 1개(λ 0.3 → 0.1), 사후학습 3개 | 평균 수락 길이가 next-token CE 에 대해 에 맞음 |
| MiniMax-M2 | DeepSeek 방식 | 1개를 가중치 복사로 3개로 확장; MTP 손실이 안정될 때까지 본 모델 고정, 이후 공동 학습 | Forge가 MTP를 RL 정책과 함께 학습 (top-K KL) |
| Nemotron 3 Ultra | 가중치를 공유하는 블록 2개(attention + MoE), 재귀 적용 | 손실 0.1 (블록당 0.05) | RL rollout k = 5에서 1.46배; 배포 drafting |
| Qwen3-Next / 3.5 / 3.8 | multi-step 학습의 MTP (3.8: 4B 파라미터) | — | Qwen3.8: 4-step 평균 수락 길이 4.06 |
| DeepSeek-V4.1-Flash | MTP 없음 | 사전학습 뒤 따로 학습하는 drafter (DSpark) | — |
drafter로서의 MTP: 수락률 수학
speculative decoding은 토큰을 싸게 draft하고 본 모델 forward 한 번으로 검증한다(추론 레슨, speculative decoding). 샘플링을 정확하게 유지하는 규칙은 이렇다. 로 draft하고, 확률 로 수락하고, 아니면 정규화한 에서 샘플한다. 수락 확률은
이고 출력은 정확히 를 따른다. draft 개의 (앞의 것이 모두 수락됐다는 조건 아래) 수락 확률이 이면 검증은 첫 거절에서 멈추므로 한 step이 내는 토큰은
이다. 앞의 1은 본 모델이 언제나 내놓는 수정(또는 보너스) 토큰이다. 가 일정하면 다. 깊이별 가 떨어지는 이유는 둘이다. 깊이 의 draft는 정답이 아니라 앞선 draft에 조건을 거는데 학습은 teacher forcing이었다. 그리고 더 먼 예측은 그냥 더 어렵다. multi-step 학습(Qwen)과 재귀 적용하는 head 하나(Nemotron)는 첫 번째를 공략한다. draft step 하나가 본 decode step의 배 비용이고 개 토큰 검증이 약 한 step 비용이라면(메모리 병목인 decode 영역에서 성립) 속도 향상은 약 다.
import numpy as np
rng = np.random.default_rng(0)
V = 50
# 1) Speculative sampling (Leviathan et al.): accept draft x~q with prob min(1, p/q), else resample from (p−q)+
p = rng.dirichlet(np.ones(V) * 0.3) # target (main model) next-token distribution
q = 0.7 * p + 0.3 * rng.dirichlet(np.ones(V) * 0.3) # draft (MTP head) — close but not equal
alpha = np.minimum(p, q).sum() # acceptance probability = 1 − TV(p, q)
N = 200_000
x = rng.choice(V, size=N, p=q)
acc = rng.random(N) < np.minimum(1, p[x] / q[x])
resid = np.maximum(p - q, 0); resid /= resid.sum()
out = np.where(acc, x, rng.choice(V, size=N, p=resid))
emp = np.bincount(out.astype(np.intp), minlength=V) / N
print(f"acceptance: theory Σmin(p,q) = {alpha:.4f}, simulated = {acc.mean():.4f}")
print(f"output distribution vs target: max |emp − p| = {np.abs(emp - p).max():.4f} (exact in expectation)")
# 2) Expected tokens per verification step with k drafts and per-depth acceptance a_1..a_k
def expected_tokens(a): # 1 (bonus/corrected token) + Σ_j Π_{i≤j} a_i
return 1 + np.cumprod(a).sum()
def simulate(a, n=100_000):
u = rng.random((n, len(a))) < np.array(a) # independent per-depth accept events
run = np.cumprod(u, axis=1).sum(1) # accepted prefix length
return 1 + run.mean()
for a in [[0.875], [0.8] * 3, [0.85, 0.75, 0.65, 0.55]]:
print(f"a = {a}: E[tokens/step] = {expected_tokens(np.array(a)):.3f} (simulated {simulate(a):.3f})")
print("DeepSeek-V3 (k=1, 2nd-token acceptance 85–90%):",
f"{expected_tokens(np.array([0.85])):.2f}–{expected_tokens(np.array([0.90])):.2f} tokens/step; reported 1.8x TPS")
# 3) Speedup when a draft step costs c of a main-model step and verifying k+1 tokens costs ~1 step
def speedup(a1, decay, k, c):
a = a1 * decay ** np.arange(k)
return expected_tokens(a) / (1 + k * c)
for c in [0.02, 0.1]:
best = max(range(1, 9), key=lambda k: speedup(0.85, 0.9, k, c))
print(f"draft cost c={c}: best k={best}, speedup {speedup(0.85, 0.9, best, c):.2f}x (k=1: {speedup(0.85, 0.9, 1, c):.2f}x)")The 1.85–1.9 tokens per step implied by V3’s acceptance is consistent with its reported 1.8× TPS once verification overhead is paid. Note what the rejection rule guarantees: with sampling, MTP drafting changes speed, never the distribution — which matters when the drafter is used to generate RL rollouts.
Why does DeepSeek-V3's sequential MTP module make a better drafter than Gloeckle-style parallel heads, at equal size?
A parallel head predicts , averaging over all possible ; when the main model has sampled a specific , that marginal is a worse proposal than , so — the acceptance — is lower. The sequential module takes as input and keeps the causal chain. V3 actually shares one output head across depths, and uses a small λ.
import torch
import torch.nn as nn
import torch.nn.functional as F
class MTPModule(nn.Module):
"""DeepSeek-V3-style sequential MTP depth k: combine h^{k-1}_i with Emb(t_{i+k}), one block, shared head."""
def __init__(self, d, n_heads):
super().__init__()
self.norm_h, self.norm_e = nn.RMSNorm(d), nn.RMSNorm(d)
self.proj = nn.Linear(2 * d, d, bias=False) # M_k ∈ R^{d×2d}
self.block = nn.TransformerEncoderLayer(d, n_heads, 4 * d, batch_first=True, norm_first=True)
def forward(self, h_prev, emb_next, causal_mask):
x = self.proj(torch.cat([self.norm_h(h_prev), self.norm_e(emb_next)], dim=-1))
return self.block(x, src_mask=causal_mask, is_causal=True)
def mtp_loss(h0, tokens, embed, head, modules, lam=0.3):
"""h0: main-model final hidden states [B, T, d]; tokens: [B, T]. Depth k predicts t_{i+k+1} from position i."""
B, T, _ = h0.shape
losses, h = [], h0
for k, mod in enumerate(modules, start=1):
n = T - k - 1 # positions that have a target at i+k+1
mask = nn.Transformer.generate_square_subsequent_mask(n)
h = mod(h[:, :n], embed(tokens[:, k:k + n]), mask) # teacher forcing: true t_{i+k} as input
logits = head(h) # shared output head
losses.append(F.cross_entropy(logits.flatten(0, 1), tokens[:, k + 1:k + 1 + n].flatten()))
return lam / len(modules) * sum(losses)
V, d = 1000, 128
embed, head = nn.Embedding(V, d), nn.Linear(d, V, bias=False) # shared with the main model
modules = nn.ModuleList([MTPModule(d, 4) for _ in range(2)]) # D = 2 (V3 uses D = 1)
tokens = torch.randint(0, V, (2, 64))
h0 = torch.randn(2, 64, d) # stand-in for the main model's output
print(f"MTP loss term: {mtp_loss(h0, tokens, embed, head, modules).item():.3f}") # ≈ 0.3·ln(1000) ≈ 2.1 at initThe input end: how big should the vocabulary be?
The vocabulary trades three costs against two benefits.
- Parameters: for the input embedding, another for an untied output head.
- FLOPs per token: the LM head is a matmul, FLOPs — against roughly for the rest of the forward pass.
- Activation memory: the logits tensor is . One 8K-token sequence with K is 7.6 GiB in FP32 — larger than many layers’ activations, which is why training stacks compute cross-entropy in vocabulary chunks with an online log-sum-exp (the same trick as FlashAttention’s online softmax) and never materialise it. RL is hit twice: log-probs of the sampled tokens and, for full-vocabulary KL or distillation, the whole distribution.
The benefits: compression — fewer tokens per text means less compute per document and more text per context window (Meta reported Llama 3’s 128K tokenizer yields up to 15% fewer tokens than Llama 2’s 32K one; Qwen reported 10–60% better encoding efficiency for most languages when Qwen3.5 moved to ~250K) — and multilingual coverage, since a small vocabulary spends its merges on the dominant language and leaves other scripts fragmented. Rare tokens pay a price: an embedding row only gets gradient when its token appears, so the tail of a large vocabulary is undertrained.
Tao et al. fitted how the compute-optimal vocabulary grows with model size and concluded that Llama2-70B’s optimal vocabulary should have been at least 216K, seven times its 32K; at a fixed FLOPs, going from 32K to 43K raised ARC-Challenge from 29.1 to 32.0. Frontier vocabularies have moved accordingly: Llama 3 128,256; DeepSeek-V3 129,280; Nemotron 3 Ultra 131,072; Qwen3 151,936; Kimi K2/K3 163,840; MiniMax-M2 200,064; gpt-oss 201,088; Llama 4 202,048; Qwen3.5/3.8 248,320; Gemma 2 256,128 (all from config.json or reports).
import numpy as np
rng = np.random.default_rng(0)
V = 50
# 1) Speculative sampling (Leviathan et al.): draft x~q를 min(1, p/q)로 수락, 아니면 (p−q)+에서 다시 샘플
p = rng.dirichlet(np.ones(V) * 0.3) # 목표(본 모델) 다음 토큰 분포
q = 0.7 * p + 0.3 * rng.dirichlet(np.ones(V) * 0.3) # draft(MTP head) — 가깝지만 같지 않다
alpha = np.minimum(p, q).sum() # 수락 확률 = 1 − TV(p, q)
N = 200_000
x = rng.choice(V, size=N, p=q)
acc = rng.random(N) < np.minimum(1, p[x] / q[x])
resid = np.maximum(p - q, 0); resid /= resid.sum()
out = np.where(acc, x, rng.choice(V, size=N, p=resid))
emp = np.bincount(out.astype(np.intp), minlength=V) / N
print(f"acceptance: theory Σmin(p,q) = {alpha:.4f}, simulated = {acc.mean():.4f}")
print(f"output distribution vs target: max |emp − p| = {np.abs(emp - p).max():.4f} (exact in expectation)")
# 2) draft k개, 깊이별 수락률 a_1..a_k일 때 검증 step당 기대 토큰
def expected_tokens(a): # 1 (보너스/수정 토큰) + Σ_j Π_{i≤j} a_i
return 1 + np.cumprod(a).sum()
def simulate(a, n=100_000):
u = rng.random((n, len(a))) < np.array(a) # 깊이별 독립 수락 사건
run = np.cumprod(u, axis=1).sum(1) # 수락된 prefix 길이
return 1 + run.mean()
for a in [[0.875], [0.8] * 3, [0.85, 0.75, 0.65, 0.55]]:
print(f"a = {a}: E[tokens/step] = {expected_tokens(np.array(a)):.3f} (simulated {simulate(a):.3f})")
print("DeepSeek-V3 (k=1, 2nd-token acceptance 85–90%):",
f"{expected_tokens(np.array([0.85])):.2f}–{expected_tokens(np.array([0.90])):.2f} tokens/step; reported 1.8x TPS")
# 3) draft step 비용이 본 step의 c배이고 k+1개 검증이 ~1 step일 때 속도 향상
def speedup(a1, decay, k, c):
a = a1 * decay ** np.arange(k)
return expected_tokens(a) / (1 + k * c)
for c in [0.02, 0.1]:
best = max(range(1, 9), key=lambda k: speedup(0.85, 0.9, k, c))
print(f"draft cost c={c}: best k={best}, speedup {speedup(0.85, 0.9, best, c):.2f}x (k=1: {speedup(0.85, 0.9, 1, c):.2f}x)")V3의 수락률이 뜻하는 step당 1.85–1.9 토큰은 검증 오버헤드를 치르고 나면 보고된 TPS 1.8배와 맞는다. rejection 규칙이 보장하는 것에 주목하자. 샘플링에서 MTP drafting은 속도만 바꾸고 분포는 절대 바꾸지 않는다. drafter로 RL rollout을 만들 때 중요한 성질이다.
같은 크기라면 DeepSeek-V3의 순차 MTP 모듈이 Gloeckle식 병렬 head보다 나은 drafter인 이유는?
병렬 head는 가능한 모든 에 대해 평균한 를 예측한다. 본 모델이 특정 을 샘플했다면 그 주변분포는 보다 나쁜 제안이고, 따라서 , 즉 수락률이 낮다. 순차 모듈은 를 입력으로 받아 causal 사슬을 유지한다. V3는 실제로 출력 head 하나를 깊이 사이에 공유하고, 작은 λ를 쓴다.
import torch
import torch.nn as nn
import torch.nn.functional as F
class MTPModule(nn.Module):
"""DeepSeek-V3식 순차 MTP 깊이 k: h^{k-1}_i와 Emb(t_{i+k})를 합치고, 블록 하나, 공유 head."""
def __init__(self, d, n_heads):
super().__init__()
self.norm_h, self.norm_e = nn.RMSNorm(d), nn.RMSNorm(d)
self.proj = nn.Linear(2 * d, d, bias=False) # M_k ∈ R^{d×2d}
self.block = nn.TransformerEncoderLayer(d, n_heads, 4 * d, batch_first=True, norm_first=True)
def forward(self, h_prev, emb_next, causal_mask):
x = self.proj(torch.cat([self.norm_h(h_prev), self.norm_e(emb_next)], dim=-1))
return self.block(x, src_mask=causal_mask, is_causal=True)
def mtp_loss(h0, tokens, embed, head, modules, lam=0.3):
"""h0: 본 모델의 마지막 hidden [B, T, d]; tokens: [B, T]. 깊이 k는 위치 i에서 t_{i+k+1}을 예측한다."""
B, T, _ = h0.shape
losses, h = [], h0
for k, mod in enumerate(modules, start=1):
n = T - k - 1 # i+k+1에 목표가 있는 위치 수
mask = nn.Transformer.generate_square_subsequent_mask(n)
h = mod(h[:, :n], embed(tokens[:, k:k + n]), mask) # teacher forcing: 정답 t_{i+k}를 입력으로
logits = head(h) # 공유 출력 head
losses.append(F.cross_entropy(logits.flatten(0, 1), tokens[:, k + 1:k + 1 + n].flatten()))
return lam / len(modules) * sum(losses)
V, d = 1000, 128
embed, head = nn.Embedding(V, d), nn.Linear(d, V, bias=False) # 본 모델과 공유
modules = nn.ModuleList([MTPModule(d, 4) for _ in range(2)]) # D = 2 (V3는 D = 1)
tokens = torch.randint(0, V, (2, 64))
h0 = torch.randn(2, 64, d) # 본 모델 출력 대용
print(f"MTP loss term: {mtp_loss(h0, tokens, embed, head, modules).item():.3f}") # 초기화 때 ≈ 0.3·ln(1000) ≈ 2.1입력 쪽: 어휘는 얼마나 커야 하나
어휘 크기 는 비용 셋과 이득 둘을 맞바꾼다.
- 파라미터: 입력 임베딩에 , 묶지 않은 출력 head에 또 .
- 토큰당 FLOPs: LM head는 행렬곱, FLOPs다. forward의 나머지는 대략 다.
- activation 메모리: logits 텐서는 다. K에서 8K 토큰 시퀀스 하나가 FP32로 7.6 GiB로, 많은 층의 activation보다 크다. 그래서 학습 스택은 cross-entropy를 어휘 chunk 단위로 online log-sum-exp(FlashAttention의 online softmax와 같은 요령)로 계산하고 전체를 실체화하지 않는다. RL은 두 번 맞는다. 샘플한 토큰의 log-prob, 그리고 full-vocabulary KL이나 증류라면 분포 전체다.
이득은 압축이다. 텍스트당 토큰이 적으면 문서당 연산이 줄고 문맥 창에 더 많은 텍스트가 들어간다(Meta는 Llama 3의 128K 토크나이저가 Llama 2의 32K보다 토큰을 최대 15% 덜 쓴다고 보고했고, Qwen은 Qwen3.5가 약 250K로 바꾸며 대부분 언어에서 인코딩 효율이 10–60% 좋아졌다고 보고했다). 그리고 다국어 커버리지다. 작은 어휘는 merge를 지배적인 언어에 써 버려 다른 문자 체계를 잘게 쪼갠다. 드문 토큰은 대가를 치른다. 임베딩 행은 그 토큰이 나올 때만 기울기를 받으므로 큰 어휘의 꼬리는 덜 학습된다.
Tao et al.은 compute-optimal 어휘가 모델 크기에 따라 어떻게 커지는지 맞추고, Llama2-70B의 최적 어휘는 그 32K의 일곱 배인 216K 이상이었어야 한다고 결론지었다. FLOPs 고정에서 32K → 43K로 늘리자 ARC-Challenge가 29.1에서 32.0으로 올랐다. 프런티어 어휘도 그렇게 움직였다. Llama 3 128,256; DeepSeek-V3 129,280; Nemotron 3 Ultra 131,072; Qwen3 151,936; Kimi K2/K3 163,840; MiniMax-M2 200,064; gpt-oss 201,088; Llama 4 202,048; Qwen3.5/3.8 248,320; Gemma 2 256,128 (모두 config.json 또는 보고서).
import numpy as np
# (vocab V, hidden d, active params per token, tied?) — V, d, tying from config.json; active from model cards/reports
models = {
"Qwen3-0.6B": (151_936, 1024, 0.6e9, True),
"Llama-3.1-8B": (128_256, 4096, 8.0e9, False),
"gpt-oss-120b": (201_088, 2880, 5.13e9, False),
"Qwen3.8-Flash-Next": (248_320, 2560, 6.0e9, False),
"Qwen3.5-397B-A17B": (248_320, 4096, 17e9, False),
"DeepSeek-V3": (129_280, 7168, 37e9, False),
}
T = 8192
print(f"{'model':20s} {'emb+head params':>15s} {'head FLOPs/token':>17s} {'≈ share of active':>17s} {'FP32 logits, 8K seq':>20s}")
for name, (V, d, act, tied) in models.items():
emb = V * d * (1 if tied else 2)
head_flops = 2 * d * V # one matmul h·Wᵀ per token
share = head_flops / (2 * act) # forward ≈ 2·(active params) FLOPs per token
logits = T * V * 4 # materialised [T, V] logits in FP32
print(f"{name:20s} {emb/1e9:13.2f} B {head_flops/1e9:14.2f} G {share:16.1%} {logits/2**30:17.2f} GiB")
# weight tying saves V·d parameters — decisive for small models, negligible for large ones
V, d = 151_936, 1024
print(f"\nQwen3-0.6B: tying saves {V*d/1e6:.0f}M parameters ≈ {V*d/0.6e9:.0%} of the model")
# softmax over V is a log-sum-exp: chunk it so the [T, V] matrix is never fully materialised
rng = np.random.default_rng(0)
h, W = rng.normal(size=(256, 64)), rng.normal(size=(20_000, 64)) / 8
full = np.log(np.exp(h @ W.T).sum(1))
m, s = np.full(256, -np.inf), np.zeros(256)
for c in range(0, 20_000, 4096): # online log-sum-exp over vocabulary chunks
z = h @ W[c:c + 4096].T
m_new = np.maximum(m, z.max(1)); s = s * np.exp(m - m_new) + np.exp(z - m_new[:, None]).sum(1); m = m_new
print(f"chunked log Z equals full log Z: {np.allclose(full, m + np.log(s))} (peak logits memory 4096/20000 of full)")Weight tying
Tying sets the output head to the input embedding, (GPT from scratch). It saves parameters, and output rows of rare tokens benefit from input-side training. The table above says when that matters: for Qwen3-0.6B the embedding is 26% of the model and the config ties (tie_word_embeddings: true), as do Gemma 2 (all sizes) and SmolLM3; Qwen3-8B and every frontier MoE model in this track keep them separate. At scale the saving is a rounding error, and the two matrices do different jobs: the input row encodes what a token is, the output row where the final state must point to predict it — and the output side receives gradient for every vocabulary row at every position through the softmax, while an input row is updated only when its token occurs. Untying lets each be shaped by its own role.
N-gram embeddings: parameters without FLOPs
MoE separates parameters from FLOPs by activating a few experts per token; a table lookup separates them completely. Engram (Cheng et al. 2026) revives the n-gram embedding at scale:
- Compress token ids to canonical ids (NFKC, lower-casing — about 23% fewer ids for a 128K tokenizer) and form the suffix n-grams for .
- Hash each n-gram with independent heads into prime-sized tables, , and concatenate everything into .
- Gate by context: , , , then a short causal convolution, and add (convolved) to the residual stream. When the retrieved memory contradicts the context, .
Two properties make it an architectural axis rather than a trick. The address is known before the forward pass — it depends only on input tokens — so the tables can live in host DRAM and be prefetched while earlier layers compute: with a 100B-parameter table in host memory the paper measures 1.9–2.8% lower throughput on H800. And it trades against MoE: splitting a fixed sparse-parameter budget between experts and Engram gives a U-shaped loss, best at about 20–25% Engram. Engram-27B beat an iso-parameter, iso-FLOP MoE (MMLU +3.4, BBH +5.0, HumanEval +3.0, MATH +2.4) and lifted multi-query needle-in-a-haystack from 84.2 to 97.0. DeepSeek-V4.1-Flash ships a 196B Engram with 2-, 3- and 4-gram tables.
Qwen3.8-Flash-Next puts a 51B n-gram table (config: trigrams, 20M base slots, 8 hash heads per n-gram) at layer 2 only — so its prefetch overlaps with layer 1 — and reports the trade-off honestly: in the placement ablation the layer-2 table scores 47.94 vs 45.44 without; but growing the n-gram vocabulary from 20× to 200× the 250K base keeps lowering loss (1.553 → 1.526) while benchmarks saturate or fluctuate, and under a fixed total parameter budget it found no clear downstream gain over MoE alone. Read with the Qwen3.8 lesson.
Why several hash heads? A table of rows holding distinct n-grams collides a given n-gram in one head with probability about . With heads (each of rows at a fixed budget) two n-grams are confused only if they collide in all heads, since the retrieved rows are concatenated:
import numpy as np
rng = np.random.default_rng(0)
# A Zipf-like token stream; its distinct trigrams play the role of n-gram "vocabulary"
V, T = 2000, 200_000
ranks = np.arange(1, V + 1)
tok = rng.choice(V, size=T, p=ranks**-1.2 / (ranks**-1.2).sum())
tri = (tok[:-2].astype(np.int64) * V + tok[1:-1]) * V + tok[2:] # id of the trigram ending at t
uniq, inv, cnt = np.unique(tri, return_inverse=True, return_counts=True)
print(f"{T:,} positions, {len(uniq):,} distinct trigrams ({(cnt == 1).mean():.0%} seen once)")
def hash_heads(ids, K, M, seed=1):
"""K independent multiplicative-XOR-style hashes into tables of size M (one table per head)."""
r = np.random.default_rng(seed)
a = r.integers(1, 2**31 - 1, size=K, dtype=np.int64) | 1
b = r.integers(0, 2**31 - 1, size=K, dtype=np.int64)
return ((ids[:, None] * a + b) ^ (ids[:, None] >> 7)) % M # [n_ids, K]
budget = 2**18 # total rows across all heads
for K in [1, 2, 4, 8]:
M = budget // K
h = hash_heads(uniq, K, M)
clean_any = np.zeros(len(uniq), bool)
for j in range(K):
col = h[:, j].astype(np.intp)
occ = np.bincount(col, minlength=M) # how many trigrams share each row
clean_any |= occ[col] == 1 # this head gives a private row
sig = {tuple(row) for row in h.tolist()} # distinct K-row signatures
w = cnt / cnt.sum() # weight by occurrence frequency
print(f"K={K}, {M:6d} rows/head: some head collision-free for {np.average(clean_any, weights=w):.1%} of positions;"
f" distinct signatures = {len(sig) / len(uniq):.1%} of distinct trigrams")
# the module concatenates the K retrieved rows, so two trigrams are confused only if ALL K rows collideWith one table, a fifth of the trigrams share their entire embedding with another; with two heads at the same budget almost every trigram has a distinct signature. More heads keep signatures distinct but leave fewer trigrams with any private row — which is where the context gate earns its keep, suppressing a polluted lookup.
Why can a 51B or 196B n-gram table sit in host memory without slowing decoding much, while MoE experts of the same size cannot?
Engram’s addresses are hashes of the last 2–3 (compressed) token ids. They are available as soon as the token is, so the gather from host DRAM can overlap with layer 1 (hence layer 2 placement in Qwen3.8, and the measured ≤2.8% overhead for a 100B table in the Engram paper). MoE routing needs the router’s input — a hidden state produced by the preceding layers — so expert weights must already be resident or fetched on the critical path.
Summary
- MTP adds extra targets per position. Parallel heads predict marginals; DeepSeek-V3’s sequential modules condition on the true intermediate token, keep the causal chain, and double as a conditional drafter at inference.
- Speculative sampling accepts with and preserves exactly; acceptance is and a step yields tokens. Per-depth decay of acceptance and draft cost set the best draft length — hence light MTP blocks (MiMo) and recursive shared heads (Nemotron).
- Vocabulary size sets embedding parameters (, ×2 untied), head FLOPs () and a logits tensor; it buys compression and multilingual coverage. Optimal grows with model size, and frontier vocabularies are now 128K–256K.
- Tie embeddings when is a large fraction of the model (sub-billion models); untie at scale.
- Hashed n-gram tables (Engram, Qwen3.8) add parameters without FLOPs; their addresses are known before the forward pass, so they live in host memory with prefetch. Multiple hash heads make collisions rare; the gains are real but saturate, and under a fixed parameter budget they compete with MoE experts (U-shaped optimum near 20–25%).
import numpy as np
# (어휘 V, hidden d, 토큰당 활성 파라미터, tying 여부) — V, d, tying은 config.json; 활성은 model card/보고서
models = {
"Qwen3-0.6B": (151_936, 1024, 0.6e9, True),
"Llama-3.1-8B": (128_256, 4096, 8.0e9, False),
"gpt-oss-120b": (201_088, 2880, 5.13e9, False),
"Qwen3.8-Flash-Next": (248_320, 2560, 6.0e9, False),
"Qwen3.5-397B-A17B": (248_320, 4096, 17e9, False),
"DeepSeek-V3": (129_280, 7168, 37e9, False),
}
T = 8192
print(f"{'model':20s} {'emb+head params':>15s} {'head FLOPs/token':>17s} {'≈ share of active':>17s} {'FP32 logits, 8K seq':>20s}")
for name, (V, d, act, tied) in models.items():
emb = V * d * (1 if tied else 2)
head_flops = 2 * d * V # 토큰당 행렬곱 h·Wᵀ 하나
share = head_flops / (2 * act) # forward ≈ 토큰당 2·(활성 파라미터) FLOPs
logits = T * V * 4 # FP32로 실체화한 [T, V] logits
print(f"{name:20s} {emb/1e9:13.2f} B {head_flops/1e9:14.2f} G {share:16.1%} {logits/2**30:17.2f} GiB")
# weight tying은 V·d 파라미터를 아낀다 — 작은 모델에서는 결정적, 큰 모델에서는 무시할 만하다
V, d = 151_936, 1024
print(f"\nQwen3-0.6B: tying saves {V*d/1e6:.0f}M parameters ≈ {V*d/0.6e9:.0%} of the model")
# V에 대한 softmax는 log-sum-exp: chunk로 나눠 [T, V] 행렬을 전부 실체화하지 않는다
rng = np.random.default_rng(0)
h, W = rng.normal(size=(256, 64)), rng.normal(size=(20_000, 64)) / 8
full = np.log(np.exp(h @ W.T).sum(1))
m, s = np.full(256, -np.inf), np.zeros(256)
for c in range(0, 20_000, 4096): # 어휘 chunk에 대한 online log-sum-exp
z = h @ W[c:c + 4096].T
m_new = np.maximum(m, z.max(1)); s = s * np.exp(m - m_new) + np.exp(z - m_new[:, None]).sum(1); m = m_new
print(f"chunked log Z equals full log Z: {np.allclose(full, m + np.log(s))} (peak logits memory 4096/20000 of full)")Weight tying
tying은 출력 head를 입력 임베딩으로 둔다. (GPT 바닥부터). 파라미터를 아끼고, 드문 토큰의 출력 행이 입력 쪽 학습의 덕을 본다. 위 표가 그것이 언제 중요한지 말해 준다. Qwen3-0.6B에서는 임베딩이 모델의 26%이고 config도 묶는다(tie_word_embeddings: true). Gemma 2(모든 크기)와 SmolLM3도 그렇다. Qwen3-8B와 이 트랙의 모든 프런티어 MoE 모델은 따로 둔다. 규모가 커지면 절약분은 반올림 오차이고, 두 행렬은 하는 일이 다르다. 입력 행은 토큰이 무엇인지를, 출력 행은 그 토큰을 예측하려면 마지막 상태가 어디를 가리켜야 하는지를 부호화한다. 그리고 출력 쪽은 softmax를 통해 모든 위치에서 모든 어휘 행이 기울기를 받는 반면, 입력 행은 그 토큰이 나올 때만 갱신된다. 묶지 않으면 각자가 제 역할대로 빚어진다.
n-gram 임베딩: FLOPs 없는 파라미터
MoE는 토큰마다 expert 몇 개만 켜서 파라미터와 FLOPs를 분리한다. 테이블 조회는 둘을 완전히 분리한다. Engram(Cheng et al. 2026)은 n-gram 임베딩을 큰 규모로 되살린다.
- 토큰 id를 정규 id로 압축하고(NFKC, 소문자화 — 128K 토크나이저에서 id가 약 23% 줄어든다) 의 접미 n-gram 을 만든다.
- n-gram마다 독립 hash head 개로 소수 크기의 테이블을 찾고 , 전부 이어 붙여 를 만든다.
- 문맥으로 gate한다. , , , 짧은 causal convolution을 거쳐 를 residual stream에 더한다. 찾아온 기억이 문맥과 어긋나면 이다.
두 성질이 이것을 요령이 아니라 아키텍처의 축으로 만든다. 주소가 forward 전에 정해진다. 입력 토큰에만 의존하므로 테이블을 host DRAM에 두고 앞 층이 계산하는 동안 prefetch할 수 있다. 논문은 100B 파라미터 테이블을 host 메모리에 두었을 때 H800에서 처리량이 1.9–2.8% 줄었다고 잰다. 그리고 MoE와 맞바꾼다. 고정된 sparse 파라미터 예산을 expert와 Engram에 나누면 손실이 U자형이고, Engram이 약 20–25%일 때 가장 좋다. Engram-27B는 파라미터·FLOPs가 같은 MoE를 이겼고(MMLU +3.4, BBH +5.0, HumanEval +3.0, MATH +2.4), multi-query needle-in-a-haystack을 84.2에서 97.0으로 올렸다. DeepSeek-V4.1-Flash는 2·3·4-gram 테이블의 196B Engram을 싣는다.
Qwen3.8-Flash-Next는 51B n-gram 테이블(config: trigram, 기본 슬롯 2천만, n-gram당 hash head 8개)을 층 2에만 둔다. prefetch가 층 1과 겹치게 하기 위해서다. 그리고 trade-off를 솔직하게 보고한다. 배치 ablation에서 층 2 테이블은 47.94, 없으면 45.44다. 하지만 n-gram 어휘를 250K 기본 어휘의 20배에서 200배로 키우면 손실은 계속 내려가는데(1.553 → 1.526) 벤치마크는 포화되거나 흔들리고, 총 파라미터 예산을 고정하면 MoE만 쓸 때보다 분명한 이득을 찾지 못했다. Qwen3.8 레슨과 함께 읽자.
왜 hash head가 여러 개인가? 행 테이블에 서로 다른 n-gram 개가 들어 있으면 주어진 n-gram이 head 하나에서 충돌할 확률은 약 이다. head가 개(예산 고정이면 각 행)이면 찾아온 행을 이어 붙이므로 두 n-gram은 모든 head에서 충돌할 때만 혼동된다.
import numpy as np
rng = np.random.default_rng(0)
# Zipf 꼴 토큰 스트림; 그 안의 서로 다른 trigram이 n-gram "어휘" 역할을 한다
V, T = 2000, 200_000
ranks = np.arange(1, V + 1)
tok = rng.choice(V, size=T, p=ranks**-1.2 / (ranks**-1.2).sum())
tri = (tok[:-2].astype(np.int64) * V + tok[1:-1]) * V + tok[2:] # t에서 끝나는 trigram의 id
uniq, inv, cnt = np.unique(tri, return_inverse=True, return_counts=True)
print(f"{T:,} positions, {len(uniq):,} distinct trigrams ({(cnt == 1).mean():.0%} seen once)")
def hash_heads(ids, K, M, seed=1):
"""크기 M의 테이블(head당 하나)로 가는 독립 multiplicative-XOR식 해시 K개."""
r = np.random.default_rng(seed)
a = r.integers(1, 2**31 - 1, size=K, dtype=np.int64) | 1
b = r.integers(0, 2**31 - 1, size=K, dtype=np.int64)
return ((ids[:, None] * a + b) ^ (ids[:, None] >> 7)) % M # [n_ids, K]
budget = 2**18 # 모든 head를 합친 행 수
for K in [1, 2, 4, 8]:
M = budget // K
h = hash_heads(uniq, K, M)
clean_any = np.zeros(len(uniq), bool)
for j in range(K):
col = h[:, j].astype(np.intp)
occ = np.bincount(col, minlength=M) # 행마다 몇 개의 trigram이 공유하나
clean_any |= occ[col] == 1 # 이 head가 전용 행을 준다
sig = {tuple(row) for row in h.tolist()} # 서로 다른 K행 서명
w = cnt / cnt.sum() # 등장 빈도로 가중
print(f"K={K}, {M:6d} rows/head: some head collision-free for {np.average(clean_any, weights=w):.1%} of positions;"
f" distinct signatures = {len(sig) / len(uniq):.1%} of distinct trigrams")
# 모듈은 K개 행을 이어 붙이므로, 두 trigram은 K개 행이 모두 충돌할 때만 혼동된다테이블이 하나면 trigram의 5분의 1이 임베딩 전체를 다른 것과 공유한다. 같은 예산에서 head가 둘이면 거의 모든 trigram의 서명이 구별된다. head를 더 늘리면 서명은 구별되지만 전용 행을 가진 trigram이 줄어든다. 오염된 조회를 억누르는 문맥 gate가 제 몫을 하는 곳이다.
51B나 196B짜리 n-gram 테이블은 host 메모리에 두어도 decode가 크게 느려지지 않는데, 같은 크기의 MoE expert는 그럴 수 없는 이유는?
Engram의 주소는 마지막 2–3개 (압축된) 토큰 id의 해시다. 토큰이 정해지자마자 알 수 있으므로 host DRAM에서 모으는 작업을 층 1과 겹칠 수 있다(그래서 Qwen3.8은 층 2에 두고, Engram 논문은 100B 테이블에서 ≤2.8% 오버헤드를 쟀다). MoE routing에는 router의 입력, 즉 앞 층들이 만든 hidden state가 필요하므로 expert 가중치는 이미 상주해 있거나 임계 경로에서 가져와야 한다.
정리
- MTP는 위치마다 목표를 개 더한다. 병렬 head는 주변분포를 예측하고, DeepSeek-V3의 순차 모듈은 실제 중간 토큰에 조건을 걸어 causal 사슬을 유지하며 추론 때 조건부 drafter를 겸한다.
- speculative sampling은 로 수락하고 를 정확히 보존한다. 수락률은 , step 하나는 토큰을 낸다. 깊이별 수락률 감소와 draft 비용이 최적 draft 길이를 정한다. 그래서 MTP 블록은 가볍고(MiMo) head는 재귀로 공유된다(Nemotron).
- 어휘 크기는 임베딩 파라미터(, 묶지 않으면 ×2), head FLOPs(), logits 텐서를 정하고, 압축과 다국어 커버리지를 산다. 최적 는 모델 크기와 함께 커지고, 프런티어 어휘는 이제 128K–256K다.
- 가 모델의 큰 비중일 때(10억 미만 모델) 임베딩을 묶고, 규모가 크면 푼다.
- 해시 n-gram 테이블(Engram, Qwen3.8)은 FLOPs 없이 파라미터를 더한다. 주소가 forward 전에 정해지므로 prefetch와 함께 host 메모리에 둔다. hash head 여럿이 충돌을 드물게 만들고, 이득은 실재하지만 포화되며, 파라미터 예산이 고정되면 MoE expert와 경쟁한다(약 20–25%에서 U자형 최적).
더 읽을거리Further reading
- Gloeckle et al., Better & Faster Large Language Models via Multi-token Prediction (ICML 2024) — 공유 trunk 위 n개 독립 head. 13B에서 HumanEval +12%, MBPP +17%, 4-token 모델은 추론 최대 3배.n independent heads on a shared trunk; at 13B +12% HumanEval and +17% MBPP; 4-token models up to 3× faster at inference.
- DeepSeek-AI, DeepSeek-V3 Technical Report (2024) — 순차 MTP 모듈(D=1, λ 0.3→0.1)과 drafter로서의 수락률 85–90%, 1.8배 TPS.Sequential MTP modules (D = 1, λ 0.3 → 0.1) and, as a drafter, 85–90% acceptance and 1.8× TPS.
- Leviathan, Kalman, Matias, Fast Inference from Transformers via Speculative Decoding (ICML 2023) — 분포를 바꾸지 않는 rejection 규칙과 기대 토큰 수 공식.The distribution-preserving rejection rule and the expected-tokens formula.
- Tao et al., Scaling Laws with Vocabulary: Larger Models Deserve Larger Vocabularies (NeurIPS 2024) — 최적 어휘 크기는 모델과 함께 커진다. Llama2-70B는 216K 이상이어야 했다는 추정.The optimal vocabulary grows with the model; Llama2-70B should have had at least 216K.
- Cheng et al., Conditional Memory via Scalable Lookup: A New Axis of Sparsity for LLMs (Engram, 2026) — 해시 n-gram 메모리, context-aware gating, host 메모리 prefetch, MoE와의 U자형 배분 법칙.Hashed n-gram memory, context-aware gating, host-memory prefetch, and the U-shaped allocation law against MoE.
- Qwen Team, On the Design of Qwen3.8-Next Architecture (2026) — 51B n-gram 임베딩의 배치·어휘 크기 ablation, MTP 4-step 평균 수락 길이.Placement and vocabulary-size ablations of the 51B n-gram embedding; 4-step mean MTP acceptance length.
- Press & Wolf, Using the Output Embedding to Improve Language Models (EACL 2017) — weight tying의 원 논문.The original weight-tying paper.