Track VII · Architecture Deep Dives · 07/12

모델의 양 끝 — multi-token prediction, 어휘, tying, n-gram 임베딩Both ends of the model — multi-token prediction, vocabulary, tying, n-gram embeddings

모델이 무엇을 예측하고(MTP) 무엇을 읽는지(어휘, 임베딩 tying, n-gram 임베딩)를 비용과 함께 본다. Gloeckle의 병렬 head와 DeepSeek-V3의 순차 모듈을 비교하고, MTP를 speculative decoding drafter로 쓸 때의 수락률 수학을 유도·검증하며, 어휘 크기가 파라미터·FLOPs·logits 메모리를 어떻게 정하는지, Engram과 Qwen3.8의 해시 n-gram 테이블이 왜 FLOPs 없이 파라미터를 늘리는 축인지 계산한다.What the model predicts (MTP) and what it reads (vocabulary, embedding tying, n-gram embeddings), with their costs. Compare Gloeckle's parallel heads with DeepSeek-V3's sequential modules, derive and verify the acceptance math of MTP as a speculative-decoding drafter, compute how vocabulary size sets parameters, FLOPs and logits memory, and why the hashed n-gram tables of Engram and Qwen3.8 are an axis that adds parameters without FLOPs.

50 분min multi-token prediction · MTP · speculative decoding · acceptance rate · vocabulary · tokenizer · weight tying · n-gram embedding · Engram · hashing 먼저 볼 것:Before this: GPT를 바닥부터GPT from scratch, 토크나이저Tokenizers, 추론 최적화Inference optimisation

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, L=−∑tlog⁡pθ(xt+1∣x≤t)\mathcal L=-\sum_t\log p_\theta(x_{t+1}\mid x_{\le t}). A forward pass over TT tokens produces TT 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 hth_t; nn independent output heads predict xt+1,…,xt+nx_{t+1},\dots,x_{t+n} from it:

LMTP=−∑t∑k=1nlog⁡pθ(k)(xt+k∣ht).\mathcal L_{\text{MTP}}=-\sum_t\sum_{k=1}^{n}\log p^{(k)}_\theta(x_{t+k}\mid h_t).

With n=4n=4 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 kk predicts the marginal p(xt+k∣x≤t)p(x_{t+k}\mid x_{\le t}) — it cannot condition on what xt+1,…,xt+k−1x_{t+1},\dots,x_{t+k-1} actually turned out to be.

Sequential modules (DeepSeek-V3). Depth kk takes the previous depth’s representation and the embedding of the true token ti+kt_{i+k}, runs one Transformer block, and predicts ti+k+1t_{i+k+1} with the shared output head:

hi′ k=Mk[RMSNorm⁡(hik−1);RMSNorm⁡(Emb⁡(ti+k))],hk=TRM⁡k(h′ k),L=Lmain+λD∑k=1DLMTPk.h_i'^{\,k}=M_k\big[\operatorname{RMSNorm}(h_i^{k-1});\operatorname{RMSNorm}(\operatorname{Emb}(t_{i+k}))\big],\quad h^{k}=\operatorname{TRM}_k(h'^{\,k}),\quad \mathcal L=\mathcal L_{\text{main}}+\frac{\lambda}{D}\sum_{k=1}^{D}\mathcal L^{k}_{\text{MTP}} .

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 D=1D=1, λ=0.3\lambda=0.3 for the first 10T tokens and 0.10.1 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 1/L1/L of the forward pass.

How the labs use it:

ModelMTP designTrainingInference use
DeepSeek-V31 sequential module (14B)λ 0.3 → 0.12nd-token acceptance 85–90%, 1.8× TPS
MiMo-V2-Flashlight blocks (dense FFN + SWA, 0.33B each)1 block in pre-training (λ 0.3 → 0.1), 3 in post-trainingmean accept length fits y=4(1−0.58x0.58)y=4(1-0.58x^{0.58}) in next-token CE xx
MiniMax-M2DeepSeek-style1 module, expanded to 3 by copying weights; main model frozen until MTP loss settles, then jointForge co-trains MTP with the RL policy (top-K KL)
Nemotron 3 Ultra2 blocks (attention + MoE) with shared weights, applied recursivelyloss 0.1 (0.05 per block)RL rollouts 1.46× at k = 5; deployment drafting
Qwen3-Next / 3.5 / 3.8MTP with multi-step training (3.8: 4B params)—Qwen3.8: 4-step mean accepted length 4.06
DeepSeek-V4.1-Flashno MTPa separate drafter (DSpark) trained after pre-training—
Sources: V3, MiMo-V2, MiniMax-M2, Nemotron 3 Ultra, Qwen3.8, V4 lessons; Qwen3.8 report Table 4.

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 x∼qx\sim q, accept with probability min⁡(1,p(x)/q(x))\min(1,p(x)/q(x)), otherwise sample from (p−q)+(p-q)_+ normalised. The probability of acceptance is

