Track VIII · Inference & Optimisation · 06/09

Speculative decoding 심화Speculative decoding in depth

수락 길이를 위치별 조건부 수락률로 일반화하고, 트리 draft의 기대 길이가 노드 값의 합이며 최적 트리가 상위 m개 노드라는 것을 유도한다. 트리 검증이 target 분포를 정확히 보존하는 재귀적 rejection을 증명하고 NumPy로 정확히 확인한 뒤, Medusa·EAGLE-1/2/3·MTP drafter를 비교하고 배치가 커지면 왜 speculation이 손해가 되는지 roofline으로 계산한다.Generalise acceptance length to per-position conditional acceptance rates, derive that a draft tree's expected length is the sum of its node values and that the best tree is the top-m nodes, prove that recursive rejection on a tree preserves the target distribution exactly (and check it exactly in NumPy), compare Medusa, EAGLE-1/2/3 and MTP drafters, and compute with a roofline why speculation turns into a loss as the batch grows.

The inference lesson derived the core of speculative decoding: a draft qq proposes, the target pp accepts with min⁡(1,p/q)\min(1, p/q) and resamples from (p−q)+(p-q)_+ on rejection, the output follows pp exactly, and with an i.i.d. acceptance probability α\alpha a chain of γ\gamma drafts yields 1−αγ+11−α\frac{1-\alpha^{\gamma+1}}{1-\alpha} tokens per target pass. That is where production systems start. Every serious deployment today (EAGLE in SGLang and vLLM, MTP heads in DeepSeek, MiMo, Qwen and Nemotron) verifies trees, not chains, uses drafters that read the target’s own hidden states, and turns speculation off or down when the batch is large. This lesson derives why.

The plan: (1) acceptance length when acceptance rates differ by position; (2) why a tree beats a chain and what the optimal tree is; (3) the proof that tree verification is still lossless when sampling, checked exactly in NumPy; (4) where drafts come from (Medusa, EAGLE-1/2/3, MTP); (5) when speculation stops paying as the batch grows.

Acceptance length, position by position

Let aia_i be the probability that draft ii is accepted given drafts 1..i−11..i-1 were accepted. The step emits at least i+1i+1 tokens exactly when the first ii drafts are accepted, so with LL the tokens emitted per target pass,

P(L≥i+1)=∏j=1iaj,E[L]=∑i≥0P(L≥i+1)=1+∑i=1γ∏j=1iaj.P(L \ge i+1) = \prod_{j=1}^{i} a_j, \qquad \mathbb E[L] = \sum_{i \ge 0} P(L \ge i+1) = 1 + \sum_{i=1}^{\gamma} \prod_{j=1}^{i} a_j .

The leading 1 is the token the target always contributes (the resample on rejection, or the bonus token after a full accept). The i.i.d. case aj=αa_j = \alpha gives back the familiar geometric sum. In practice the aja_j fall with depth: a drafter that predicts several steps ahead sees less and less of the true prefix. MiMo-7B reports about 90% for its first MTP layer and above 75% for its third on AIME24, which by this formula is 1+0.9+0.9⋅0.8+0.9⋅0.8⋅0.75≈3.21 + 0.9 + 0.9\cdot0.8 + 0.9\cdot0.8\cdot0.75 \approx 3.2 tokens per pass (with the middle layer read as 0.8; see the MiMo-7B review).

What does “acceptance” mean? Under greedy verification (temperature 0) a draft is accepted iff it equals the target’s argmax, so aa is a top-1 agreement rate. Under sampling a single draft is accepted with probability ∑xmin⁡(p(x),q(x))=1−TV(p,q)\sum_x \min(p(x), q(x)) = 1 - \mathrm{TV}(p,q). In both cases a draft’s job is to put mass where the target does.

From chains to trees

A chain spends its whole budget on one guess per depth. If the guess at depth 1 is wrong, everything behind it is wasted. A tree instead hedges: at depth 1 it might offer the draft’s top-2 tokens, and continue only the most promising branches. The target checks the whole tree in one forward pass: flatten the mm draft tokens into a sequence, give each the position id of its depth, and use an attention mask in which every node attends to the prefix and to its own ancestors only (tree attention, introduced by SpecInfer and Medusa). Sibling branches never see each other, so each node’s logits are exactly what plain decoding along that branch would produce.

Expected length of a tree. Let AvA_v be the event that draft node vv ends up on the accepted path. The accepted nodes form a single root-to-node path, so the number of accepted drafts is ∑v1[Av]\sum_v \mathbf 1[A_v], and by linearity of expectation

E[L]=1+∑v∈TP(Av).\mathbb E[L] = 1 + \sum_{v \in T} P(A_v).

No independence is needed for this. Under greedy verification, write πr\pi_r for the probability that the target’s next token is the draft’s rank-rr candidate. If vv is reached from the root by ranks (r1,…,rd)(r_1, \dots, r_d), then P(Av)=∏kπrkP(A_v) = \prod_k \pi_{r_k}: call it the value V(v)V(v).

The optimal tree is the top-mm nodes by value. We want the set TT of mm nodes, closed under taking parents, that maximises ∑v∈TV(v)\sum_{v \in T} V(v). A child’s value is its parent’s times a probability ≤1\le 1, so V(child)≤V(parent)V(\text{child}) \le V(\text{parent}). Take the mm largest values in the infinite tree (break ties towards shallower nodes): if a node is in the set, its parent has at least the same value and is in it too, so the set is a valid tree, and no valid tree can have a larger sum. This is exactly the argument EAGLE-2 uses for its reranking step (“a node’s value is always less than or equal to its parent’s”).

With πr=a(1−a)r−1\pi_r = a(1-a)^{r-1} the chain’s values are a,a2,a3,…a, a^2, a^3, \dots and its E[L]\mathbb E[L] saturates at 1/(1−a)1/(1-a). The tree can keep adding mass from rank-2 and rank-3 siblings near the root, whose values (a(1−a)a(1-a), a2(1−a)a^2(1-a), …) quickly exceed the chain’s deep nodes. That is why trees win once the budget exceeds a handful of tokens.

Static versus dynamic trees. The value of a node depends on the context: after “The capital of France is” the draft’s top-1 is almost surely right; in the middle of a creative sentence it is not. A static tree, tuned once for the average context, over-invests depth in hard contexts and under-invests in easy ones. EAGLE-2’s observation is that the draft’s own confidence is a good, cheap estimate of acceptance: on Vicuna-7B/Alpaca, tokens with confidence below 0.05 are accepted about 4% of the time and those above 0.95 about 98% of the time. So it builds the tree per context: expand the top-10 nodes by (estimated) value at each depth, up to depth 6, then rerank all drafted tokens by value and keep the top 60 (for 7B/8B targets; 50 for 13B, 48 for 70B). The figure below shows what that buys.

추론 레슨에서 speculative decoding의 핵심을 유도했다. draft qq가 제안하고, target pp가 min⁡(1,p/q)\min(1, p/q)로 수락하고 거절되면 (p−q)+(p-q)_+에서 다시 뽑으면 출력이 정확히 pp를 따르고, 수락 확률이 위치마다 독립으로 α\alpha이면 길이 γ\gamma인 chain이 target forward 한 번에 1−αγ+11−α\frac{1-\alpha^{\gamma+1}}{1-\alpha}개 토큰을 낸다. 실제 시스템은 거기서 출발한다. 오늘날 진지한 배포는 모두(SGLang·vLLM의 EAGLE, DeepSeek·MiMo·Qwen·Nemotron의 MTP head) chain이 아니라 트리를 검증하고, target 자신의 hidden state를 읽는 drafter를 쓰며, 배치가 크면 speculation을 줄이거나 끈다. 이 레슨은 그 이유를 유도한다.

순서는 이렇다. (1) 위치마다 수락률이 다를 때의 수락 길이, (2) 트리가 chain을 이기는 이유와 최적 트리, (3) 샘플링에서도 트리 검증이 무손실이라는 증명과 NumPy로 정확한 확인, (4) draft의 출처(Medusa, EAGLE-1/2/3, MTP), (5) 배치가 커질 때 speculation이 이득이 아니게 되는 지점.

위치별 수락 길이

aia_i를 draft 1..i−11..i-1이 수락되었다는 조건에서 draft ii가 수락될 확률이라 하자. 처음 ii개가 모두 수락될 때 정확히 그때 step이 i+1i+1개 이상의 토큰을 내므로, target forward 한 번에 나오는 토큰 수를 LL이라 하면

P(L≥i+1)=∏j=1iaj,E[L]=∑i≥0P(L≥i+1)=1+∑i=1γ∏j=1iaj.P(L \ge i+1) = \prod_{j=1}^{i} a_j, \qquad \mathbb E[L] = \sum_{i \ge 0} P(L \ge i+1) = 1 + \sum_{i=1}^{\gamma} \prod_{j=1}^{i} a_j .

앞의 1은 target이 항상 보태는 토큰이다(거절 시 재샘플, 또는 모두 수락 시 보너스 토큰). aj=αa_j = \alpha로 두면 익숙한 등비합이 돌아온다. 실제로는 aja_j가 깊이에 따라 떨어진다. 여러 칸 앞을 예측하는 drafter는 진짜 prefix를 점점 덜 본다. MiMo-7B는 AIME24에서 첫 MTP layer의 수락률이 약 90%, 세 번째 layer도 75% 이상이라고 보고하는데, 이 식에 넣으면(가운데 layer를 0.8로 읽어) 1+0.9+0.9⋅0.8+0.9⋅0.8⋅0.75≈3.21 + 0.9 + 0.9\cdot0.8 + 0.9\cdot0.8\cdot0.75 \approx 3.2개다(MiMo-7B 리뷰 참고).

