PythiloLesson 5 of 8 · progress kept in this browser

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.

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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.