α=∑xq(x)min⁡ ⁣(1,p(x)q(x))=∑xmin⁡(p(x),q(x))=1−TV⁡(p,q),\alpha=\sum_x q(x)\min\!\Big(1,\tfrac{p(x)}{q(x)}\Big)=\sum_x\min(p(x),q(x))=1-\operatorname{TV}(p,q),

and the output is distributed exactly as pp. With kk drafts whose acceptance probabilities (given all earlier ones were accepted) are a1,…,aka_1,\dots,a_k, verification stops at the first rejection, so one step yields

E[tokens]=1+∑j=1k∏i≤jai,\mathbb E[\text{tokens}]=1+\sum_{j=1}^{k}\prod_{i\le j}a_i ,

the leading 1 being the corrected (or bonus) token the main model always contributes. With constant aa this is (1−ak+1)/(1−a)(1-a^{k+1})/(1-a). Two things make the per-depth aja_j fall: drafts at depth jj 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 cc of a main decode step and verifying k+1k+1 tokens costs about one step (true in the memory-bound decode regime), the speedup is about E[tokens]/(1+kc)\mathbb E[\text{tokens}]/(1+kc).

앞의 레슨들은 네트워크의 가운데 — attention, MoE, 순환 상태, residual stream — 를 다뤘다. 이 레슨은 양 끝을 본다. 출력 쪽에서는 모델이 무엇을 예측하도록 학습되는지, 그리고 두 번째 예측 head가 추론 때 어떻게 공짜 draft 모델이 되는지. 입력 쪽에서는 어휘가 얼마나 커야 하는지, 입력과 출력 임베딩이 가중치를 공유해야 하는지, 그리고 더 새로운 생각인 해시 n-gram 테이블, 즉 FLOPs를 거의 쓰지 않고 수백억 파라미터를 더하는 방법이다.

next-token prediction은 신호를 남긴다

표준 목적함수는 위치마다 목표를 하나 준다. L=−∑tlog⁡pθ(xt+1∣x≤t)\mathcal L=-\sum_t\log p_\theta(x_{t+1}\mid x_{\le t}). TT 토큰의 forward 한 번이 바로 다음 토큰에 대한 학습 신호 TT개를 만든다. multi-token prediction(MTP)은 각 위치에 더 먼 토큰도 예측하게 한다.

병렬 head (Gloeckle et al. 2024). 공유 trunk가 hth_t를 만들고, 독립적인 출력 head nn개가 그것으로 xt+1,…,xt+nx_{t+1},\dots,x_{t+n}을 예측한다.

LMTP=−∑t∑k=1nlog⁡pθ(k)(xt+k∣ht).\mathcal L_{\text{MTP}}=-\sum_t\sum_{k=1}^{n}\log p^{(k)}_\theta(x_{t+k}\mid h_t).

n=4n=4에서 그들의 13B 코드 모델은 next-token baseline보다 HumanEval 문제를 12%, MBPP를 17% 더 풀었고, 추가 head가 스스로 draft를 만들면 4-token 모델이 추론에서 최대 3배 빨랐다. 함정은 head kk가 주변분포 p(xt+k∣x≤t)p(x_{t+k}\mid x_{\le t})를 예측한다는 점이다. xt+1,…,xt+k−1x_{t+1},\dots,x_{t+k-1}이 실제로 무엇이었는지에 조건을 걸 수 없다.

순차 모듈 (DeepSeek-V3). 깊이 kk는 이전 깊이의 표현과 정답 토큰 ti+kt_{i+k}의 임베딩을 받아 Transformer 블록 하나를 돌리고, 공유 출력 head로 ti+k+1t_{i+k+1}을 예측한다.

hi′ k=Mk[RMSNorm⁡(hik−1);RMSNorm⁡(Emb⁡(ti+k))],hk=TRM⁡k(h′ k),L=Lmain+λD∑k=1DLMTPk.h_i'^{\,k}=M_k\big[\operatorname{RMSNorm}(h_i^{k-1});\operatorname{RMSNorm}(\operatorname{Emb}(t_{i+k}))\big],\quad h^{k}=\operatorname{TRM}_k(h'^{\,k}),\quad \mathcal L=\mathcal L_{\text{main}}+\frac{\lambda}{D}\sum_{k=1}^{D}\mathcal L^{k}_{\text{MTP}} .