“수락”이란 무엇인가. greedy 검증(temperature 0)에서는 draft가 target의 argmax와 같을 때만 수락되므로 aa는 top-1 일치율이다. 샘플링에서는 draft 하나가 ∑xmin⁡(p(x),q(x))=1−TV(p,q)\sum_x \min(p(x), q(x)) = 1 - \mathrm{TV}(p,q)의 확률로 수락된다. 어느 쪽이든 draft의 일은 target이 확률을 두는 곳에 확률을 두는 것이다.

chain에서 트리로

chain은 깊이마다 추측 하나에 예산을 다 쓴다. 깊이 1의 추측이 틀리면 그 뒤는 모두 버려진다. 트리는 위험을 분산한다. 깊이 1에서 draft의 top-2 토큰을 함께 내놓고, 가능성 높은 가지만 이어 간다. target은 트리 전체를 forward 한 번에 확인한다. mm개 draft 토큰을 한 줄로 펴고, 각자에게 깊이에 해당하는 position id를 주고, 모든 노드가 prefix와 자기 조상만 보는 attention mask를 쓴다(SpecInfer와 Medusa가 도입한 tree attention). 형제 가지는 서로를 보지 않으므로 각 노드의 logit은 그 가지를 따라 평범하게 decode했을 때와 정확히 같다.

트리의 기대 길이. draft 노드 vv가 최종 수락 경로 위에 있는 사건을 AvA_v라 하자. 수락된 노드들은 루트에서 시작하는 경로 하나를 이루므로 수락된 draft 수는 ∑v1[Av]\sum_v \mathbf 1[A_v]이고, 기댓값의 선형성으로

E[L]=1+∑v∈TP(Av).\mathbb E[L] = 1 + \sum_{v \in T} P(A_v).

여기엔 독립 가정이 필요 없다. greedy 검증에서 target의 다음 토큰이 draft의 rank-rr 후보일 확률을 πr\pi_r이라 쓰자. vv가 루트에서 순위 (r1,…,rd)(r_1, \dots, r_d)를 따라 도달하는 노드면 P(Av)=∏kπrkP(A_v) = \prod_k \pi_{r_k}이고, 이를 노드의 값 V(v)V(v)라 부르자.

최적 트리는 값 상위 mm개 노드다. 부모를 포함하는 집합(즉 트리)이면서 크기가 mm인 TT 중 ∑v∈TV(v)\sum_{v \in T} V(v)가 최대인 것을 찾고 싶다. 자식의 값은 부모의 값에 1 이하의 확률을 곱한 것이므로 V(자식)≤V(부모)V(\text{자식}) \le V(\text{부모})다. 무한 트리에서 값이 큰 mm개를 고르면(동률은 얕은 쪽 우선), 어떤 노드가 뽑혔을 때 그 부모는 값이 같거나 크므로 함께 뽑혀 있다. 그러니 이 집합은 올바른 트리이고, 어떤 트리도 이보다 큰 합을 가질 수 없다. EAGLE-2가 reranking 단계에서 쓰는 논증이 정확히 이것이다(“노드의 값은 항상 부모의 값 이하”).

πr=a(1−a)r−1\pi_r = a(1-a)^{r-1}이면 chain의 값은 a,a2,a3,…a, a^2, a^3, \dots이고 E[L]\mathbb E[L]은 1/(1−a)1/(1-a)에서 포화한다. 트리는 루트 근처의 rank-2·rank-3 형제를 계속 더할 수 있고, 그 값(a(1−a)a(1-a), a2(1−a)a^2(1-a), …)은 금세 chain의 깊은 노드를 넘어선다. 예산이 몇 토큰을 넘으면 트리가 이기는 이유다.

정적 트리와 동적 트리. 노드의 값은 문맥에 따라 다르다. “프랑스의 수도는” 다음에는 draft의 top-1이 거의 확실히 맞고, 창작 문장 한가운데서는 그렇지 않다. 평균 문맥에 한 번 맞춘 정적 트리는 어려운 문맥에 깊이를 과하게, 쉬운 문맥에는 부족하게 쓴다. EAGLE-2의 관찰은 draft 자신의 confidence가 수락률의 좋고 싼 추정치라는 것이다. Vicuna-7B/Alpaca에서 confidence 0.05 미만 토큰은 약 4%, 0.95 초과 토큰은 약 98% 수락된다. 그래서 트리를 문맥마다 짠다. 깊이마다 (추정) 값 상위 10개 노드를 확장해 깊이 6까지 키운 뒤, draft한 모든 토큰을 값으로 다시 줄 세워 상위 60개를 남긴다(7B/8B target 기준, 13B는 50, 70B는 48). 아래 그림이 그것이 무엇을 사는지 보여 준다.

왼쪽 그림:Left panel:
Each verification forward pass checks m draft tokens. Right: expected tokens produced per pass, E[L] = 1 + Σv∈tree P(v accepted), averaged over contexts, for a chain (grey), the best static tree for the average context (blue) and a dynamic tree rebuilt per context (red, EAGLE-2 style). Raise m: the chain saturates at 1/(1−ā) while trees keep growing (logarithmically). Raise σ: contexts differ more, and the dynamic tree pulls ahead because easy contexts get deep, narrow trees and hard ones get wide, shallow ones (switch the left panel to see the shapes). Node colour = draft rank of that token: ■ 1 ■ 2 ■ 3 ■ 4+. 검증 forward 한 번이 draft 토큰 m개를 확인한다. 오른쪽: forward 한 번에 나오는 기대 토큰 수 E[L] = 1 + Σv∈tree P(v 수락)을 문맥에 대해 평균한 값. chain(회색), 평균 문맥에 최적인 정적 트리(파랑), 문맥마다 다시 짜는 동적 트리(빨강, EAGLE-2 방식). m을 올리면 chain은 1/(1−ā)에서 포화하고 트리는 (로그적으로) 계속 는다. σ를 올리면 문맥 간 차이가 커지고, 쉬운 문맥에는 깊고 좁은 트리, 어려운 문맥에는 넓고 얕은 트리를 주는 동적 트리가 앞선다(왼쪽 그림을 바꿔 모양을 보자). 노드 색 = 그 토큰의 draft 순위: ■ 1 ■ 2 ■ 3 ■ 4+.

Things to check in the figure:

  1. At m≤4m \le 4 all three curves coincide: with a small budget the best tree is a chain (the deep rank-1 nodes still have the largest values).
  2. Push mm to 64 at ā = 0.7: the chain is stuck near 1/(1−aˉ)≈3.31/(1-\bar a) \approx 3.3, the trees keep climbing, but only logarithmically. Doubling the verification budget buys roughly a constant number of extra tokens, which is why the budget is a cost knob (next sections), not something to max out.
  3. Raise σ with ā fixed: the static tree loses ground and the dynamic tree gains. Switch the left panel between the easy and hard context: the dynamic tree is a near-chain in the easy context and a bushy, shallow tree in the hard one, at the same mm.
  4. EAGLE-2 reports speed-ups of 3.05×–4.26×, 20–40% over EAGLE-1 with a static tree. The toy is not that experiment, but it shows where such a gain comes from.

Lossless verification on a tree

Greedy verification of a tree is trivially exact: walk from the root, at each node move to the child whose token equals the target’s argmax, stop when none does and emit the target’s argmax there. Sampling is subtler. A node has several candidate children; we must accept at most one and still emit exactly pp.

Recursive rejection. Let the children x1,…,xkx_1, \dots, x_k be drawn i.i.d. from qq. Keep a running target r←pr \leftarrow p. For i=1,…,ki = 1, \dots, k: accept xix_i with probability min⁡(1,r(xi)/q(xi))\min(1, r(x_i)/q(x_i)) and descend into its subtree; on rejection set r←(r−q)+/∥(r−q)+∥1r \leftarrow (r - q)_+ / \lVert (r-q)_+ \rVert_1 and try the next child. If every child is rejected, sample the output from the final rr. (This is the multi-candidate scheme used by SpecInfer-style tree verification.)

Claim: the emitted token has distribution pp, for any kk.

Proof by induction on kk. k=0k = 0: we sample from r=pr = p. Step: one round is ordinary speculative sampling with target rr and proposal qq. It emits xx via acceptance with probability min⁡(r(x),q(x))\min(r(x), q(x)), and rejects with total probability β=∑x(r(x)−q(x))+\beta = \sum_x (r(x) - q(x))_+. Conditioned on rejection, the remaining k−1k-1 children are still i.i.d. from qq (they were drawn independently of x1x_1), so by the induction hypothesis the rest of the procedure emits the residual r′=(r−q)+/βr' = (r-q)_+/\beta exactly. Total: min⁡(r,q)+β r′=min⁡(r,q)+(r−q)+=r\min(r, q) + \beta\, r' = \min(r,q) + (r-q)_+ = r. □\square

The same lemma applied at every node of the accepted path gives the joint distribution of the emitted sequence. Two variants matter in practice:

  • Deterministic children (the draft’s top-kk tokens, as EAGLE-2 and Medusa-style trees draft): treat each candidate as a point-mass proposal δx\delta_{x}. Then accept xx with probability r(x)r(x), and on rejection r←rr \leftarrow r with xx zeroed and renormalised: sampling without replacement. The same induction goes through, and the chance that some child is accepted is exactly p({x1..xk})p(\{x_1..x_k\}), the target mass the candidate set covers.
  • The tempting mistake: testing every child against the original pp instead of the running residual. With one child it is the correct rule; with two or more it over-emits tokens that appear among the candidates. The code below measures how wrong it is.

Medusa’s “typical acceptance”, which accepts a candidate whose target probability clears an entropy-dependent threshold, deliberately gives up exactness for a higher acceptance rate; the rejection schemes above are what “lossless” means.

NumPy Exact output distribution of one tree node, three verification rules
import numpy as np
from itertools import product

V = 6
p = np.array([0.40, 0.22, 0.15, 0.11, 0.07, 0.05])   # target p(. | node)
q = np.array([0.15, 0.35, 0.20, 0.10, 0.12, 0.08])   # draft  q(. | node)

def residual(r, q):
    z = np.maximum(r - q, 0.0)
    return z / z.sum() if z.sum() > 0 else z

