Practice in Lab: Preserve target mass with speculative accept and residual resampling →
Preserve target mass with speculative accept and residual resampling
A draft model proposes cheaply, but naive verification would change the target distribution. Speculative sampling accepts some draft mass and compensates on rejection using the positive residual between target and draft probabilities. That residual is not simply the target distribution again. Making both uniform draws explicit separates the probability transform from RNG ownership and permits deterministic boundary tests. The Lab studies one categorical verification step, not a multi-token cached transformer execution pipeline.
Prepare offline
Choose Download entire course or Download entire category first. After completion, code and checks run locally on CPU. The independent example needs no account, remote service or API key.
import torch
p = torch.tensor([.2, .8])
q = torch.tensor([.8, .2])
print((p-q).clamp_min(0))Review the evidence
Check support mismatch, equal distributions and rejection boundaries. Correct target mass is necessary for speculative generation, while speed depends on model costs, acceptance rates and the actual hardware pipeline.
Your task
Implement one exact categorical speculative step for normalized finite nonnegative [vocab] probabilities. The proposed token must have positive draft mass. Accept it when accept_uniform < min(1,target[proposal]/draft[proposal]). On rejection, inverse-CDF sample from normalized clamp(target-draft,min=0), using residual_uniform and right-open CDF bins. Return (token, accepted). Uniforms are explicit finite values in [0,1), so the function owns no RNG. Reject invalid probabilities, token indices and uniforms. This single-position probability mechanism makes no wall-clock speed claim.
The explanation opens here once every check passes.