각 깊이가 완전한 causal 사슬을 유지하므로(보여 준 토큰의 다음을 예측한다) 추론 때 제대로 된 조건부 drafter가 된다. 방금 샘플한 토큰을 넣으면 그다음을 제안한다. V3는 D=1D=1, 처음 10T 토큰 동안 λ=0.3\lambda=0.3, 마지막 4.8T 동안 0.10.1을 쓰고, 공개 체크포인트는 685B = 본 모델 671B + MTP 모듈 14B다. 그림은 V3 레슨에 있다. 보고서가 드는 동기는 더 촘촘한 학습 신호와, 미래 토큰을 위해 표현을 “미리 계획”하게 만드는 것이다. 비용은 깊이마다 블록 하나, forward의 약 1/L1/L이다.

연구소들의 사용법:

모델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 xx에 대해 y=4(1−0.58x0.58)y=4(1-0.58x^{0.58})에 맞음
MiniMax-M2DeepSeek 방식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.8multi-step 학습의 MTP (3.8: 4B 파라미터)—Qwen3.8: 4-step 평균 수락 길이 4.06
DeepSeek-V4.1-FlashMTP 없음사전학습 뒤 따로 학습하는 drafter (DSpark)—
출처: V3, MiMo-V2, MiniMax-M2, Nemotron 3 Ultra, Qwen3.8, V4 레슨; Qwen3.8 보고서 Table 4.

drafter로서의 MTP: 수락률 수학

speculative decoding은 토큰을 싸게 draft하고 본 모델 forward 한 번으로 검증한다(추론 레슨, speculative decoding). 샘플링을 정확하게 유지하는 규칙은 이렇다. x∼qx\sim q로 draft하고, 확률 min⁡(1,p(x)/q(x))\min(1,p(x)/q(x))로 수락하고, 아니면 정규화한 (p−q)+(p-q)_+에서 샘플한다. 수락 확률은

α=∑xq(x)min⁡ ⁣(1,p(x)q(x))=∑xmin⁡(p(x),q(x))=1−TV⁡(p,q)\alpha=\sum_x q(x)\min\!\Big(1,\tfrac{p(x)}{q(x)}\Big)=\sum_x\min(p(x),q(x))=1-\operatorname{TV}(p,q)

이고 출력은 정확히 pp를 따른다. draft kk개의 (앞의 것이 모두 수락됐다는 조건 아래) 수락 확률이 a1,…,aka_1,\dots,a_k이면 검증은 첫 거절에서 멈추므로 한 step이 내는 토큰은

E[tokens]=1+∑j=1k∏i≤jai\mathbb E[\text{tokens}]=1+\sum_{j=1}^{k}\prod_{i\le j}a_i

이다. 앞의 1은 본 모델이 언제나 내놓는 수정(또는 보너스) 토큰이다. aa가 일정하면 (1−ak+1)/(1−a)(1-a^{k+1})/(1-a)다. 깊이별 aja_j가 떨어지는 이유는 둘이다. 깊이 jj의 draft는 정답이 아니라 앞선 draft에 조건을 거는데 학습은 teacher forcing이었다. 그리고 더 먼 예측은 그냥 더 어렵다. multi-step 학습(Qwen)과 재귀 적용하는 head 하나(Nemotron)는 첫 번째를 공략한다. draft step 하나가 본 decode step의 cc배 비용이고 k+1k+1개 토큰 검증이 약 한 step 비용이라면(메모리 병목인 decode 영역에서 성립) 속도 향상은 약 E[tokens]/(1+kc)\mathbb E[\text{tokens}]/(1+kc)다.