def exact_iid(p, q, k):
    """k children drawn i.i.d. from q, tried in order; after each rejection the target becomes (r - q)+."""
    out, p_end = np.zeros(V), 0.0
    for kids in product(range(V), repeat=k):
        w = np.prod(q[list(kids)])                # probability of drafting exactly these children
        r, alive = p.copy(), 1.0
        for x in kids:
            acc = min(1.0, r[x] / q[x])
            out[x] += w * alive * acc
            alive *= 1.0 - acc
            r = residual(r, q)
        out += w * alive * r                       # every child rejected: sample what is left
        p_end += w * alive
    return out, 1 - p_end

def exact_topk(p, q, k):
    """k distinct children = the draft's top-k tokens (no sampling): the proposal is a point mass."""
    out, r, alive = np.zeros(V), p.copy(), 1.0
    for x in np.argsort(-q)[:k]:
        acc = r[x]                                 # min(1, r(x) / 1)
        out[x] += alive * acc
        alive *= 1.0 - acc
        r = r.copy(); r[x] = 0.0; r /= r.sum()
    return out + alive * r, 1 - alive

def exact_naive(p, q, k):
    """WRONG: each child is tested against the ORIGINAL p; fallback to (p - q)+."""
    out = np.zeros(V)
    for kids in product(range(V), repeat=k):
        w, alive = np.prod(q[list(kids)]), 1.0
        for x in kids:
            acc = min(1.0, p[x] / q[x])
            out[x] += w * alive * acc
            alive *= 1.0 - acc
        out += w * alive * residual(p, q)
    return out

tv = lambda a, b: 0.5 * np.abs(a - b).sum()
print(f"one draft token: alpha = sum min(p, q) = {np.minimum(p, q).sum():.3f}")
print(" k | TV(iid + residual, p) | TV(top-k, p) | TV(naive, p) | P(accept a child): iid / top-k")
for k in [1, 2, 3, 4]:
    (oi, ai), (ot, at), on = exact_iid(p, q, k), exact_topk(p, q, k), exact_naive(p, q, k)
    print(f" {k} | {tv(oi, p):9.1e}             | {tv(ot, p):9.1e}    | {tv(on, p):9.4f}    | {ai:.3f} / {at:.3f}")
 

These are exact enumerations, not samples: both correct rules agree with pp to rounding error (~1e-16), while the naive rule is off by 0.15–0.19 in total variation once there are two or more children. Note the last column: the draft’s top-1 here is token 1, which the target gives only 0.22, so deterministic top-kk candidates cover little target mass until k=3k = 3 includes token 0. Sampled candidates hedge better when the draft is miscalibrated; deterministic ones are better when the draft’s ranking is right, which is the regime trained drafters aim for.

Next, a whole tree on a context-dependent (bigram) target: build a random draft tree, verify it with the recursive rule, repeat, and compare the joint distribution of 3-token outputs with the exact one.

NumPy Tree speculative sampling on a bigram model: joint distribution check
import random
R = random.Random(0)
Vb = 3
P = np.array([[0.7, 0.2, 0.1], [0.1, 0.3, 0.6], [0.3, 0.3, 0.4]])    # target bigram p(x_t | x_{t-1})
Q = np.array([[0.3, 0.4, 0.3], [0.5, 0.25, 0.25], [0.2, 0.6, 0.2]])  # draft  bigram

def draw(dist):
    u, acc = R.random(), 0.0
    for i, w in enumerate(dist):
        acc += w
        if u < acc:
            return i
    return len(dist) - 1

def build_tree(ctx, widths):
    """Draft tree: widths[d] children per node at depth d, drawn i.i.d. from Q[parent]. Node = (token, kids)."""
    if not widths:
        return []
    return [(x, build_tree(x, widths[1:])) for x in (draw(Q[ctx]) for _ in range(widths[0]))]

def verify(ctx, kids, naive=False):
    """Walk the tree with recursive rejection sampling; return the emitted tokens (>= 1)."""
    out = []
    while True:
        r = P[ctx].copy()
        for x, sub in kids:
            pr = (P[ctx] if naive else r)[x]
            if R.random() < min(1.0, pr / Q[ctx][x]):
                out.append(x); ctx, kids = x, sub
                break
            if not naive:
                r = np.maximum(r - Q[ctx], 0.0); r = r / r.sum() if r.sum() > 0 else r
        else:                                   # no child accepted (or leaf reached)
            base = P[ctx] if not kids else (np.maximum(P[ctx] - Q[ctx], 0) if naive else r)
            out.append(draw(base / base.sum()))
            return out

def generate(n, widths, naive=False):
    seq, calls = [0], 0
    while len(seq) - 1 < n:
        seq += verify(seq[-1], build_tree(seq[-1], widths), naive)
        calls += 1
    return tuple(seq[1:n + 1]), calls

exact = {(a, b, c): P[0, a] * P[a, b] * P[b, c] for a in range(Vb) for b in range(Vb) for c in range(Vb)}
M = 6000
for widths, naive in [((2, 2, 1), False), ((3, 1, 1), False), ((2, 2, 1), True)]:
    emp, calls = {}, 0
    for _ in range(M):
        s, c = generate(3, widths, naive)
        emp[s] = emp.get(s, 0) + 1; calls += c
    tvd = 0.5 * sum(abs(emp.get(k, 0) / M - v) for k, v in exact.items())
    tag = "naive (no residual update)" if naive else "recursive rejection     "
    print(f"tree widths {widths} {tag}: TV of 3-token joint = {tvd:.3f}   target calls per 3 tokens = {calls / M:.2f}")
print(f"(sampling noise for {M} samples is about 0.02-0.03; plain decoding needs 3.00 calls)")
 

The two correct trees land at the noise floor while needing about half the target calls of plain decoding; the naive rule is fast too, but it samples from a different distribution (TV ≈ 0.16).

Finally, the acceptance-length formula for trees. Build the best tree of budget mm (top-mm values with a heap, exactly EAGLE-2’s reranking), and compare 1+∑vV(v)1 + \sum_{v} V(v) with a simulation of greedy verification.

NumPy Best tree of budget m: formula vs simulation, and chain vs tree
import heapq

def best_tree(rank_p, m, max_rank=8):
    """Greedy-verification model: the target's token is the draft's rank-r candidate with prob rank_p[r-1],
    independently at every depth. Node = tuple of ranks; value = product of rank_p along the path.
    Returns the m highest-value nodes (always a connected tree because a child never beats its parent)."""
    heap, tree = [(-rank_p[0], (1,))], []
    while heap and len(tree) < m:
        negv, path = heapq.heappop(heap)
        tree.append((path, -negv))
        heapq.heappush(heap, (negv * rank_p[0], path + (1,)))               # first child
        if path[-1] < max_rank:                                              # next sibling
            heapq.heappush(heap, (negv / rank_p[path[-1] - 1] * rank_p[path[-1]], path[:-1] + (path[-1] + 1,)))
    return tree

def simulate(tree, rank_p, n=8000, seed=1):
    rs = np.random.default_rng(seed)
    nodes = {path for path, _ in tree}
    cdf = np.cumsum(rank_p)
    total = 0
    for _ in range(n):
        path = ()
        while True:
            r = int(np.searchsorted(cdf, rs.random() * cdf[-1])) + 1           # target's token = draft rank r
            if path + (r,) in nodes:
                path = path + (r,)
            else:
                break
        total += len(path) + 1                                                 # accepted + 1 corrected/bonus
    return total / n

a = 0.7                                         # top-1 acceptance of the draft
rank_p = a * (1 - a) ** np.arange(8)            # P(target = rank r) = a (1-a)^(r-1)
print(f"top-1 acceptance a = {a}")
print("  m | chain E[L] | best tree E[L] (formula) | simulated | tree depth")
for m in [1, 4, 8, 16, 32, 64]:
    chain = 1 + sum(a ** i for i in range(1, m + 1))
    tree = best_tree(rank_p, m)
    formula = 1 + sum(v for _, v in tree)
    depth = max(len(p) for p, _ in tree)
    print(f" {m:2d} |   {chain:5.2f}    |         {formula:5.2f}            |   {simulate(tree, rank_p):5.2f}   |   {depth}")
 

For m≤4m \le 4 the best tree is the chain; at m=64m = 64 the tree gives 5.7 tokens per pass against the chain’s ceiling of 3.3, with a depth of only 11. The formula and the simulation agree to within sampling noise.

확인 문제Check yourself

Greedy verification, rank model π_r = a(1−a)^(r−1) with a = 0.6, budget m = 3 draft nodes. Which tree maximises E[L]?

Node values: depth-1 rank 1 = 0.6, its rank-1 child = 0.36, depth-1 rank 2 = 0.6⋅0.4=0.240.6 \cdot 0.4 = 0.24, the chain’s third node = 0.216, depth-1 rank 3 = 0.096. The top three values are 0.6, 0.36, 0.24, so E[L]=1+1.2=2.2\mathbb E[L] = 1 + 1.2 = 2.2, against 1+0.6+0.36+0.216=2.1761 + 0.6 + 0.36 + 0.216 = 2.176 for the chain and 1+0.6+0.24+0.096=1.9361 + 0.6 + 0.24 + 0.096 = 1.936 for the star.

