REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Preserve target mass with speculative accept and residual resampling
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.
Run this Lab in Pythilo
Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.
No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.
PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.
Pythilo on the App Store →Read lesson: Preserve target mass with speculative accept and residual resampling →
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.
Starter
import math
import torch
def speculative_token(target, draft, proposal, accept_uniform, residual_uniform):
# TODO: implement speculative_token under the declared contract.
return NoneInspect the worked answer
import math
import torch
def speculative_token(target, draft, proposal, accept_uniform, residual_uniform):
if target.ndim!=1 or len(target)<2 or draft.shape!=target.shape:raise ValueError('Expected aligned categorical probability vectors.')
for probability in (target,draft):
if not probability.is_floating_point() or not torch.isfinite(probability).all() or (probability<0).any() or abs(probability.double().sum().item()-1)>1e-6:raise ValueError('Probabilities must be finite, nonnegative and normalized.')
if type(proposal)!=int or not 0<=proposal<len(target) or draft[proposal]<=0:raise ValueError('Proposed token must have positive draft probability.')
if any(not math.isfinite(u) or not 0<=u<1 for u in (accept_uniform,residual_uniform)):raise ValueError('Uniform draws must belong to [0, 1).')
acceptance=min(1.,target[proposal].item()/draft[proposal].item())
if accept_uniform<acceptance:return proposal,True
residual=(target.detach().double()-draft.detach().double()).clamp_min(0)
mass=residual.sum()
if mass<=0:raise ValueError('A rejected proposal must leave positive residual mass.')
cumulative=(residual/mass).cumsum(0)
token=int(torch.searchsorted(cumulative,torch.tensor(residual_uniform,dtype=cumulative.dtype),right=True).item())
return min(token,len(target)-1),False