검증당 토큰tokens / verification – 속도 향상speedup – 최적 kbest k – 상한 (모두 수락)ceiling (all accepted) –
Left: probability that at least j drafted tokens are accepted (the bars multiply: a draft at depth j only counts if depths 1…j−1 were accepted). Right: expected speedup for k = 1…8 at the current a₁, δ and c. Set k = 1, a₁ = 0.85–0.9: 1.85–1.9 tokens per step, the regime DeepSeek-V3 reports (85–90% second-token acceptance, 1.8× TPS). Raise k: each extra depth adds only a₁⋯ak, which shrinks fast when acceptance decays with depth (δ < 1 — deeper MTP heads see their own drafted inputs, not the truth). Raise c (a heavier draft) and the best k drops. This is why MiMo keeps its MTP blocks light (0.33B, dense FFN, SWA) and why Nemotron shares one head across depths. 왼쪽은 draft 토큰이 적어도 j개 수락될 확률이다(막대는 곱해진다. 깊이 j의 draft는 1…j−1이 모두 수락돼야 의미가 있다). 오른쪽은 현재 a₁, δ, c에서 k = 1…8의 기대 속도 향상이다. k = 1, a₁ = 0.85–0.9로 두면 step당 1.85–1.9 토큰, DeepSeek-V3가 보고한 영역이다(두 번째 토큰 수락률 85–90%, TPS 1.8배). k를 올리면 깊이 하나가 a₁⋯ak만 더하는데, 수락률이 깊이에 따라 줄면(δ < 1 — 깊은 MTP head는 정답이 아니라 자기가 만든 draft를 입력으로 본다) 이 값이 빨리 작아진다. c를 올리면(무거운 draft) 최적 k가 줄어든다. MiMo가 MTP 블록을 가볍게(0.33B, dense FFN, SWA) 두고 Nemotron이 깊이마다 head 하나를 공유하는 이유다.
NumPy Speculative sampling: acceptance = Σ min(p, q), the output is exactly p, and expected tokens per step
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.

확인 문제Check yourself

Why does DeepSeek-V3's sequential MTP module make a better drafter than Gloeckle-style parallel heads, at equal size?

A parallel head predicts p(xt+k∣x≤t)p(x_{t+k}\mid x_{\le t}), averaging over all possible xt+1,…,xt+k−1x_{t+1},\dots,x_{t+k-1}; when the main model has sampled a specific xt+1x_{t+1}, that marginal is a worse proposal than p(xt+2∣x≤t+1)p(x_{t+2}\mid x_{\le t+1}), so min⁡(p,q)\min(p,q) — the acceptance — is lower. The sequential module takes Emb⁡(ti+k)\operatorname{Emb}(t_{i+k}) as input and keeps the causal chain. V3 actually shares one output head across depths, and uses a small λ.

PyTorch PyTorch: a DeepSeek-V3-style sequential MTP module and loss (teacher forcing, shared embedding and head) 로컬에서 실행run locally (pip install torch)
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 init
 

The input end: how big should the vocabulary be?

The vocabulary VV trades three costs against two benefits.

  • Parameters: VdVd for the input embedding, another VdVd for an untied output head.
  • FLOPs per token: the LM head is a d×Vd\times V matmul, 2dV2dV FLOPs — against roughly 2Nactive2N_{\text{active}} for the rest of the forward pass.
  • Activation memory: the logits tensor is T×VT\times V. One 8K-token sequence with V=248V=248K 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 2.3×10212.3\times10^{21} 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).

NumPy speculative sampling: 수락률 = Σ min(p, q), 출력은 정확히 p, 그리고 step당 기대 토큰
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을 만들 때 중요한 성질이다.

확인 문제Check yourself

같은 크기라면 DeepSeek-V3의 순차 MTP 모듈이 Gloeckle식 병렬 head보다 나은 drafter인 이유는?

병렬 head는 가능한 모든 xt+1,…,xt+k−1x_{t+1},\dots,x_{t+k-1}에 대해 평균한 p(xt+k∣x≤t)p(x_{t+k}\mid x_{\le t})를 예측한다. 본 모델이 특정 xt+1x_{t+1}을 샘플했다면 그 주변분포는 p(xt+2∣x≤t+1)p(x_{t+2}\mid x_{\le t+1})보다 나쁜 제안이고, 따라서 min⁡(p,q)\min(p,q), 즉 수락률이 낮다. 순차 모듈은 Emb⁡(ti+k)\operatorname{Emb}(t_{i+k})를 입력으로 받아 causal 사슬을 유지한다. V3는 실제로 출력 head 하나를 깊이 사이에 공유하고, 작은 λ를 쓴다.

PyTorch PyTorch: DeepSeek-V3식 순차 MTP 모듈과 손실 (teacher forcing, 공유 임베딩과 head) 로컬에서 실행run locally (pip install torch)
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
 

입력 쪽: 어휘는 얼마나 커야 하나