그림에서 확인할 것:

  1. m≤4m \le 4에서는 세 곡선이 겹친다. 예산이 작으면 최적 트리가 곧 chain이다(깊은 rank-1 노드들의 값이 여전히 가장 크다).
  2. ā = 0.7에서 mm을 64까지 올리면 chain은 1/(1−aˉ)≈3.31/(1-\bar a) \approx 3.3 근처에서 멈추고 트리는 계속 오르지만 로그적으로만 오른다. 검증 예산을 두 배로 해도 대략 일정한 수의 토큰만 더 얻는다. 그래서 예산은 다음 절에서 보듯 비용 손잡이지, 최대로 올릴 대상이 아니다.
  3. ā를 고정하고 σ를 올리면 정적 트리는 밀리고 동적 트리는 앞선다. 왼쪽 그림을 쉬운 문맥과 어려운 문맥 사이에서 바꿔 보면, 같은 mm에서 동적 트리가 쉬운 문맥에서는 거의 chain이고 어려운 문맥에서는 덤불처럼 얕고 넓다.
  4. EAGLE-2는 3.05×–4.26×, 정적 트리를 쓰는 EAGLE-1보다 20–40% 빠른 속도를 보고한다. 이 장난감이 그 실험은 아니지만, 그런 이득이 어디서 오는지는 보여 준다.

트리 위의 무손실 검증

트리의 greedy 검증은 자명하게 정확하다. 루트에서 출발해 각 노드에서 target argmax와 같은 토큰의 자식으로 내려가고, 그런 자식이 없으면 거기서 target argmax를 내고 멈춘다. 샘플링은 더 미묘하다. 노드에는 후보 자식이 여럿 있는데, 그중 많아야 하나를 수락하면서도 정확히 pp를 내야 한다.

재귀적 rejection. 자식 x1,…,xkx_1, \dots, x_k를 qq에서 i.i.d.로 뽑았다고 하자. 진행 중인 target r←pr \leftarrow p를 둔다. i=1,…,ki = 1, \dots, k에 대해: xix_i를 min⁡(1,r(xi)/q(xi))\min(1, r(x_i)/q(x_i))의 확률로 수락하고 그 부분 트리로 내려간다. 거절되면 r←(r−q)+/∥(r−q)+∥1r \leftarrow (r - q)_+ / \lVert (r-q)_+ \rVert_1로 바꾸고 다음 자식을 시도한다. 모든 자식이 거절되면 마지막 rr에서 출력을 뽑는다(SpecInfer 계열 트리 검증이 쓰는 다중 후보 방식).

주장: 어떤 kk에서도 출력 토큰의 분포는 pp다.

kk에 대한 귀납법. k=0k = 0이면 r=pr = p에서 뽑는다. 귀납 단계: 한 라운드는 target rr, 제안 qq인 보통의 speculative sampling이다. 수락으로 xx를 낼 확률은 min⁡(r(x),q(x))\min(r(x), q(x))이고, 거절될 총확률은 β=∑x(r(x)−q(x))+\beta = \sum_x (r(x) - q(x))_+다. 거절을 조건으로 해도 남은 k−1k-1개 자식은 여전히 qq에서 i.i.d.이므로(x1x_1과 독립으로 뽑았다), 귀납 가정에 의해 나머지 절차는 잔차 r′=(r−q)+/βr' = (r-q)_+/\beta를 정확히 낸다. 합치면 min⁡(r,q)+β r′=min⁡(r,q)+(r−q)+=r\min(r, q) + \beta\, r' = \min(r,q) + (r-q)_+ = r. □\square

수락 경로의 모든 노드에서 같은 보조정리를 쓰면 출력 시퀀스의 결합 분포가 나온다. 실무에서 중요한 변형이 둘 있다.

  • 결정적 자식(EAGLE-2나 Medusa식 트리처럼 draft의 top-kk 토큰을 후보로 쓸 때): 각 후보를 점질량 제안 δx\delta_{x}로 다룬다. 그러면 xx를 확률 r(x)r(x)로 수락하고, 거절되면 rr에서 xx를 0으로 만들고 다시 정규화한다. 비복원 추출이다. 같은 귀납이 그대로 통하고, 어느 자식이든 수락될 확률은 정확히 p({x1..xk})p(\{x_1..x_k\}), 즉 후보 집합이 덮는 target 질량이다.
  • 빠지기 쉬운 실수: 진행 중인 잔차가 아니라 원래의 pp로 모든 자식을 시험하는 것. 자식이 하나면 올바른 규칙이지만 둘 이상이면 후보에 등장한 토큰을 과하게 낸다. 아래 코드가 얼마나 틀리는지 잰다.

Medusa의 “typical acceptance”는 target 확률이 엔트로피에 따른 문턱을 넘는 후보를 수락하는데, 더 높은 수락률을 위해 정확성을 일부러 포기한다. “무손실”이 뜻하는 것은 위의 rejection 방식들이다.

NumPy 트리 노드 하나의 정확한 출력 분포: 세 가지 검증 규칙
import numpy as np
from itertools import product

V = 6
p = np.array([0.40, 0.22, 0.15, 0.11, 0.07, 0.05])   # target p(. | 노드)
q = np.array([0.15, 0.35, 0.20, 0.10, 0.12, 0.08])   # draft  q(. | 노드)

def residual(r, q):
    z = np.maximum(r - q, 0.0)
    return z / z.sum() if z.sum() > 0 else z

def exact_iid(p, q, k):
    """q에서 i.i.d.로 뽑은 자식 k개를 차례로 시도; 거절될 때마다 target을 (r - q)+로 바꾼다."""
    out, p_end = np.zeros(V), 0.0
    for kids in product(range(V), repeat=k):
        w = np.prod(q[list(kids)])                # 정확히 이 자식들을 draft할 확률
        r, alive = p.copy(), 1.0
        for x in kids:
            acc = min(1.0, r[x] / q[x])
            out[x] += w * alive * acc
            alive *= 1.0 - acc
            r = residual(r, q)
        out += w * alive * r                       # 모두 거절: 남은 분포에서 뽑는다
        p_end += w * alive
    return out, 1 - p_end

def exact_topk(p, q, k):
    """자식 k개 = draft의 top-k 토큰(샘플링 없음): 제안이 점질량이다."""
    out, r, alive = np.zeros(V), p.copy(), 1.0
    for x in np.argsort(-q)[:k]:
        acc = r[x]                                 # min(1, r(x) / 1)
        out[x] += alive * acc
        alive *= 1.0 - acc
        r = r.copy(); r[x] = 0.0; r /= r.sum()
    return out + alive * r, 1 - alive

def exact_naive(p, q, k):
    """틀린 방식: 모든 자식을 '원래' p로 시험하고, 실패하면 (p - q)+에서 뽑는다."""
    out = np.zeros(V)
    for kids in product(range(V), repeat=k):
        w, alive = np.prod(q[list(kids)]), 1.0
        for x in kids:
            acc = min(1.0, p[x] / q[x])
            out[x] += w * alive * acc
            alive *= 1.0 - acc
        out += w * alive * residual(p, q)
    return out

tv = lambda a, b: 0.5 * np.abs(a - b).sum()
print(f"draft 토큰 하나: alpha = sum min(p, q) = {np.minimum(p, q).sum():.3f}")
print(" k | TV(iid + 잔차, p) | TV(top-k, p) | TV(naive, p) | 자식 하나라도 수락될 확률: iid / top-k")
for k in [1, 2, 3, 4]:
    (oi, ai), (ot, at), on = exact_iid(p, q, k), exact_topk(p, q, k), exact_naive(p, q, k)
    print(f" {k} | {tv(oi, p):9.1e}         | {tv(ot, p):9.1e}    | {tv(on, p):9.4f}    | {ai:.3f} / {at:.3f}")
 

표본이 아니라 정확한 열거다. 올바른 두 규칙은 반올림 오차(~1e-16) 안에서 pp와 같고, naive 규칙은 자식이 둘 이상이면 total variation으로 0.15–0.19만큼 틀린다. 마지막 열도 보자. 여기서 draft의 top-1은 target이 0.22밖에 주지 않는 토큰 1이라, 결정적 top-kk 후보는 k=3k = 3이 되어 토큰 0을 포함하기 전까지 target 질량을 별로 덮지 못한다. draft가 잘못 보정되어 있으면 샘플링한 후보가 위험을 더 잘 분산하고, draft의 순위가 맞으면 결정적 후보가 낫다. 학습된 drafter가 노리는 쪽은 후자다.

다음은 문맥에 따라 분포가 바뀌는(bigram) target에서 트리 전체를 다룬다. 무작위 draft 트리를 만들고 재귀 규칙으로 검증하기를 반복해, 3-토큰 출력의 결합 분포를 정확한 값과 비교한다.

NumPy bigram 모델에서의 트리 speculative sampling: 결합 분포 확인
import random
R = random.Random(0)
Vb = 3
P = np.array([[0.7, 0.2, 0.1], [0.1, 0.3, 0.6], [0.3, 0.3, 0.4]])    # target bigram p(x_t | x_{t-1})
Q = np.array([[0.3, 0.4, 0.3], [0.5, 0.25, 0.25], [0.2, 0.6, 0.2]])  # draft  bigram

def draw(dist):
    u, acc = R.random(), 0.0
    for i, w in enumerate(dist):
        acc += w
        if u < acc:
            return i
    return len(dist) - 1

def build_tree(ctx, widths):
    """draft 트리: 깊이 d의 노드마다 자식 widths[d]개를 Q[부모]에서 i.i.d.로 뽑는다. 노드 = (토큰, 자식들)."""
    if not widths:
        return []
    return [(x, build_tree(x, widths[1:])) for x in (draw(Q[ctx]) for _ in range(widths[0]))]

def verify(ctx, kids, naive=False):
    """재귀적 rejection sampling으로 트리를 따라 내려간다. 낸 토큰 목록(1개 이상)을 돌려준다."""
    out = []
    while True:
        r = P[ctx].copy()
        for x, sub in kids:
            pr = (P[ctx] if naive else r)[x]
            if R.random() < min(1.0, pr / Q[ctx][x]):
                out.append(x); ctx, kids = x, sub
                break
            if not naive:
                r = np.maximum(r - Q[ctx], 0.0); r = r / r.sum() if r.sum() > 0 else r
        else:                                   # 수락된 자식이 없음(또는 잎에 도달)
            base = P[ctx] if not kids else (np.maximum(P[ctx] - Q[ctx], 0) if naive else r)
            out.append(draw(base / base.sum()))
            return out

