Text sampling: temperature, top-k, top-p and the truncation family
The same model can produce repetitive, incoherent or brilliant text depending on next-token selection. We study the decoding loop and logit processors, temperature, top-k and top-p, adaptive truncation (min-p, typical and eta), repetition penalties and Gumbel-max. We implement these from scratch, vectorize batches with per-request parameters, and evaluate diversity and quality.
After this lesson you can
- Implement a logit-processor chain with temperature, top-k, top-p, min-p, typical sampling and penalties.
- Explain text degeneration and each truncation's assumptions about the distribution tail.
- Prove Gumbel-max and use it for batched sampling with per-request seeds.
- Vectorize a GPU sampler with different per-request parameters and measure cost against vocabulary size.
- Evaluate decoders with diversity, repetition and MAUVE over multiple seeds.
Before you start
One model, many continuations
The autoregressive decoding loop receives a prefix, computes next-token logits, applies processors, chooses a token, and appends it to the prefix. It ends at EOS, a length limit, or a stop sequence. A stop sequence can cross token boundaries: the server must decide whether to include it in returned text and check matches over the appropriate stream. KV cache avoids recomputing the entire prefix but does not change the distribution defined by logits.
Processor order is part of the algorithm. This figure uses temperature, top-k, top-p, and min-p; repetition penalty is applied earlier in the NumPy lab. Transformers builds processors according to configuration and version. In vLLM code, the inspected GPU path applies temperature and min-p before top-k/top-p. Do not assume two libraries or versions compose filters identically just because they accept the same names.
Temperature and entropy
With logits and , temperature sampling uses . Lower temperature concentrates mass on maxima; higher temperature flattens the distribution. If the maximum is unique, concentrates all mass on it; tied maxima share mass in the limit. An API accepting usually defines deterministic argmax separately, avoiding division by zero. As , the distribution over finite logits approaches uniform.
Entropy in nats satisfies and
The derivative can be zero if all logits are equal. This property concerns the distribution before truncation: if the allowed token set also changes, final entropy may behave differently. Temperature changes distribution shape; it does not correct a false claim or guarantee useful diversity.
To derive it, write and . Then , , and . Thus ; multiplying by gives the preceding formula. This derivation assumes a finite vocabulary of fixed finite logits as changes.
Truncate the tail
Top-k retains the largest logits and renormalizes. With boundary ties, an implementation may keep all tied values and exceed , or break ties deterministically. Fixed can be restrictive in a flat distribution and leave many options in a concentrated one.
Top-p or nucleus sampling sorts by descending probability and retains the smallest prefix whose mass reaches , including the token crossing the threshold. If the first already exceeds , at least that token is retained. For and , the first three remain: their mass is 0.85 and the first becomes . With , the entire finite support remains.
Holtzman et al. study degeneration in open-ended generation: maximizing probability can produce repetitive text, while sampling the entire tail can introduce implausible continuations. These are observations for their tasks and models, not a universal ranking of temperatures. A grid of a few samples lets us investigate examples, not discover an optimal setting for every task.
The adaptive truncation family uses properties of that step’s distribution:
- Min-p: retains . If the maximum is 0.6 and , the threshold is 0.06. Applied to the earlier distribution, its actual maximum is 0.5, so the threshold is 0.05 and all five tokens survive when equality is included.
- Locally typical: sorts by and accumulates desired mass in that order. A very likely token may be excluded if its surprise is far from entropy. Meister et al. distinguish local and full-sequence typicality.
- Eta: uses and retains probabilities above threshold, with a safeguard of at least one token. Hewitt et al. interpret truncation as a way to undo smoothing; this models the problem, not proof that each discarded token is incorrect.
Top-p depends on probabilities, so applying temperature before or after can change the nucleus. For example, distribution has a two-token nucleus for ; at much lower temperature the first can exceed the threshold alone. By contrast, for temperature preserves logit order and by itself does not change which indices belong to top-k without ties.
Repetition and biases
Repetition penalties alter logits based on history. A presence penalty subtracts a constant if the token already appeared; a frequency penalty subtracts an amount proportional to appearances. The multiplicative variant used in CTRL divides a positive logit by a factor greater than one and multiplies a negative one by it. Dividing a negative logit would move it toward zero and might favor it. Penalties can break loops but also harm names, code, quotations, and function words that should recur.
The Gumbel race
The Gumbel-max trick generates with independent uniform and chooses . Winning probability is . To prove it, are independent unit-rate exponentials. Maximizing equals minimizing , exponential with rate . In an independent exponential race, the probability that wins is its rate divided by the sum: integrating from zero to infinity gives that ratio. Adding to is equivalent, for , to adding standard Gumbel to .
A per-request seed allows the random trajectory not to depend on other requests sharing the batch, provided each request retains its own generator and draw count. It does not ensure bitwise equality across versions, devices, or different sampling algorithms. In the lab, filtering is vectorized; drawing from independent generators iterates over rows. A single-row generation is also compared with transformers.generate using the same seed and multinomial, without claiming Gumbel and multinomial produce the same sequence.
Evaluate distributions and text
distinct-n divides the number of distinct n-grams by the total n-grams; repetition can be defined several ways and must be accompanied by its definition. Random text may have high diversity and be useless. Early EOS, variable length, tokenization, prompts, and sample size affect both figures. Use multiple seeds, the same prompts, and enough examples, and complement metrics with task-appropriate quality and accuracy review.
MAUVE compares distributions of generated and reference text representations using quantization and a divergence frontier. It depends on extractor, sample count, clustering, and domains. A high value does not prove every claim true; a tiny sample can be unstable. The displayed grid uses only three seeds per cell and does not calculate MAUVE; this lesson’s additional experiment states its configuration and limits instead of attributing a general quality result to the model.
In one real exploratory test, 32 passages were taken from WikiText-2 test: eight prefix tokens and 16 reference tokens, with SmolLM2-135M on an RTX 3060. For each setting and seed, up to 16 tokens per prefix were generated; mean final-layer representations from the same model were compared with four clusters using mauve-text 0.4.0. At temperature 0.7 and top-p 0.9, seeds 11, 29, and 47 gave MAUVE 0.948, 0.984, and 0.993; at temperature 1.2 and top-p 1.0 they gave 0.877, 0.825, and 0.997. The library warned that 64 combined vectors are few for four centroids. These figures check the procedure, not a reliable quality comparison or standard evaluation with large GPT-2. Seed variation and scarce data prevent choosing a setting from this test.
The continuation figure was generated with the same model and shown English prompt, three seeds, and at most 20 tokens; its distinct-2 and repetition are computed over tokens, not words. Distributions are real float32 logits from three prompts, stored in full so changing temperature recalculates mass and entropy without approximating the tail. They do not update when the model version changes: regenerating the resource requires recording model, prompt, version, and parameters again.
The next example reproduces the exploratory protocol if mauve-text, faiss-cpu, datasets, transformers, and PyTorch with CUDA are installed and the model and WikiText-2 are cached. It is optional local code because of its dependencies and cost; the reference run used an isolated mauve-text installation and does not modify the project’s shared installation.
import os,sys,json
from pathlib import Path
os.environ['HF_HUB_OFFLINE']='1';os.environ['HF_DATASETS_OFFLINE']='1';os.environ['OMP_NUM_THREADS']='1'
import numpy as np
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
import mauve
import faiss
faiss.omp_set_num_threads(1)
torch.set_num_threads(1);assert torch.cuda.is_available()
model_id='HuggingFaceTB/SmolLM2-135M';tok=AutoTokenizer.from_pretrained(model_id,local_files_only=True)
tok.pad_token=tok.eos_token
model=AutoModelForCausalLM.from_pretrained(model_id,local_files_only=True,dtype=torch.float32).eval().cuda()
ds=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split='test')
sequences=[]
for row in ds:
ids=tok(row['text'],add_special_tokens=False)['input_ids']
if len(ids)>=24: sequences.append(ids[:24])
if len(sequences)==32:break
assert len(sequences)==32
contexts=torch.tensor([x[:8] for x in sequences],device='cuda')
references=[tok.decode(x[8:],skip_special_tokens=True) for x in sequences]
def features(texts):
out=[]
for start in range(0,len(texts),8):
batch=tok([x if x else tok.eos_token for x in texts[start:start+8]],padding=True,truncation=True,max_length=32,return_tensors='pt').to('cuda')
with torch.no_grad(): hidden=model(**batch,output_hidden_states=True).hidden_states[-1]
mask=batch['attention_mask'].unsqueeze(-1); pooled=(hidden*mask).sum(1)/mask.sum(1)
out.append(pooled.float().cpu().numpy())
return np.concatenate(out)
p=features(references);results=[]
for temp,top_p in ((.7,.9),(1.2,1.0)):
for seed in (11,29,47):
torch.manual_seed(seed);torch.cuda.manual_seed_all(seed);generated=[]
with torch.no_grad():
for start in range(0,len(contexts),8):
inp=contexts[start:start+8]
output=model.generate(input_ids=inp,attention_mask=torch.ones_like(inp),do_sample=True,temperature=temp,top_p=top_p,top_k=0,max_new_tokens=16,pad_token_id=tok.eos_token_id)
generated.extend(output[:,8:].cpu().tolist())
generated=[ids[:ids.index(tok.eos_token_id)] if tok.eos_token_id in ids else ids for ids in generated]
texts=[tok.decode(x,skip_special_tokens=True) for x in generated]
bigrams=[(a,b) for ids in generated for a,b in zip(ids,ids[1:])]
distinct=len(set(bigrams))/len(bigrams) if bigrams else 0.
repetition=np.mean([1-len(set(ids))/len(ids) if ids else 0. for ids in generated])
q=features(texts)
score=mauve.compute_mauve(p_features=p,q_features=q,num_buckets=4,seed=7,kmeans_num_redo=2,kmeans_max_iter=50,verbose=False).mauve
result={'temperature':temp,'top_p':top_p,'seed':seed,'distinct2':float(distinct),'repeat':float(repetition),'mauve':float(score),'n':len(texts)}
print(json.dumps(result),flush=True);results.append(result)
print('GPU',torch.cuda.get_device_name(),'32 pasajes; MAUVE exploratorio con medias de hidden-state y 4 grupos, no comparable con evaluación estándar.',flush=True)
Lab: processors in NumPy
The cell applies penalty, temperature, and filters in the stated order; Gumbel-max is checked against the resulting categorical distribution with a statistic for each configuration. The threshold 30 is a reproducible check for these cases, not a mathematical proof of equality. The character model is trained on a toy sentence. Five real logits come from the figure’s factual prompt; their probabilities are renormalized only over those five, not the full vocabulary.
import numpy as np
def probabilities(z):
z=np.asarray(z,dtype=float);e=np.exp(z-np.max(z));return e/e.sum()
def truncate(z,order,mass):
p=probabilities(z); cumulative=np.cumsum(p[order]);keep=np.zeros(len(z),bool)
# Incluye el primer token que alcanza o cruza el umbral.
count=min(len(z),np.searchsorted(cumulative,mass,side='left')+1)
keep[order[:count]]=True;return np.where(keep,z,-np.inf)
def process(logits,history=(),temperature=1.,k=None,top_p=1.,min_p=0.,typical=1.,eta=None,repetition=1.,frequency=0.,presence=0.):
z=np.asarray(logits,dtype=float).copy();counts=np.bincount(list(history),minlength=len(z))
seen=counts>0;z[seen]=np.where(z[seen]<0,z[seen]*repetition,z[seen]/repetition)
z-=frequency*counts+presence*seen
if temperature==0:
out=np.full_like(z,-np.inf);out[np.argmax(z)]=0;return out
z/=temperature
if k is not None and k<len(z):
cutoff=np.sort(z)[-k];z=np.where(z>=cutoff,z,-np.inf)
if top_p<1: z=truncate(z,np.argsort(-z,kind='stable'),top_p)
if min_p>0:
p=probabilities(z);z=np.where(p>=min_p*p.max(),z,-np.inf)
if typical<1:
p=probabilities(z);positive=p>0;entropy=-np.sum(p[positive]*np.log(p[positive]));surprise=np.full_like(p,np.inf);surprise[positive]=np.abs(-np.log(p[positive])-entropy)
z=truncate(z,np.argsort(surprise,kind='stable'),typical)
if eta is not None:
p=probabilities(z);positive=p>0;entropy=-np.sum(p[positive]*np.log(p[positive]));threshold=min(eta,np.sqrt(eta)*np.exp(-entropy));keep=p>threshold;keep[np.argmax(p)]=True;z=np.where(keep,z,-np.inf)
return z
def gumbel(z,rng):
u=np.clip(rng.random(len(z)),1e-12,1-1e-12);return int(np.argmax(z-np.log(-np.log(u))))
z=np.log([.5,.2,.15,.1,.05]);rng=np.random.default_rng(123)
cases={'base':{},'top-k':{'k':3},'top-p':{'top_p':.8},'min-p':{'min_p':.3},'típico':{'typical':.8},'eta':{'eta':.08},'penalización':{'history':[0,0,3],'frequency':.2,'presence':.1},'temperatura':{'temperature':.6}}
for name,kwargs in cases.items():
filtered=process(z,**kwargs);p=probabilities(filtered)
draws=np.array([gumbel(filtered,rng) for _ in range(30000)]);counts=np.bincount(draws,minlength=len(p));mask=p>0
chi=float(np.sum((counts[mask]-30000*p[mask])**2/(30000*p[mask])))
assert np.all(counts[~mask]==0) and chi<30
entropy=-sum(p[mask]*np.log(p[mask]));print(name,'probabilidades',np.round(p,4),'chi²',round(chi,3),'entropía',round(entropy,3))
assert np.flatnonzero(np.isfinite(process(z,top_p=.8))).tolist()==[0,1,2]
assert probabilities(process(z,temperature=0)).argmax()==0
assert process(np.array([-2.,2.]),history=[0,1],repetition=2).tolist()==[-4.,1.]
# Modelo de caracteres de juguete con cuentas de transición suavizadas.
text='la luna ilumina la laguna y la luna ilumina la ladera '
chars=sorted(set(text));lookup={c:i for i,c in enumerate(chars)};counts=np.ones((len(chars),len(chars)))
for a,b in zip(text,text[1:]):counts[lookup[a],lookup[b]]+=1
current=lookup['l'];generated='l'
for _ in range(60):
logits=np.log(counts[current]);current=gumbel(process(logits,temperature=.8,top_p=.9),rng);generated+=chars[current]
print('Modelo de caracteres de juguete:',generated)
real=np.array([14.022818565368652,12.99731159210205,12.747232437133789,12.236936569213867,12.124651908874512])
print('Cinco logits de SmolLM2-135M; probabilidades condicionadas a estos cinco:',np.round(probabilities(real),4))
Lab: batched sampler on CUDA
On a CUDA GPU, real SmolLM2-135M logits and different per-row controls are used. Filtering is compared with Transformers processors and one-row multinomial generation with generate using the same seed. Independent Gumbel generators are checked inside and outside the batch. The topk versus sort comparison uses synthetic tensors, CUDA events, and several vocabulary sizes; it measures those primitives, not full generation latency, and times vary with GPU load.
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation.logits_process import TemperatureLogitsWarper, TopKLogitsWarper, TopPLogitsWarper, MinPLogitsWarper
assert torch.cuda.is_available()
device=torch.device('cuda');torch.set_num_threads(1)
model_id='HuggingFaceTB/SmolLM2-135M'
tokenizer=AutoTokenizer.from_pretrained(model_id,local_files_only=True)
model=AutoModelForCausalLM.from_pretrained(model_id,local_files_only=True,dtype=torch.float32).eval().to(device)
def filter_logits(logits,temps,ks,ps,mins):
# Cada control tiene un valor por fila. Temperatura cero es voraz.
B,V=logits.shape; temps=temps.to(device);ks=ks.to(device).clamp(1,V);ps=ps.to(device);mins=mins.to(device)
greedy=temps==0; safe=torch.where(greedy,torch.ones_like(temps),temps)
scores=logits/safe[:,None]
threshold=torch.topk(scores,int(ks.max().item()),dim=-1).values.gather(1,(ks-1)[:,None])
scores=scores.masked_fill(scores<threshold,-torch.inf)
sorted_scores,order=torch.sort(scores,descending=True,dim=-1,stable=True)
probs=torch.softmax(sorted_scores,dim=-1); cumulative=torch.cumsum(probs,dim=-1)
remove=(cumulative-probs>=ps[:,None]) & (ps[:,None]<1)
sorted_scores=sorted_scores.masked_fill(remove,-torch.inf)
scores=torch.full_like(scores,-torch.inf).scatter(1,order,sorted_scores)
probs=torch.softmax(scores,dim=-1);scores=scores.masked_fill(probs<mins[:,None]*probs.max(dim=-1,keepdim=True).values,-torch.inf)
if greedy.any():
winner=logits.argmax(dim=-1); allowed=torch.arange(V,device=device)[None,:]==winner[:,None]
scores=torch.where(greedy[:,None]&~allowed,torch.full_like(scores,-torch.inf),scores)
return scores
def gumbel_sample(scores,generators):
# Generadores persistentes por petición; solo el RNG se recorre por fila.
u=torch.stack([torch.rand(scores.shape[1],device=device,generator=g) for g in generators]).clamp_(1e-7,1-1e-7)
return (scores-torch.log(-torch.log(u))).argmax(dim=-1)
def vec(values,dtype): return torch.tensor(values,device=device,dtype=dtype)
prompt='Once upon a time, in a forest'
inputs=tokenizer(prompt,return_tensors='pt').to(device)
with torch.no_grad(): raw=model(**inputs).logits[:,-1,:].float()
batch=raw.repeat(3,1);temps=vec([.7,1.,1.3],torch.float32);ks=vec([20,40,80],torch.long);ps=vec([.8,.9,1.],torch.float32);mins=vec([.05,.02,0.],torch.float32)
ours=filter_logits(batch,temps,ks,ps,mins)
for i in range(3):
expected=batch[i:i+1]
for processor in (TemperatureLogitsWarper(float(temps[i])),TopKLogitsWarper(int(ks[i])),TopPLogitsWarper(float(ps[i])),MinPLogitsWarper(float(mins[i]))):
expected=processor(None,expected)
torch.testing.assert_close(ours[i:i+1],expected,rtol=1e-5,atol=1e-5)
print('Filtros por fila coinciden con procesadores de Transformers')
gens=[torch.Generator(device=device).manual_seed(s) for s in (11,29,47)]
batch_choice=gumbel_sample(ours,gens)
for i,seed in enumerate((11,29,47)):
single=gumbel_sample(ours[i:i+1],[torch.Generator(device=device).manual_seed(seed)])
assert batch_choice[i]==single[0]
print('Gumbel por petición conserva su semilla al cambiar de lote')
# Paridad de generación con la misma semilla y el mismo sampler multinomial.
torch.manual_seed(314);torch.cuda.manual_seed_all(314)
with torch.no_grad():
hf=model.generate(**inputs,do_sample=True,temperature=.8,top_k=20,top_p=.9,min_p=.05,max_new_tokens=8,pad_token_id=tokenizer.eos_token_id)
torch.manual_seed(314);torch.cuda.manual_seed_all(314)
ids=inputs['input_ids'].clone()
with torch.no_grad():
for _ in range(8):
logits=model(input_ids=ids).logits[:,-1,:].float()
scores=filter_logits(logits,vec([.8],torch.float32),vec([20],torch.long),vec([.9],torch.float32),vec([.05],torch.float32))
chosen=torch.multinomial(torch.softmax(scores,dim=-1),1)
ids=torch.cat([ids,chosen],dim=-1)
if int(chosen.item())==tokenizer.eos_token_id: break
assert torch.equal(ids,hf)
print('Generación multinomial con misma semilla coincide con generate:',tokenizer.decode(ids[0],skip_special_tokens=True))
for V in (1024,8192,32768,131072):
x=torch.randn((4,V),device=device)
def bench(fn):
for _ in range(5): fn()
torch.cuda.synchronize();a=torch.cuda.Event(enable_timing=True);b=torch.cuda.Event(enable_timing=True);a.record()
for _ in range(30): fn()
b.record();torch.cuda.synchronize();return a.elapsed_time(b)/30
print('V=',V,'topk20 ms=',round(bench(lambda:torch.topk(x,20,dim=-1)),4),'sort ms=',round(bench(lambda:torch.sort(x,dim=-1,descending=True)),4))
print('GPU:',torch.cuda.get_device_name(),'; tiempos ilustrativos de primitivas, no de generación completa')
npm run lab and open the connection link.Exercises
Step 1 of 2. If U is uniform on (0,1), which transformation generates a standard Gumbel?
Step 1 of 1. Which expression results for the derivative?
import numpy as np
def top_p_filter(logits,p):
...