어휘 크기 VV는 비용 셋과 이득 둘을 맞바꾼다.

  • 파라미터: 입력 임베딩에 VdVd, 묶지 않은 출력 head에 또 VdVd.
  • 토큰당 FLOPs: LM head는 d×Vd\times V 행렬곱, 2dV2dV FLOPs다. forward의 나머지는 대략 2Nactive2N_{\text{active}}다.
  • activation 메모리: logits 텐서는 T×VT\times V다. V=248V=248K에서 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 이상이었어야 한다고 결론지었다. 2.3×10212.3\times10^{21} 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 또는 보고서).

임베딩+head 파라미터embedding + head params – 토큰당 head FLOPs 비중head share of FLOPs/token – FP32 logits, 8K 시퀀스FP32 logits, one 8K sequence –
For a fixed model shape (hidden size d, active parameters N), the curves show how the vocabulary V sets three costs: the input embedding and output head as a share of the (active) parameters N (solid; untied counts both), the share of per-token forward FLOPs spent in the LM head, 2dV / 2N (dashed), and, in the readout, the FP32 logits tensor of one 8K-token sequence. Dots mark real vocabularies (Llama 3 128,256; DeepSeek-V3 129,280; Qwen3 151,936; gpt-oss 201,088; Qwen3.5/3.8 248,320; Gemma 2 256,128). Switch to the 0.6B shape: at V = 152K the embedding alone is a quarter of the model and an untied head doubles that, which is why small models tie their embeddings. Switch to the 37B-active shape: the same vocabulary is 2.5% of the compute — large models can afford large vocabularies, and the vocabulary scaling-law paper argues they should have them. 모델 모양(hidden d, 활성 파라미터 N)을 고정하면 어휘 크기 V가 세 비용을 정한다. (활성) 파라미터 N 대비 입력 임베딩과 출력 head의 비중(실선; 묶지 않으면 둘 다 센다), 토큰당 forward FLOPs 중 LM head의 몫 2dV / 2N(점선), 그리고 아래 숫자의 8K 토큰 시퀀스 하나의 FP32 logits 텐서다. 점은 실제 어휘 크기다(Llama 3 128,256; DeepSeek-V3 129,280; Qwen3 151,936; gpt-oss 201,088; Qwen3.5/3.8 248,320; Gemma 2 256,128). 0.6B 모양으로 바꾸면 V = 152K에서 임베딩만으로 모델의 4분의 1이고 head를 따로 두면 그 두 배다. 작은 모델이 임베딩을 묶는 이유다. 37B 활성 모양으로 바꾸면 같은 어휘가 연산의 2.5%다. 큰 모델은 큰 어휘를 감당할 수 있고, 어휘 scaling law 논문은 그래야 한다고 주장한다.
NumPy Vocabulary arithmetic for real configs, the price of not tying, and a chunked log-sum-exp
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, logitt,v=⟨h^t,Ev⟩\text{logit}_{t,v}=\langle\hat h_t,E_v\rangle (GPT from scratch). It saves VdVd 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:

  1. Compress token ids to canonical ids (NFKC, lower-casing — about 23% fewer ids for a 128K tokenizer) and form the suffix n-grams gt,n=(xt−n+1′,…,xt′)g_{t,n}=(x'_{t-n+1},\dots,x'_t) for n=2,3n=2,3.
  2. Hash each n-gram with KK independent heads into prime-sized tables, et,n,k=En,k[φn,k(gt,n)]e_{t,n,k}=E_{n,k}[\varphi_{n,k}(g_{t,n})], and concatenate everything into ete_t.
  3. Gate by context: kt=WKetk_t=W_Ke_t, vt=WVetv_t=W_Ve_t, αt=σ(RMSNorm⁡(ht)⊤RMSNorm⁡(kt)/d)\alpha_t=\sigma\big(\operatorname{RMSNorm}(h_t)^\top\operatorname{RMSNorm}(k_t)/\sqrt d\big), then a short causal convolution, and add αtvt\alpha_tv_t (convolved) to the residual stream. When the retrieved memory contradicts the context, αt→0\alpha_t\to0.

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 MM rows holding UU distinct n-grams collides a given n-gram in one head with probability about 1−e−U/M1-e^{-U/M}. With KK heads (each of M/KM/K rows at a fixed budget) two n-grams are confused only if they collide in all heads, since the retrieved rows are concatenated:

NumPy Hashed n-gram tables: one big table vs several hash heads at a fixed row budget
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 collide
 

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