def generate(n, widths, naive=False):
    seq, calls = [0], 0
    while len(seq) - 1 < n:
        seq += verify(seq[-1], build_tree(seq[-1], widths), naive)
        calls += 1
    return tuple(seq[1:n + 1]), calls

exact = {(a, b, c): P[0, a] * P[a, b] * P[b, c] for a in range(Vb) for b in range(Vb) for c in range(Vb)}
M = 6000
for widths, naive in [((2, 2, 1), False), ((3, 1, 1), False), ((2, 2, 1), True)]:
    emp, calls = {}, 0
    for _ in range(M):
        s, c = generate(3, widths, naive)
        emp[s] = emp.get(s, 0) + 1; calls += c
    tvd = 0.5 * sum(abs(emp.get(k, 0) / M - v) for k, v in exact.items())
    tag = "naive (잔차 갱신 없음)" if naive else "재귀적 rejection     "
    print(f"트리 폭 {widths} {tag}: 3-토큰 결합 분포의 TV = {tvd:.3f}   3토큰당 target 호출 = {calls / M:.2f}")
print(f"(표본 {M}개의 샘플링 잡음은 약 0.02-0.03; 일반 decode는 3.00회 호출)")
 

올바른 두 트리는 잡음 수준에 떨어지면서 target 호출은 일반 decode의 절반 정도다. naive 규칙도 빠르지만 다른 분포(TV ≈ 0.16)에서 샘플링한다.

마지막으로 트리의 수락 길이 공식. 예산 mm의 최적 트리(heap으로 상위 mm개 값을 고르는 것, EAGLE-2의 reranking과 같다)를 만들고 1+∑vV(v)1 + \sum_{v} V(v)를 greedy 검증 시뮬레이션과 비교한다.

NumPy 예산 m의 최적 트리: 공식과 시뮬레이션, chain과 트리 비교
import heapq

def best_tree(rank_p, m, max_rank=8):
    """greedy 검증 모델: 깊이마다 독립으로 target 토큰이 draft의 rank-r 후보일 확률이 rank_p[r-1].
    노드 = 순위의 튜플, 값 = 경로를 따라 rank_p의 곱.
    값 상위 m개 노드를 돌려준다(자식은 부모를 넘지 못하므로 항상 연결된 트리)."""
    heap, tree = [(-rank_p[0], (1,))], []
    while heap and len(tree) < m:
        negv, path = heapq.heappop(heap)
        tree.append((path, -negv))
        heapq.heappush(heap, (negv * rank_p[0], path + (1,)))               # 첫 자식
        if path[-1] < max_rank:                                              # 다음 형제
            heapq.heappush(heap, (negv / rank_p[path[-1] - 1] * rank_p[path[-1]], path[:-1] + (path[-1] + 1,)))
    return tree

def simulate(tree, rank_p, n=8000, seed=1):
    rs = np.random.default_rng(seed)
    nodes = {path for path, _ in tree}
    cdf = np.cumsum(rank_p)
    total = 0
    for _ in range(n):
        path = ()
        while True:
            r = int(np.searchsorted(cdf, rs.random() * cdf[-1])) + 1           # target 토큰 = draft rank r
            if path + (r,) in nodes:
                path = path + (r,)
            else:
                break
        total += len(path) + 1                                                 # 수락 + 교정/보너스 1개
    return total / n

a = 0.7                                         # draft의 top-1 수락률
rank_p = a * (1 - a) ** np.arange(8)            # P(target = rank r) = a (1-a)^(r-1)
print(f"top-1 수락률 a = {a}")
print("  m | chain E[L] | 최적 트리 E[L] (공식) | 시뮬레이션 | 트리 깊이")
for m in [1, 4, 8, 16, 32, 64]:
    chain = 1 + sum(a ** i for i in range(1, m + 1))
    tree = best_tree(rank_p, m)
    formula = 1 + sum(v for _, v in tree)
    depth = max(len(p) for p, _ in tree)
    print(f" {m:2d} |   {chain:5.2f}    |        {formula:5.2f}         |   {simulate(tree, rank_p):5.2f}    |   {depth}")
 

m≤4m \le 4에서는 최적 트리가 chain이다. m=64m = 64에서 트리는 forward 한 번에 5.7개 토큰을 주고(chain의 상한은 3.3), 깊이는 11밖에 안 된다. 공식과 시뮬레이션은 샘플링 잡음 안에서 일치한다.

확인 문제Check yourself

greedy 검증, rank 모델 π_r = a(1−a)^(r−1), a = 0.6, 예산 m = draft 노드 3개. E[L]을 최대로 하는 트리는?

노드 값: 깊이 1의 rank 1 = 0.6, 그 rank-1 자식 = 0.36, 깊이 1의 rank 2 = 0.6⋅0.4=0.240.6 \cdot 0.4 = 0.24, chain의 세 번째 노드 = 0.216, 깊이 1의 rank 3 = 0.096. 상위 세 값이 0.6, 0.36, 0.24이므로 E[L]=1+1.2=2.2\mathbb E[L] = 1 + 1.2 = 2.2다. chain은 1+0.6+0.36+0.216=2.1761 + 0.6 + 0.36 + 0.216 = 2.176, 별 모양은 1+0.6+0.24+0.096=1.9361 + 0.6 + 0.24 + 0.096 = 1.936.

Where drafts come from

The value of a node is ∏πrk\prod \pi_{r_k}: a better drafter raises every value in the tree at once. The history of the field is a search for drafters that are both accurate and cheap, and the decisive move was to stop treating the drafter as a separate model.

DrafterWhat it readsHow it draftsReported (from each paper)
Separate small model (Leviathan; Chen)tokens onlyautoregressive, own KV cachemust share the tokeniser; cost cc is a full small model
Medusa headstarget’s last hidden state hth_thead kk predicts token t+k+1t{+}k{+}1 directly from hth_t; tree = combinations of each head’s top candidatesMedusa-1 (frozen backbone) > 2.2×; Medusa-2 (joint fine-tune) 2.3–3.6×
EAGLEsecond-to-top-layer features + the token sequence shifted by oneone decoder layer autoregresses at the feature level2.7–3.5× latency speed-up on LLaMA2-Chat 70B
EAGLE-2same drafterdynamic tree from draft confidence3.05–4.26×, 20–40% over EAGLE-1
EAGLE-3fused low, mid and high featurestoken-level loss only, training-time testup to 6.5×; τ = 6.13 vs 4.05 for EAGLE-2 (LLaMA-3.1-8B, MT-bench, T = 0)
MTP modules (DeepSeek-V3, MiMo, Qwen3-Next, Nemotron 3)main model’s hidden state + next token embeddingtrained with the model as an auxiliary loss; reused as drafterV3: 85–90% acceptance of the 2nd token, 1.8× TPS

Why Medusa is limited. Head kk predicts xt+k+1x_{t+k+1} from hth_t alone, without knowing which token was chosen at t+1,…,t+kt{+}1, \dots, t{+}k. It can only learn the marginal over those intermediate choices, and the Cartesian product of per-head top-kk lists contains many paths that are individually plausible but jointly incoherent. Accuracy decays quickly with kk.

EAGLE’s two fixes. (1) Autoregress on features rather than tokens: the second-to-top hidden state is a smoother target than a token, and the target’s own LM head turns the predicted feature into a distribution. (2) Feed the drafter the token sequence advanced by one step: the feature at t+1t{+}1 depends on which token was actually sampled at t+1t{+}1, and giving the drafter that token removes the “which branch am I on?” uncertainty that Medusa cannot resolve. The drafter is a single decoder layer, so cc is tiny.

EAGLE-3: train the drafter the way it is used. At inference the drafter’s step-2 input is its own step-1 output, not the target’s true feature. Training only on true features creates exposure bias, and acceptance decays with depth. EAGLE-3’s training-time test simulates inference during training: step 1 uses the target’s fused features; step 2 replaces the not-yet-available feature with the drafter’s own previous output, and so on, with the attention mask adjusted accordingly. Two more changes: the input is a concatenation of low, middle and high-layer features (3k→k3k \to k through an FC layer, kk the hidden size), and the feature-regression loss is dropped, because forcing the drafter’s output to match the top-layer feature “limits the expressiveness of the draft model”. With those, the authors report that more drafter training data keeps raising the speed-up, which EAGLE/EAGLE-2 did not show.

MTP as the drafter. The MTP lesson and the report reviews cover how these modules are trained. From the inference side, four facts matter:

  • They are free: trained with the model, shipped in the checkpoint, sharing the embedding and LM head. DeepSeek-V3’s single MTP module accepts the second token 85–90% of the time and gives 1.8× TPS (V3 review).
  • Depth needs training for it. MiMo-7B copies its one pre-trained MTP layer twice and fine-tunes the copies for inference drafting; Qwen3-Next trains MTP multi-step to keep training and inference consistent (its model card serves with 3 draft steps in SGLang and 2 in vLLM); Nemotron 3 Ultra shares one MTP head across its two blocks so it can be applied recursively (Qwen3-Next, Nemotron 3 Ultra). All three are the same idea as EAGLE-3’s training-time test: make step kk of training look like step kk of inference.
  • Acceptance is almost a function of the target’s predictability. MiMo-V2-Flash fits mean accept length yy to next-token cross-entropy xx as y=4(1−0.58 x0.58)y = 4(1 - 0.58\,x^{0.58}) (R2=0.995R^2 = 0.995, k=3k = 3); its three 0.33B MTP blocks give accept length up to 3.6 and up to 2.6× faster decoding (MiMo-V2).
  • Recurrent state complicates rollback. When a draft is rejected, attention just truncates the KV cache; a Mamba or linear-attention state is overwritten in place and has no past to return to. Nemotron 3 Ultra snapshots the SSM state at every draft step and reuses the mechanism for prefix caching (see the long-context lesson).

Speculation and batching: where it stops paying

Everything above counted tokens per target pass. What we pay for is time. Use the roofline model of a decode step that pushes nn tokens for each of BB sequences with context SS:

