Speculative decoding II: trees, draft heads and multi-token prediction
Tree-based verification checks candidate paths in parallel. This lesson studies draft heads, EAGLE, Jacobi decoding and multi-token prediction, then trains simplified Medusa-style heads on the local GPU.
After this lesson you can
- Build a tree attention mask and depth-based positions and prove equivalence with separate path verification.
- Implement exact speculative sampling with multiple drafts per position.
- Train Medusa-style heads on a frozen model and measure accepted length.
- Compare static and dynamic trees and explain the advances in EAGLE-2 and EAGLE-3.
- Critically analyze comparisons between speculation methods and open questions.
Before you start
One verification, many paths
In a speculative chain, rejecting a token discards the rest of the chain. A tree reserves several continuations for one prefix: if one branch does not match, another may contain the token selected by the target. This opportunity has a price: more nodes mean more work and memory during verification. SpecInfer organizes proposals from small models in a tree and verifies their paths in parallel.
The mask preserves each path
Tree verification flattens the nodes into a batch of positions and replaces the linear causal mask with one that lets each node see only the common prefix, its ancestors and itself. A node’s position is the length of the common prefix plus its depth, not its index in the flattened array. Siblings have the same position but different contexts.
For a tree with parent , mask entry is zero if is an ancestor of or , and otherwise. It is added to attention logits before softmax, as in additive attention bias. Correct position is also essential for rotary encoding: two nodes at equal depth must have the same relative position.
Proof
At the input, each node and its copy in the separate path have the same token and position. Suppose their representations match at the start of a layer for all their ancestors. The query, key and value projections are identical. The mask leaves exactly the same keys and values as the separate run, so attention weights and their sum match. Position-wise operations, residuals and normalization match too. By induction this holds through all layers and the logit projection. The condition on position-wise operations excludes, for example, normalization that mixes nodes from different branches.
∎To see why an ordinary triangular mask fails, flatten the root, its two children A and B, and then A’s descendants. If B appears before a descendant of A, the triangular mask lets that descendant attend to B even though B is not part of its context. The result can change even when tokens on both branches are equal: attention would include an extra key and change the softmax denominator. Ordering the tree differently does not remove the problem for all paths; the mask must represent ancestry.
With a cache, the common prefix occupies the first key and value positions. Each tree node needs access to the entire prefix and its ancestors’ keys within the current block. An explicit 4D mask usually has batch, shared head, query and key dimensions. Check the library’s convention: a Boolean mask may interpret True as allowed or blocked, while an additive mask uses zero to allow and a large negative value to block. After accepting a branch, only its states may remain in the logical cache; states from rejected branches must not enter the next context.
The proof also explains what to measure when debugging. First compare positions and visible entries per node; then compare each path’s states or logits with separate runs at sufficient precision. Mathematical identity does not require bitwise equality on real hardware: different batch sizes and kernels change the order of floating-point operations. For greedy generation, a small difference can change the token if the top two logits are very close; the lab therefore checks both distributions and the resulting sequence.
Build the mask
In this example indices start at zero and the root’s parent is -1. The function requires each parent to appear before its child; this prevents cycles and allows depths to be calculated in one pass.
import numpy as np
def build_tree_mask(parents):
n = len(parents)
if not n or parents[0] != -1:
raise ValueError('la raíz debe ser el primer nodo')
mask = np.zeros((n, n), dtype=bool)
depth = np.zeros(n, dtype=int)
for i in range(n):
if i and not 0 <= parents[i] < i:
raise ValueError('cada padre debe preceder al hijo')
if i:
depth[i] = depth[parents[i]] + 1
j = i
while j >= 0:
mask[i, j] = True
j = parents[j]
return mask, depth
mask, depth = build_tree_mask([-1, 0, 0, 1, 1, 2, 2])
print('posiciones relativas:', depth)
print('máscara permitida:')
print(mask.astype(int))The mask is not enough if siblings use different positions. The following toy transformer uses two causal attention layers and position-wise operations. Compare the tree pass with independent execution of each path: same token, same relative position and same parameters. This verifies the small implementation, not all architectures empirically.
rng = np.random.default_rng(32)
parents = [-1, 0, 0, 1, 1, 2, 2]
tokens = np.array([0, 1, 2, 3, 4, 3, 4])
mask, positions = build_tree_mask(parents)
d = 8
embedding = rng.normal(size=(5, d))
position = rng.normal(size=(3, d))
weights = [(rng.normal(size=(d,d))*.2, rng.normal(size=(d,d))*.2,
rng.normal(size=(d,d))*.2) for _ in range(2)]
def forward_tree(token_ids, pos_ids, visible):
h = embedding[token_ids]+position[pos_ids]
for Wq, Wk, Wv in weights:
score = (h@Wq)@(h@Wk).T/np.sqrt(d)
score = np.where(visible, score, -np.inf)
exp = np.exp(score-np.max(score, axis=1, keepdims=True))
attention = exp/exp.sum(axis=1, keepdims=True)
h = np.tanh(h+attention@(h@Wv))
return h
tree_out = forward_tree(tokens, positions, mask)
errors = []
for node in range(len(tokens)):
path = []
j = node
while j >= 0:
path.append(j); j = parents[j]
path = path[::-1]
causal = np.tri(len(path), dtype=bool)
separate = forward_tree(tokens[path], positions[path], causal)
errors.append(np.max(np.abs(tree_out[node]-separate[-1])))
print('máxima diferencia por camino:', float(max(errors)))
assert max(errors) < 1e-10The assertion checks the largest difference. Equivalence depends on no operation mixing branches outside the mask: for example, normalization using statistics from the full set of nodes would invalidate the induction. Now use a toy vocabulary projection and follow the argmax until there is no matching child. Check each emitted token against the separate computation of its prefix.
unembedding = rng.normal(size=(d, 5))
logits = tree_out @ unembedding
node = 0
path = [0]
emitted = []
while True:
chosen = int(np.argmax(logits[node]))
emitted.append(chosen)
path_tokens = tokens[path]
separate = forward_tree(path_tokens, np.arange(len(path)), np.tri(len(path), dtype=bool))
assert chosen == int(np.argmax(separate[-1] @ unembedding))
child = next((i for i in range(len(parents)) if parents[i] == node and tokens[i] == chosen), None)
if child is None:
break
node = child
path.append(child)
print('nodos recorridos:', path, 'tokens emitidos:', emitted)The last token may not have a child in the tree: it is the greedy correction and closes the block. If a leaf is reached, it works the same way and that last token is the extra one. The separate comparison uses the same argmax tie-break and positions.
Multiple candidates and exactness
Multi-draft sampling requires a coupling rule that preserves the target distribution. Accepting the first plausible-looking candidate is not enough: choosing among proposals changes their distribution. A sequential construction can apply the previous lesson’s acceptance and residual rule, updating the residual distribution after each rejection and using the distribution actually used for each proposal. SpecTr formulates the choice using optimal transport. Having multiple branches does not imply independent acceptance probabilities.
One construction uses independent candidates from the same distribution . Start with the pending distribution . For each candidate, accept with ; if rejected, replace with normalized . After exhausting the candidates, sample from the current residual. Conditioned on each rejection, the previous lesson’s proof applies to the pending distribution. By backward induction, the output follows . Each next proposal must follow the stated distribution even conditioned on the history, which independence satisfies. This rule is not necessarily SpecTr’s optimal transport.
from scipy.stats import chisquare
def multi_candidate(p, q, k, random):
residual = p.copy()
for attempt in range(k):
x = random.choice(len(q), p=q)
if random.random() < min(1., residual[x]/q[x]):
return x, True
residual = np.maximum(residual-q, 0.)
residual /= residual.sum()
return int(random.choice(len(p), p=residual)), False
p = np.array([.6, .3, .1]); q = np.array([.2, .5, .3])
random = np.random.default_rng(48)
for k in (1, 3):
samples = [multi_candidate(p,q,k,random) for _ in range(6000)]
counts = np.bincount([x for x,_ in samples], minlength=3)
stat, pv = chisquare(counts, 6000*p)
print('k', k, 'frecuencia', np.round(counts/6000, 4),
'aceptación de alguna propuesta', round(np.mean([a for _,a in samples]), 4),
'chi cuadrado', round(stat,3), 'valor p', round(pv,4))The empirical output checks only a three-symbol distribution with this number of samples. Values depend on the seed, and a test that does not reject does not prove exactness. Notice that acceptance of some proposal and the final distribution are different quantities.
The pending distribution has a useful interpretation. After one attempt, the accepted mass for a symbol is . The mass not yet emitted is ; dividing by its sum yields the conditional distribution to use after rejection. The next attempt repeats the argument on that conditional distribution. If total residual mass is zero, rejection has probability zero and the normalization branch is not reached in exact arithmetic. A numerical implementation should watch for near-zero sums and use suitable precision.
More candidates do not imply a product of rejection probabilities calculated from the initial acceptance. After each rejection the pending distribution changes, and with dependent proposals the next proposal’s distribution can change too. Using again in the numerator or a different from the one that generated the candidate breaks the argument. The example uses independent candidates to make that condition explicit; it is not intended as SpecTr’s optimal transport solution.
Heads and features
Medusa draft heads predict multiple future tokens from model features. Their combinations form tree candidates verified by the model. Medusa distinguishes a frozen-backbone variant from one that tunes backbone and heads; its typical acceptance is an approximate alternative and does not imply exact preservation of the original distribution.
The base head predicts from ; additional head predicts . In the paper’s design, each head has a residual transformation with SiLU and its own vocabulary projection, initialized from the original head. Predictions for each position are combined into a candidate tree. The mask prevents one branch from reading another and each node shares its prefix computation. Medusa-1 freezes the backbone; Medusa-2 also tunes it and uses a recipe to preserve its predictive ability. In both cases distinguish the resulting model from the acceptance rule: a frozen backbone does not turn arbitrary approximate selection into exact sampling.
The paper’s typical acceptance selects continuations considered sufficiently plausible and takes a long prefix; it aims to preserve empirical quality, not necessarily to match the original distribution. In contrast, a correct rejection rule can preserve the target distribution. Greedy verification preserves greedy output with fixed tie-breaking, which is not equivalent to preserving a positive-temperature distribution.
Training extra heads requires correctly aligning targets. If state summarizes the prefix through , the base head predicts and the first extra head predicts . The final pair of positions lacks labels for all heads and must be excluded from the corresponding loss. When the backbone is frozen, its representations can be computed without gradients; the projection and heads must still form a differentiable path to trainable parameters. Freezing the backbone saves gradients and prevents its weights from changing, but does not by itself ensure good future proposals.
To measure acceptance without contaminating evaluation, separate tuning sequences from those used for evaluation. Record how many prefixes reach each depth, how often each candidate rank matches, and accepted prefix length. At greater depths only cases that matched earlier survive: dividing by the initial total instead of those that reached the depth answers a different question. A mean over a few prefixes also cannot distinguish general improvement from variation specific to those texts.
EAGLE drafting uses internal features to anticipate continuations. EAGLE autoregresses on penultimate-layer features and incorporates an advanced token sequence to reduce prediction uncertainty. EAGLE-2 builds context-dependent dynamic trees, using draft confidence to prioritize candidates. EAGLE-3 abandons direct feature prediction, fuses features from several layers and trains to reduce the gap between training and inference inputs. Published speedups depend on models, tasks and hardware: they cannot be directly compared with another work without matching those conditions.
The change from a static to a dynamic shape responds to a budget decision. A static shape always reserves the same branches per depth; a dynamic one assigns more nodes to paths that look promising in the current context. Draft confidence is a ranking signal, not a guaranteed acceptance probability by definition. EAGLE-2 reports that this signal was well calibrated in its experiments. EAGLE-3 fuses features from different layers and uses training that exposes the draft to inputs resembling those it generates during inference; it no longer imposes direct feature prediction as the main objective. Output distributions still depend on subsequent verification and selection.
The following comparison uses an explicit binary model: at each node the target selects one branch with probability and the other with , the same at all levels. A path’s probability is the product of its edges. Expected covered length sums the probabilities of all tree nodes except the root. Here expansion by probability maximizes that sum among trees of equal budget, because a descendant’s probability never exceeds its parent’s. This does not prove a real dynamic tree is optimal: estimated probabilities and each shape’s cost matter too.
The identity used is . At one level, possible paths are disjoint and their probabilities add; summing levels gives each node’s contribution. For example, with two complete levels and binary probabilities summing to one at each level, covered length is exactly two. With a limited budget, a narrow branch may be preferable if it concentrates much probability; with less concentrated distributions, covering siblings gains weight. The correction or extra token is not counted in this figure.
The figure also offers a profile recorded in the later lab before tuning, over four test prefixes. At each depth it divides matches of each rank by prefixes that reached it: the three levels have 4, 4 and 1 attempts respectively, and matches by rank are , and . For hypothetical paths these proportions are reused for every context at a level, an additional assumption the four examples do not justify on their own. The third level has one attempt and says nothing about later depths. Use it to explore the calculation, not as a prediction of model acceptance.
Fixed points and multi-token prediction
Jacobi decoding expresses greedy generation as a fixed point: each position is updated in parallel from previous positions in the preceding iteration. The first position is correct after one iteration; by induction, at least one additional position becomes correct per iteration. In the worst case there are as many iterations as tokens and no step savings. Lookahead decoding reuses n-grams from iterations as verified proposals. The result depends on the verification rule, not merely calling the method Jacobi.
If returns the greedy token at position from a prefix, the update is . All positions on the right belong to the previous iteration. The first depends on no unknown and becomes correct immediately; once the first positions are correct, the next update also fixes . Some later positions may match earlier, but that does not guarantee they stay correct while their prefix changes. In the figure only the prefix matching the greedy solution is considered stable.
Multi-token prediction adds training objectives for several future positions, as studied by Gloeckle et al.. Those predictions can serve as a draft, provided subsequent verification preserves the desired output rule. Adding heads or an auxiliary branch does not guarantee a time improvement: their cost, the tree, cache and batch must be measured together.
During training, a distance-two objective compares the output associated with the prefix through with token ; a distance-three head is compared with . Shifts must exclude unlabeled positions at the end of each sequence. During inference those future tokens do not yet exist: a proposal is fed the context and available predictions, then the target verifies them. Confusing a future label used in training with information available during generation would introduce information leakage.
DeepSeek-V3 uses sequential MTP modules to extend the training objective to additional tokens and notes that they can also be reused for speculation. That architecture is not identical to the simplified parallel heads in the next lab. The additional objective can influence the learned model, while the exactness of a particular run belongs to its verifier and acceptance rule.
What to compare and what remains open
A longer accepted prefix does not by itself mean lower latency. Iteration time includes proposal, mask and tree construction, verification and selection, as well as cache management. If the tree generates an average of tokens per iteration and takes , the relevant ratio is ; changing shape can increase both. Memory matters too: duplicating states or building a dense mask can cancel the savings from sharing paths.
In a large batch, the target may already use the accelerator better and extra verification competes for resources with other requests. For long contexts, cache reads and the attention shape change the balance. In mixture-of-experts models, token distribution per expert and inter-device communication add costs that mean acceptance does not describe. These are performance hypotheses to measure for each system, not a universal rule that speculation always helps or hurts.
A fair comparison fixes target model and revision, tokenizer, prompts, input and output length, precision, batch, temperature, hardware and cache configuration. Report per-request latency and throughput, warmup, number of repetitions, memory and accepted-length distribution, as well as the selection rule. If a method changes the model or uses approximate acceptance, also measure the relevant quality or distribution difference. A single eight-token measurement can detect that the flow works, but cannot establish a production result.
Local lab: heads on a frozen model
This experiment builds two simplified residual heads on SmolLM2-360M, with the backbone and its vocabulary projection frozen. Each head learns a linear correction to the hidden state and predicts tokens two and three positions ahead respectively. It is a teaching variant inspired by Medusa, not a reproduction of its complete recipe. Training uses part of the training split of WikiText-2 raw, and evaluation uses separate test prefixes.
At each step, the base model proposes two candidates for the first token and the heads propose two for each later position. Their Cartesian product produces a tree of 14 nodes. The 4D mask exposes the common prefix and each node’s ancestors, and positions depend on depth. The first check compares all paths with independent passes in FP32. The verifier then follows the target’s argmax among the children until that child is missing, and emits the missing argmax. If it reaches a leaf, it emits one extra token. In exact arithmetic this reproduces the greedy sequence; on the machine, generated token equality is checked.
The prototype reprocesses the full prefix and first computes logits and heads before the tree pass. It is deliberately simple, not an optimized serving kernel: comparing time with the uncached baseline quantifies this implementation, not an intrinsic Medusa speedup. The 135M draft from the previous lesson is also compared using generate with the same 360M target and its library baseline. These are different paths and shared load can change the ratios. The short training loop checks the flow; increase steps and training tokens for a study, with independent validation and multiple seeds.
import time
import torch
from torch import nn
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
torch.manual_seed(29)
torch.set_num_threads(4)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model_id = 'HuggingFaceTB/SmolLM2-360M'
revision = 'f8027fd0eaeea54caa13c31d31b9fdc459c38b49'
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision,
dtype=torch.float32, attn_implementation='eager').to(device).eval()
for parameter in model.parameters():
parameter.requires_grad_(False)
hidden_size = model.config.hidden_size
heads = nn.ModuleList([nn.Linear(hidden_size, hidden_size, bias=False) for _ in range(2)]).to(device)
for head in heads:
nn.init.zeros_(head.weight)
optimizer = torch.optim.AdamW(heads.parameters(), lr=1e-3)
dataset_rev = 'b08601e04326c79dfdd32d625aee71d232d685c3'
train = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1', split='train', revision=dataset_rev)
test = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1', split='test', revision=dataset_rev)
def tokenize_rows(rows, limit):
text = chr(10).join(r['text'] for r in rows if r['text'].strip())
return tokenizer(text, return_tensors='pt', truncation=True, max_length=limit).input_ids[0]
train_ids, test_ids = tokenize_rows(train, 8192), tokenize_rows(test, 1024)
def candidates(h, logits):
choices = [torch.topk(logits, 2).indices.tolist()]
for head in heads:
choices.append(torch.topk(model.lm_head(h+head(h)), 2).indices.tolist())
nodes, parents, depth, frontier = [], [], [], [-1]
for level, options in enumerate(choices, 1):
new = []
for parent in frontier:
for token in options:
new.append(len(nodes)); nodes.append(token); parents.append(parent); depth.append(level)
frontier = new
return nodes, parents, depth
@torch.no_grad()
def tree_pass(prefix, nodes, parents, depth):
n = prefix.shape[1]; size = n+len(nodes)
ids = torch.cat((prefix, torch.tensor([nodes], device=device)), dim=1)
visible = torch.zeros((size,size), dtype=torch.bool, device=device)
visible[:n,:n] = torch.tril(torch.ones((n,n), dtype=torch.bool, device=device))
for i in range(len(nodes)):
visible[n+i,:n] = True
j = i
while j >= 0:
visible[n+i,n+j] = True
j = parents[j]
additive = torch.where(visible, 0., torch.finfo(torch.float32).min)[None,None,:,:]
positions = torch.tensor([list(range(n))+[n+d-1 for d in depth]], device=device)
return model(ids, attention_mask=additive, position_ids=positions, use_cache=False).logits[0]
@torch.no_grad()
def step(prefix, verify=False):
output = model(prefix, output_hidden_states=True, use_cache=False)
h, logits = output.hidden_states[-1][0,-1], output.logits[0,-1]
nodes, parents, depth = candidates(h, logits)
tree_logits = tree_pass(prefix, nodes, parents, depth)
if verify:
max_tv = 0.
for node in range(len(nodes)):
path=[]; j=node
while j>=0:
path.append(j); j=parents[j]
path.reverse()
seq = torch.cat((prefix, torch.tensor([[nodes[j] for j in path]],device=device)),dim=1)
separate = model(seq, use_cache=False).logits[0,-1]
tv = (F.softmax(separate.float(),dim=-1)-F.softmax(tree_logits[prefix.shape[1]+node].float(),dim=-1)).abs().sum()/2
max_tv = max(max_tv, tv.item())
print('TV máxima entre árbol y caminos:', max_tv)
assert max_tv < 1e-4
selected, parent = [], -1
next_token = int(logits.argmax())
while True:
matching = next((i for i,p in enumerate(parents) if p == parent and nodes[i] == next_token), None)
if matching is None:
break
selected.append(nodes[matching]); parent = matching
next_token = int(tree_logits[prefix.shape[1]+matching].argmax())
return selected+[next_token], len(selected)
@torch.no_grad()
def heldout_acceptance():
lengths = []
for start in (0,64,128,192):
prefix = test_ids[start:start+32][None,:].to(device)
_, accepted = step(prefix)
lengths.append(accepted)
return lengths
@torch.no_grad()
def heldout_rank_profile():
attempts = [0,0,0]
hits = [[0,0] for _ in range(3)]
for start in (0,64,128,192):
prefix = test_ids[start:start+32][None,:].to(device)
output = model(prefix, output_hidden_states=True, use_cache=False)
nodes, parents, depth = candidates(output.hidden_states[-1][0,-1], output.logits[0,-1])
logits = tree_pass(prefix, nodes, parents, depth)
target_token = int(output.logits[0,-1].argmax()); parent = -1
for level in range(3):
attempts[level] += 1
siblings = [i for i,p in enumerate(parents) if p == parent]
found = next((rank for rank,i in enumerate(siblings) if nodes[i] == target_token), None)
if found is None:
break
hits[level][found] += 1
parent = siblings[found]
target_token = int(logits[prefix.shape[1]+parent].argmax())
return attempts, hits
sample = test_ids[:32][None,:].to(device)
step(sample, verify=True)
print('longitudes aceptadas antes:', heldout_acceptance())
print('perfil antes: intentos y aciertos por rango:', heldout_rank_profile())
seq, batch, steps = 48, 4, 16
losses = []
for t in range(steps):
starts = [(t*batch+i)*seq for i in range(batch)]
x = torch.stack([train_ids[start:start+seq] for start in starts]).to(device)
with torch.no_grad():
h = model.model(x, use_cache=False).last_hidden_state
optimizer.zero_grad(set_to_none=True)
loss = 0.
for index, offset in enumerate((2,3)):
h0 = h[:,:-offset]
prediction = model.lm_head(h0+heads[index](h0))
loss = loss + F.cross_entropy(prediction.reshape(-1,prediction.shape[-1]),x[:,offset:].reshape(-1))
loss.backward(); optimizer.step(); losses.append(loss.item())
print('pérdida primer y último lote:', round(losses[0],4), round(losses[-1],4))
print('longitudes aceptadas después:', heldout_acceptance())
print('perfil: intentos por profundidad y aciertos por rango:', heldout_rank_profile())
@torch.no_grad()
def tree_generate(prefix, count):
ids = prefix.clone(); accepted_total = calls = 0
while ids.shape[1] < prefix.shape[1]+count:
emitted, accepted = step(ids)
ids = torch.cat((ids,torch.tensor([emitted],device=device)),dim=1)
accepted_total += accepted; calls += 1
return ids, accepted_total, calls
@torch.no_grad()
def greedy_generate(prefix,count):
ids = prefix.clone()
for _ in range(count):
token = model(ids,use_cache=False).logits[0,-1].argmax().reshape(1,1)
ids = torch.cat((ids,token),dim=1)
return ids
def measured(fn):
if device=='cuda': torch.cuda.synchronize()
start=time.perf_counter(); result=fn()
if device=='cuda': torch.cuda.synchronize()
return result,time.perf_counter()-start
tree_generate(sample,2); greedy_generate(sample,2)
(out,accepted,calls),elapsed = measured(lambda:tree_generate(sample,8))
baseline,elapsed_base = measured(lambda:greedy_generate(sample,8))
same = torch.equal(out[:,:sample.shape[1]+8],baseline)
print('árbol: tokens',out.shape[1]-sample.shape[1],'aceptados',accepted,'llamadas',calls,
'igual al voraz',same,'tokens/s',(out.shape[1]-sample.shape[1])/elapsed,
'base tokens/s',8/elapsed_base)
draft_id = 'HuggingFaceTB/SmolLM2-135M'
draft_rev = '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
draft_tokenizer = AutoTokenizer.from_pretrained(draft_id, revision=draft_rev)
assert tokenizer.get_vocab() == draft_tokenizer.get_vocab()
draft = AutoModelForCausalLM.from_pretrained(draft_id,revision=draft_rev,dtype=torch.float32).to(device).eval()
draft.generation_config.num_assistant_tokens = 4
draft.generation_config.num_assistant_tokens_schedule = 'constant'
draft.generation_config.assistant_confidence_threshold = 0.0
@torch.no_grad()
def library_generate(assistant=None):
kwargs = {'assistant_model':assistant} if assistant is not None else {}
return model.generate(sample,max_new_tokens=8,do_sample=False,pad_token_id=tokenizer.eos_token_id,**kwargs)
library_generate(); library_generate(draft)
base, tb = measured(library_generate)
assisted, ta = measured(lambda:library_generate(draft))
print('biblioteca: igual al voraz',torch.equal(base,assisted),
'tokens base',base.shape[1]-sample.shape[1], 'tokens asistida',assisted.shape[1]-sample.shape[1],
'velocidad relativa',((assisted.shape[1]-sample.shape[1])/ta)/((base.shape[1]-sample.shape[1])/tb))npm run lab and open the connection link.Do not interpret the loss of the first and last batch as a learning curve: they are different batches. The four test lengths check the flow and are insufficient to claim general improvement or deterioration. Save the heads and expand the data, training and evaluation before deciding; the lesson does not include a pretrained checkpoint from this experiment.
In a short RTX 3060 run with FP32, maximum TV between distributions of the 14 nodes and those of their independent paths was approximately . Accepted lengths for the four test prefixes were before tuning and afterward. For the prefix used for generation, the tree emitted eight tokens in four blocks and matched the greedy baseline. The library also produced the same sequence with the 135M draft for that example. There is no evidence here that tuning improves overall acceptance: four prefixes and 16 training steps are too few. The path equality test is a limited validation of mask and positions in this model and environment, not a guarantee about another implementation.
Exercises
Step 1 of 2. Which keys can a node use?
tree_mask(parents): it receives parents with root -1 and every parent before its child. Return the Boolean ancestor mask and depths.import numpy as np
def tree_mask(parents):
pass