확인 문제Check yourself

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 DD 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 min⁡(1,p/q)\min(1,p/q) and preserves pp exactly; acceptance is 1−TV⁡(p,q)1-\operatorname{TV}(p,q) and a step yields 1+∑j∏i≤jai1+\sum_j\prod_{i\le j}a_i 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 (VdVd, ×2 untied), head FLOPs (2dV2dV) and a T×VT\times V logits tensor; it buys compression and multilingual coverage. Optimal VV grows with model size, and frontier vocabularies are now 128K–256K.
  • Tie embeddings when VdVd 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%).
NumPy 실제 config의 어휘 계산, 묶지 않는 비용, chunk 단위 log-sum-exp
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를 입력 임베딩으로 둔다. logitt,v=⟨h^t,Ev⟩\text{logit}_{t,v}=\langle\hat h_t,E_v\rangle(GPT 바닥부터). VdVd 파라미터를 아끼고, 드문 토큰의 출력 행이 입력 쪽 학습의 덕을 본다. 위 표가 그것이 언제 중요한지 말해 준다. 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 임베딩을 큰 규모로 되살린다.

  1. 토큰 id를 정규 id로 압축하고(NFKC, 소문자화 — 128K 토크나이저에서 id가 약 23% 줄어든다) n=2,3n=2,3의 접미 n-gram gt,n=(xt−n+1′,…,xt′)g_{t,n}=(x'_{t-n+1},\dots,x'_t)을 만든다.
  2. n-gram마다 독립 hash head KK개로 소수 크기의 테이블을 찾고 et,n,k=En,k[φn,k(gt,n)]e_{t,n,k}=E_{n,k}[\varphi_{n,k}(g_{t,n})], 전부 이어 붙여 ete_t를 만든다.
  3. 문맥으로 gate한다. kt=WKetk_t=W_Ke_t, vt=WVetv_t=W_Ve_t, αt=σ(RMSNorm⁡(ht)⊤RMSNorm⁡(kt)/d)\alpha_t=\sigma\big(\operatorname{RMSNorm}(h_t)^\top\operatorname{RMSNorm}(k_t)/\sqrt d\big), 짧은 causal convolution을 거쳐 αtvt\alpha_tv_t를 residual stream에 더한다. 찾아온 기억이 문맥과 어긋나면 αt→0\alpha_t\to0이다.

두 성질이 이것을 요령이 아니라 아키텍처의 축으로 만든다. 주소가 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가 여러 개인가? MM행 테이블에 서로 다른 n-gram UU개가 들어 있으면 주어진 n-gram이 head 하나에서 충돌할 확률은 약 1−e−U/M1-e^{-U/M}이다. head가 KK개(예산 고정이면 각 M/KM/K행)이면 찾아온 행을 이어 붙이므로 두 n-gram은 모든 head에서 충돌할 때만 혼동된다.

NumPy 해시 n-gram 테이블: 고정된 행 예산에서 큰 테이블 하나 대 hash 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가 제 몫을 하는 곳이다.

확인 문제Check yourself

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는 위치마다 목표를 DD개 더한다. 병렬 head는 주변분포를 예측하고, DeepSeek-V3의 순차 모듈은 실제 중간 토큰에 조건을 걸어 causal 사슬을 유지하며 추론 때 조건부 drafter를 겸한다.
  • speculative sampling은 min⁡(1,p/q)\min(1,p/q)로 수락하고 pp를 정확히 보존한다. 수락률은 1−TV⁡(p,q)1-\operatorname{TV}(p,q), step 하나는 1+∑j∏i≤jai1+\sum_j\prod_{i\le j}a_i 토큰을 낸다. 깊이별 수락률 감소와 draft 비용이 최적 draft 길이를 정한다. 그래서 MTP 블록은 가볍고(MiMo) head는 재귀로 공유된다(Nemotron).
  • 어휘 크기는 임베딩 파라미터(VdVd, 묶지 않으면 ×2), head FLOPs(2dV2dV), T×VT\times V logits 텐서를 정하고, 압축과 다국어 커버리지를 산다. 최적 VV는 모델 크기와 함께 커지고, 프런티어 어휘는 이제 128K–256K다.
  • VdVd가 모델의 큰 비중일 때(10억 미만 모델) 임베딩을 묶고, 규모가 크면 푼다.
  • 해시 n-gram 테이블(Engram, Qwen3.8)은 FLOPs 없이 파라미터를 더한다. 주소가 forward 전에 정해지므로 prefetch와 함께 host 메모리에 둔다. hash head 여럿이 충돌을 드물게 만들고, 이득은 실재하지만 포화되며, 파라미터 예산이 고정되면 MoE expert와 경쟁한다(약 20–25%에서 U자형 최적).

더 읽을거리Further reading