t(B,n)≈max⁡(W+BSkBW⏟read weights + KV, B n fF⏟compute),f≈2N+4LdS,t(B, n) \approx \max\Big(\underbrace{\tfrac{W + B S k}{\text{BW}}}_{\text{read weights + KV}},\ \underbrace{\tfrac{B\, n\, f}{F}}_{\text{compute}}\Big), \qquad f \approx 2N + 4 L d S,

with WW the weight bytes, kk the KV bytes per token, ff FLOPs per token. Note that the KV is read once per sequence per step, however many of that sequence’s tokens are verified. Plain decoding emits one token per sequence per t(B,1)t(B,1); speculation emits E[L]\mathbb E[L] per t(B,nv)+tdraftt(B, n_v) + t_{\text{draft}}, where nvn_v is the number of tokens each sequence sends through the verifier (γ+1\gamma + 1 for a chain, the tree size plus one for a tree). So

speed-up(B)=E[L]  t(B,1)t(B,nv)+tdraft.\text{speed-up}(B) = \frac{\mathbb E[L]\; t(B,1)}{t(B, n_v) + t_{\text{draft}}}.

Two regimes fall out.

  • Verification still memory-bound (Bnvf/F<(W+BSk)/BWB n_v f / F < (W + BSk)/\text{BW}): t(B,nv)=t(B,1)t(B, n_v) = t(B,1), and the speed-up is E[L]/(1+tdraft/t(B,1))\mathbb E[L] / (1 + t_{\text{draft}}/t(B,1)). This is the small-batch story of the inference lesson.
  • Verification compute-bound: its time grows with nvn_v. Once plain decoding is compute-bound too, the speed-up is E[L]/(nv+… )<1\mathbb E[L]/(n_v + \dots) < 1, because E[L]≤nv\mathbb E[L] \le n_v always. Every rejected draft token was paid for in FLOPs.

The crossover is where Bnvf/FB n_v f / F reaches the memory time. Ignoring KV, with bf16 weights (W=2NW = 2N, f≈2Nf \approx 2N) it sits at

B×≈F/BWnv=ridge pointnv,B^\times \approx \frac{F/\text{BW}}{n_v} = \frac{\text{ridge point}}{n_v},

about 295/5≈60295/5 \approx 60 for a γ=4\gamma = 4 chain on an H100-class accelerator, but 295/33≈9295/33 \approx 9 for a 32-node tree. Trees, which win on tokens per pass, are exactly what make speculation fragile under load. With KV included, the memory side grows as BSkB S k while the compute side grows as BnvfB n_v f, so if

S k  ≳  nvfF/BWS\, k \;\gtrsim\; \frac{n_v f}{F/\text{BW}}

the verification pass never becomes compute-bound at any batch (for a GQA-8B model, k=128k = 128 KiB and ridge ≈ 295, this is S≳410 nvS \gtrsim 410\, n_v tokens). That is the MagicDec observation: at long contexts decoding is dominated by KV reads that scale with both BB and SS, so speculation keeps paying at large batch (they report up to 2.51× for Llama-3.1-8B at batch 32–256, with a sparse-KV drafter).

draft는 어디서 오는가

노드의 값은 ∏πrk\prod \pi_{r_k}이므로, 더 나은 drafter는 트리의 모든 값을 한꺼번에 올린다. 이 분야의 역사는 정확하면서도 싼 drafter를 찾는 과정이었고, 결정적 한 수는 drafter를 별도 모델로 보지 않게 된 것이다.

Drafter무엇을 읽나어떻게 draft하나보고된 결과(각 논문)
별도의 작은 모델(Leviathan; Chen)토큰만자기회귀, 자체 KV cachetokenizer를 공유해야 함. 비용 cc는 작은 모델 전체
Medusa headtarget의 마지막 hidden state hth_thead kk가 hth_t에서 곧바로 토큰 t+k+1t{+}k{+}1을 예측. 트리 = head별 상위 후보의 조합Medusa-1(backbone 고정) 2.2× 이상, Medusa-2(공동 fine-tune) 2.3–3.6×
EAGLEsecond-to-top layer feature + 한 칸 앞선 토큰 시퀀스decoder layer 하나가 feature 수준에서 자기회귀LLaMA2-Chat 70B에서 latency 2.7–3.5×
EAGLE-2같은 drafterdraft confidence로 동적 트리3.05–4.26×, EAGLE-1보다 20–40%
EAGLE-3low·mid·high feature 융합토큰 수준 loss만, training-time test최대 6.5×. τ = 6.13 대 EAGLE-2의 4.05 (LLaMA-3.1-8B, MT-bench, T = 0)
MTP 모듈(DeepSeek-V3, MiMo, Qwen3-Next, Nemotron 3)본 모델의 hidden state + 다음 토큰 embedding보조 loss로 모델과 함께 학습, drafter로 재사용V3: 두 번째 토큰 수락률 85–90%, 1.8× TPS

Medusa의 한계. head kk는 t+1,…,t+kt{+}1, \dots, t{+}k에서 어떤 토큰이 골라졌는지 모른 채 hth_t만으로 xt+k+1x_{t+k+1}을 예측한다. 그러니 그 중간 선택들에 대한 주변 분포만 배울 수 있고, head별 top-kk 목록의 데카르트 곱에는 하나하나는 그럴듯하지만 합치면 앞뒤가 맞지 않는 경로가 많다. 정확도가 kk에 따라 빨리 떨어진다.

EAGLE의 두 가지 수정. (1) 토큰이 아니라 feature로 자기회귀한다. second-to-top hidden state는 토큰보다 매끄러운 예측 대상이고, target 자신의 LM head가 예측한 feature를 분포로 바꿔 준다. (2) drafter에게 한 칸 앞선 토큰 시퀀스를 넣는다. t+1t{+}1의 feature는 t+1t{+}1에서 실제로 뽑힌 토큰에 달려 있는데, 그 토큰을 drafter에게 주면 Medusa가 풀지 못하는 “지금 어느 가지에 있나?”의 불확실성이 사라진다. drafter는 decoder layer 하나라 cc가 아주 작다.

EAGLE-3: 쓰는 방식 그대로 drafter를 학습한다. 추론에서 drafter의 2단계 입력은 target의 참 feature가 아니라 자기 1단계 출력이다. 참 feature로만 학습하면 exposure bias가 생기고 수락률이 깊이에 따라 떨어진다. EAGLE-3의 training-time test는 학습 중에 추론을 흉내 낸다. 1단계는 target의 융합 feature를 쓰고, 2단계는 아직 없는 feature 자리에 drafter 자신의 이전 출력을 넣는 식으로 이어 가며 attention mask도 그에 맞게 바꾼다. 변화가 두 가지 더 있다. 입력이 low·middle·high layer feature의 연결이고(FC로 3k→k3k \to k, kk는 hidden size), feature 회귀 loss를 없앴다. drafter 출력을 top-layer feature에 맞추도록 강제하면 “draft 모델의 표현력을 제한”하기 때문이다. 그 결과 저자들은 drafter 학습 데이터를 늘릴수록 속도 향상이 계속 오른다고 보고하며, 이는 EAGLE/EAGLE-2에서는 보이지 않던 현상이다.

MTP를 drafter로. 이 모듈을 어떻게 학습하는지는 MTP 레슨과 보고서 리뷰가 다룬다. 추론 쪽에서 중요한 사실은 넷이다.

  • 공짜다. 모델과 함께 학습되어 체크포인트에 들어 있고, embedding과 LM head를 공유한다. DeepSeek-V3의 MTP 모듈 하나는 두 번째 토큰을 85–90% 수락시키고 1.8× TPS를 준다(V3 리뷰).
  • 깊이는 학습이 필요하다. MiMo-7B는 사전학습한 MTP layer 하나를 두 번 복사해 추론 drafting용으로 그 복사본만 fine-tune한다. Qwen3-Next는 학습과 추론을 맞추려고 MTP를 multi-step으로 학습한다(model card는 SGLang에서 draft 3단계, vLLM에서 2토큰으로 서빙한다). Nemotron 3 Ultra는 두 블록이 MTP head 하나를 공유해 재귀적으로 적용할 수 있게 한다(Qwen3-Next, Nemotron 3 Ultra). 셋 다 EAGLE-3의 training-time test와 같은 생각이다. 학습의 kk단계를 추론의 kk단계처럼 보이게 만든다.
  • 수락률은 거의 target의 예측 가능성의 함수다. MiMo-V2-Flash는 평균 수락 길이 yy를 다음 토큰 cross-entropy xx에 대해 y=4(1−0.58 x0.58)y = 4(1 - 0.58\,x^{0.58})로 맞춘다(R2=0.995R^2 = 0.995, k=3k = 3). 0.33B짜리 MTP 블록 셋으로 수락 길이 최대 3.6, decoding 최대 2.6× (MiMo-V2).
  • 순환 상태는 되돌리기를 어렵게 한다. draft가 거절되면 attention은 KV cache를 잘라 내면 그만이지만, Mamba나 linear attention의 상태는 제자리에서 덮어써져 돌아갈 과거가 없다. Nemotron 3 Ultra는 draft step마다 SSM 상태를 snapshot하고 같은 장치를 prefix caching에도 쓴다(long-context 레슨 참고).

speculation과 배칭: 언제 이득이 끝나는가

지금까지는 target forward 한 번당 토큰을 셌다. 우리가 지불하는 것은 시간이다. 문맥 SS인 시퀀스 BB개 각각에 대해 토큰 nn개를 미는 decode step의 roofline 모델을 쓰자.

t(B,n)≈max⁡(W+BSkBW⏟가중치 + KV 읽기, B n fF⏟연산),f≈2N+4LdS,t(B, n) \approx \max\Big(\underbrace{\tfrac{W + B S k}{\text{BW}}}_{\text{가중치 + KV 읽기}},\ \underbrace{\tfrac{B\, n\, f}{F}}_{\text{연산}}\Big), \qquad f \approx 2N + 4 L d S,

WW는 가중치 바이트, kk는 토큰당 KV 바이트, ff는 토큰당 FLOP이다. KV는 그 시퀀스의 토큰을 몇 개 검증하든 step마다 시퀀스당 한 번 읽힌다는 점에 주의하자. 일반 decode는 t(B,1)t(B,1)마다 시퀀스당 토큰 하나를 내고, speculation은 t(B,nv)+tdraftt(B, n_v) + t_{\text{draft}}마다 E[L]\mathbb E[L]개를 낸다. nvn_v는 시퀀스마다 검증기에 보내는 토큰 수다(chain은 γ+1\gamma + 1, 트리는 트리 크기 + 1). 따라서

속도 향상(B)=E[L]  t(B,1)t(B,nv)+tdraft.\text{속도 향상}(B) = \frac{\mathbb E[L]\; t(B,1)}{t(B, n_v) + t_{\text{draft}}}.

두 영역이 나온다.

  • 검증이 아직 memory-bound (Bnvf/F<(W+BSk)/BWB n_v f / F < (W + BSk)/\text{BW}): t(B,nv)=t(B,1)t(B, n_v) = t(B,1)이고 속도 향상은 E[L]/(1+tdraft/t(B,1))\mathbb E[L] / (1 + t_{\text{draft}}/t(B,1))이다. 추론 레슨의 작은 배치 이야기다.
  • 검증이 compute-bound: 시간이 nvn_v에 비례해 는다. 일반 decode까지 compute-bound가 되면 E[L]≤nv\mathbb E[L] \le n_v가 항상 성립하므로 속도 향상은 E[L]/(nv+… )<1\mathbb E[L]/(n_v + \dots) < 1이다. 거절된 draft 토큰 하나하나를 FLOP으로 치른 셈이다.

손익분기는 Bnvf/FB n_v f / F가 메모리 시간에 닿는 곳이다. KV를 무시하고 bf16 가중치(W=2NW = 2N, f≈2Nf \approx 2N)면

B×≈F/BWnv=ridge pointnv,B^\times \approx \frac{F/\text{BW}}{n_v} = \frac{\text{ridge point}}{n_v},

H100급 가속기에서 γ=4\gamma = 4 chain이면 약 295/5≈60295/5 \approx 60이지만 노드 32개 트리면 295/33≈9295/33 \approx 9다. forward당 토큰에서 이기게 해 주는 트리가, 부하가 걸리면 speculation을 취약하게 만드는 바로 그 원인이다. KV를 넣으면 메모리 쪽은 BSkB S k로, 연산 쪽은 BnvfB n_v f로 자라므로

S k  ≳  nvfF/BWS\, k \;\gtrsim\; \frac{n_v f}{F/\text{BW}}

이면 검증 forward는 어떤 배치에서도 compute-bound가 되지 않는다(GQA 8B 모델, k=128k = 128 KiB, ridge ≈ 295이면 S≳410 nvS \gtrsim 410\, n_v 토큰). 이것이 MagicDec의 관찰이다. 긴 문맥에서 decode는 BB와 SS 모두에 비례하는 KV 읽기가 지배하므로 큰 배치에서도 speculation이 이득이다(sparse-KV drafter로 Llama-3.1-8B, 배치 32–256에서 최대 2.51×).

An idealised roofline (assumed accelerator: 989 TFLOP/s bf16, 3.35 TB/s, 80 GB). Left: speed-up of speculative decoding over plain decoding versus batch size, for the chosen γ (red) and for the best γ at each batch (dashed). The grey region is where the KV cache no longer fits. Slide B up: while one verification pass is memory-bound, checking γ+1 tokens costs the same as checking one, so the speed-up ≈ E[L]; once B·(γ+1) tokens push the pass past the ridge point, its time grows with the token count and the speed-up falls below 1. Raise S: KV reads grow with B·S, the pass stays memory-bound up to larger batches, and speculation keeps paying (the MagicDec observation). Switch to tree (8 candidates per level, as in EAGLE-2-sized trees): E[L] rises, but every sequence now sends 8γ+1 tokens through the verifier, so the crossover moves left by roughly that factor. Right: what one step is made of at the selected B. Real kernels reach the compute roof earlier than this ideal model. 이상화한 roofline(가정한 가속기: bf16 989 TFLOP/s, 3.35 TB/s, 80 GB). 왼쪽: 배치 크기에 따른 speculative decoding의 속도 향상. 고른 γ(빨강)와 배치마다 최적 γ(점선). 회색은 KV cache가 메모리에 안 들어가는 영역이다. B를 올려 보면: 검증 forward가 memory-bound인 동안은 γ+1개를 검증하나 1개를 검증하나 시간이 같아 속도 향상 ≈ E[L]이다. B·(γ+1)개 토큰이 ridge point를 넘기면 forward 시간이 토큰 수에 비례해 늘고 속도 향상이 1 아래로 떨어진다. S를 올리면: KV 읽기가 B·S에 비례해 커져 더 큰 배치까지 memory-bound가 유지되고 speculation이 계속 이득이다(MagicDec의 관찰). tree로 바꾸면(EAGLE-2 규모처럼 단마다 후보 8개): E[L]은 오르지만 시퀀스마다 8γ+1개 토큰이 검증기를 지나므로 손익분기 배치가 대략 그 배수만큼 왼쪽으로 온다. 오른쪽: 고른 B에서 한 step의 구성. 실제 커널은 이 이상적 모델보다 일찍 연산 한계에 닿는다.

Things to check in the figure:

  1. Defaults (8B, chain γ = 4, S = 512): the speed-up holds near E[L]/(1+γc)\mathbb E[L]/(1+\gamma c) up to batch ~64, then falls; the dashed best-γ curve shows the right policy, shorter drafts as load grows.
  2. Switch the draft shape to tree: the small-batch speed-up rises, and the crossover moves to batch ~8–16. The right panel shows why: the amber compute bar of the verify pass outgrows the memory bars.
  3. Raise S to 32K and above: the teal KV-read bar dominates, the crossover moves right (or disappears) and memory, not speculation, becomes the batch limit (grey region).
  4. Switch to 70B: weight reads are larger, but so is per-token compute, and the ridge-point crossover barely moves. The ratio, not the size, decides.

This idealised model is optimistic (real decode kernels hit their compute roof well below peak), but the measured numbers have exactly this shape. EAGLE-3’s SGLang benchmark on H100 (LLaMA-3.1-8B, MT-bench) reports throughput relative to no speculation:

Batch248162432485664
EAGLE1.40×1.38×1.23×1.02×0.93×0.94×0.88×0.99×0.99×
EAGLE-31.81×1.82×1.62×1.48×1.39×1.32×1.38×1.34×1.38×

EAGLE turns into a loss from batch 24; EAGLE-3, with a longer acceptance length for the same verification cost, stays above 1. In the paper’s vLLM table EAGLE-3 decays from 1.75× at batch 2 to 1.01× at batch 56, and EAGLE drops below 1 from batch 32. (The paper’s text and table disagree in places on the peak batch sizes and the vLLM hardware; the table values are quoted here.)

확인 문제Check yourself

An 8B bf16 model on an accelerator with ridge point ≈ 300 FLOP/byte, short contexts. A chain with γ = 4 drafts is verified each step. At roughly what batch size does the verification pass become compute-bound?

Each sequence sends nv=γ+1=5n_v = \gamma + 1 = 5 tokens through the target. With W≈2NW \approx 2N bytes and f≈2Nf \approx 2N FLOPs per token, the pass is compute-bound once B⋅5⋅2N/F>2N/BWB \cdot 5 \cdot 2N / F > 2N / \text{BW}, i.e. B>(F/BW)/5≈60B > (F/\text{BW})/5 \approx 60. A 32-node tree (nv=33n_v = 33) would cross at about 9. Long contexts push the crossover up, because the KV reads add BSkBSk to the memory side.

A PyTorch sketch: tree attention mask and greedy acceptance

The mask is the whole trick of tree verification. The block below builds it from a parent array, checks that one masked attention pass gives each node exactly the output of causal attention along its own root-to-node path, and implements greedy acceptance.

PyTorch Tree attention mask, a correctness check, and greedy acceptance 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn.functional as F

def tree_mask(parents, prefix_len):
    """parents[i] = index of node i's parent in the flattened tree; node 0 is the root (the last
    committed token, not yet in the KV cache) with parent -1. Parents precede children.
    Returns a bool mask (m, prefix_len + m), True = may attend, and position ids (m,)."""
    m = len(parents)
    anc = torch.eye(m, dtype=torch.bool)                 # every node sees itself
    depth = torch.zeros(m, dtype=torch.long)
    for i, p in enumerate(parents):
        if p >= 0:
            anc[i] |= anc[p]                             # ... and all ancestors of its parent
            depth[i] = depth[p] + 1
    mask = torch.cat([torch.ones(m, prefix_len, dtype=torch.bool), anc], dim=1)
    return mask, prefix_len + depth                      # siblings share a position id

# check: one masked pass == per-path causal attention
torch.manual_seed(0)
P, d = 5, 16
parents = [-1, 0, 0, 1, 1, 2, 3]
m = len(parents)
mask, pos = tree_mask(parents, P)
q = torch.randn(1, 1, m, d)
k = torch.randn(1, 1, P + m, d)
v = torch.randn(1, 1, P + m, d)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)   # bool mask: True = take part
for i in range(m):
    path, j = [], i
    while j >= 0:
        path.append(P + j)
        j = parents[j]
    idx = list(range(P)) + path[::-1]
    ref = F.scaled_dot_product_attention(q[:, :, i:i + 1], k[:, :, idx], v[:, :, idx])
    assert torch.allclose(out[:, :, i:i + 1], ref, atol=1e-6)
print("tree mask matches path-wise causal attention; position ids:", pos.tolist())

def accept_greedy(tokens, parents, logits):
    """tokens (m,) flattened tree, logits (m, V) from ONE target pass over it.
    Returns the accepted node indices (root excluded) and the target's next token after them."""
    target = logits.argmax(-1).tolist()
    children = {i: [] for i in range(len(parents))}
    for i, p in enumerate(parents):
        if p >= 0:
            children[p].append(i)
    node, accepted = 0, []
    while True:
        nxt = next((c for c in children[node] if int(tokens[c]) == target[node]), None)
        if nxt is None:
            return accepted, target[node]
        accepted.append(nxt)
        node = nxt
# After acceptance: keep the KV of the root and the accepted nodes (positions P + [0] + accepted),
# compact them to be contiguous, drop the rest, and append the returned token as the next root.
 

Summary

  • Acceptance length in general: E[L]=1+∑i∏j≤iaj\mathbb E[L] = 1 + \sum_i \prod_{j \le i} a_j for a chain with per-depth conditional acceptance aja_j, and E[L]=1+∑v∈TP(Av)\mathbb E[L] = 1 + \sum_{v \in T} P(A_v) for any tree, by linearity of expectation.
  • Node values never exceed their parent’s, so the best tree for a budget mm is simply the top-mm nodes by value. EAGLE-2 estimates those values per context from calibrated draft confidence (dynamic trees).
  • Tree verification stays lossless under sampling with recursive rejection: after each rejected child the target becomes the residual (r−q)+(r - q)_+. For deterministic top-kk candidates this is sampling without replacement. Testing every child against the original pp is biased.
  • Drafters improved by reading the target’s features (EAGLE), being conditioned on the sampled token, and being trained the way they are used (EAGLE-3’s training-time test, multi-step and shared-weight MTP).
  • Speculation trades FLOPs for memory traffic. It pays while the verify pass is memory-bound, roughly B<ridge/nvB < \text{ridge}/n_v (much later at long context), and loses once decoding is compute-bound. Big trees make the crossover arrive sooner, so production systems shrink the draft as the batch grows.

그림에서 확인할 것:

  1. 기본값(8B, chain γ = 4, S = 512): 배치 ~64까지는 속도 향상이 E[L]/(1+γc)\mathbb E[L]/(1+\gamma c) 근처를 유지하다가 떨어진다. 점선(배치별 최적 γ)은 올바른 정책을 보여 준다. 부하가 커질수록 draft를 짧게.
  2. draft 모양을 tree로 바꾸면 작은 배치의 속도 향상은 오르지만 손익분기가 배치 ~8–16으로 온다. 오른쪽 그림이 이유를 보여 준다. 검증 forward의 주황 연산 막대가 메모리 막대를 넘어선다.
  3. S를 32K 이상으로 올리면 청록 KV 읽기 막대가 지배하고, 손익분기가 오른쪽으로 가거나 사라지며, 배치를 제한하는 것은 speculation이 아니라 메모리(회색 영역)가 된다.
  4. 70B로 바꾸면 가중치 읽기도 커지지만 토큰당 연산도 커져서 ridge 기준 손익분기는 거의 움직이지 않는다. 크기가 아니라 비율이 결정한다.

이 이상화된 모델은 낙관적이다(실제 decode 커널은 최고 성능보다 한참 아래에서 연산 한계에 닿는다). 그래도 측정값은 정확히 이 모양이다. EAGLE-3의 SGLang 벤치마크(H100, LLaMA-3.1-8B, MT-bench)가 보고한, speculation 없을 때 대비 처리량:

배치248162432485664
EAGLE1.40×1.38×1.23×1.02×0.93×0.94×0.88×0.99×0.99×
EAGLE-31.81×1.82×1.62×1.48×1.39×1.32×1.38×1.34×1.38×

EAGLE은 배치 24부터 손해가 되고, 같은 검증 비용에 더 긴 수락 길이를 얻는 EAGLE-3는 1 위에 머문다. 논문의 vLLM 표에서 EAGLE-3는 배치 2의 1.75×에서 배치 56의 1.01×로 줄고, EAGLE은 배치 32부터 1 아래로 내려간다(최고점 배치와 vLLM 하드웨어에 대해 논문 본문과 표가 어긋나는 곳이 있어 여기서는 표의 값을 인용했다).

확인 문제Check yourself

ridge point ≈ 300 FLOP/byte인 가속기에서 bf16 8B 모델, 짧은 문맥. step마다 γ = 4인 chain을 검증한다. 검증 forward가 compute-bound가 되는 배치는 대략?

시퀀스마다 nv=γ+1=5n_v = \gamma + 1 = 5개 토큰이 target을 지난다. W≈2NW \approx 2N바이트, 토큰당 f≈2Nf \approx 2N FLOP이면 B⋅5⋅2N/F>2N/BWB \cdot 5 \cdot 2N / F > 2N / \text{BW}, 즉 B>(F/BW)/5≈60B > (F/\text{BW})/5 \approx 60에서 compute-bound가 된다. 노드 32개 트리(nv=33n_v = 33)면 약 9에서 넘어간다. 긴 문맥은 KV 읽기가 메모리 쪽에 BSkBSk를 더하므로 손익분기를 위로 민다.

PyTorch 스케치: 트리 attention mask와 greedy 수락

트리 검증의 요령은 mask가 전부다. 아래 블록은 부모 배열에서 mask를 만들고, masked attention 한 번이 각 노드에 루트→노드 경로를 따른 causal attention과 정확히 같은 출력을 주는지 확인하고, greedy 수락을 구현한다.

PyTorch 트리 attention mask, 정확성 확인, greedy 수락 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn.functional as F

def tree_mask(parents, prefix_len):
    """parents[i] = 펼친 트리에서 노드 i의 부모 인덱스. 노드 0은 루트(마지막으로 확정된 토큰,
    아직 KV cache에 없음)이고 부모는 -1. 부모가 자식보다 앞에 온다.
    bool mask (m, prefix_len + m) (True = attend 가능)와 position id (m,)를 돌려준다."""
    m = len(parents)
    anc = torch.eye(m, dtype=torch.bool)                 # 모든 노드는 자기 자신을 보고
    depth = torch.zeros(m, dtype=torch.long)
    for i, p in enumerate(parents):
        if p >= 0:
            anc[i] |= anc[p]                             # ... 부모의 모든 조상도 본다
            depth[i] = depth[p] + 1
    mask = torch.cat([torch.ones(m, prefix_len, dtype=torch.bool), anc], dim=1)
    return mask, prefix_len + depth                      # 형제는 같은 position id

# 확인: masked attention 한 번 == 경로별 causal attention
torch.manual_seed(0)
P, d = 5, 16
parents = [-1, 0, 0, 1, 1, 2, 3]
m = len(parents)
mask, pos = tree_mask(parents, P)
q = torch.randn(1, 1, m, d)
k = torch.randn(1, 1, P + m, d)
v = torch.randn(1, 1, P + m, d)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)   # bool mask: True = 참여
for i in range(m):
    path, j = [], i
    while j >= 0:
        path.append(P + j)
        j = parents[j]
    idx = list(range(P)) + path[::-1]
    ref = F.scaled_dot_product_attention(q[:, :, i:i + 1], k[:, :, idx], v[:, :, idx])
    assert torch.allclose(out[:, :, i:i + 1], ref, atol=1e-6)
print("트리 mask가 경로별 causal attention과 일치; position id:", pos.tolist())

def accept_greedy(tokens, parents, logits):
    """tokens (m,) 펼친 트리, logits (m, V)는 그 위의 target forward 한 번에서 나온 값.
    수락된 노드 인덱스(루트 제외)와 그 뒤 target의 다음 토큰을 돌려준다."""
    target = logits.argmax(-1).tolist()
    children = {i: [] for i in range(len(parents))}
    for i, p in enumerate(parents):
        if p >= 0:
            children[p].append(i)
    node, accepted = 0, []
    while True:
        nxt = next((c for c in children[node] if int(tokens[c]) == target[node]), None)
        if nxt is None:
            return accepted, target[node]
        accepted.append(nxt)
        node = nxt
# 수락 후: 루트와 수락된 노드의 KV(위치 P + [0] + accepted)만 남겨 연속되게 모으고,
# 나머지는 버리고, 돌려받은 토큰을 다음 루트로 붙인다.
 

정리

  • 일반적인 수락 길이: 깊이별 조건부 수락률 aja_j인 chain은 E[L]=1+∑i∏j≤iaj\mathbb E[L] = 1 + \sum_i \prod_{j \le i} a_j, 어떤 트리든 기댓값의 선형성으로 E[L]=1+∑v∈TP(Av)\mathbb E[L] = 1 + \sum_{v \in T} P(A_v).
  • 노드의 값은 부모를 넘지 않으므로 예산 mm의 최적 트리는 그냥 값 상위 mm개 노드다. EAGLE-2는 보정된 draft confidence로 그 값을 문맥마다 추정한다(동적 트리).
  • 샘플링에서도 재귀적 rejection으로 트리 검증은 무손실이다. 자식이 거절될 때마다 target이 잔차 (r−q)+(r - q)_+가 된다. 결정적 top-kk 후보에서는 이것이 비복원 추출이다. 모든 자식을 원래 pp로 시험하면 편향된다.
  • drafter는 target의 feature를 읽고(EAGLE), 뽑힌 토큰을 조건으로 받고, 쓰이는 방식대로 학습되면서(EAGLE-3의 training-time test, multi-step·가중치 공유 MTP) 좋아졌다.
  • speculation은 FLOP을 메모리 트래픽과 맞바꾼다. 검증 forward가 memory-bound인 동안, 대략 B<ridge/nvB < \text{ridge}/n_v에서 이득이고(긴 문맥에서는 훨씬 나중까지), decode가 compute-bound가 되면 손해다. 큰 트리는 손익분기를 앞당기므로 실제 시스템은 배치가 커질수록 draft를 줄인다.

더 읽을거리Further reading