Module contents
Lesson 3 of 31Core 100 min

Repeated sampling and aggregation: self-consistency, voting and coverage

Study repeated inference sampling and aggregation: best-of-N, self-consistency, weighted and universal voting, pass@k coverage and selection. Derive when voting converges, why aggregate accuracy can be nonmonotonic and how task difficulty affects coverage.

After this lesson you can

  • Implement self-consistency, weighted voting and universal self-consistency and compare with greedy decoding and best-of-N at equal token cost.
  • Derive majority-vote success probability and bound its error with Hoeffding’s inequality.
  • Measure pass@k coverage and estimate maj@k by sampling subsets without replacement.
  • Relate coverage-curve shape to problem difficulty distribution.
  • Explain why aggregate accuracy can fall as N grows and what is needed to use coverage.

Before you start

Many opportunities, one choice

Sampling an answer repeatedly can find a solution a single run missed. Finding and recognizing it are different tasks: a list may contain the correct answer yet a selector can choose an incorrect one. Self-consistency normalizes answers extracted from chains and returns the most frequent. Wang and colleagues proposed this strategy to approximate the marginal-answer mode from diverse trajectories rather than relying only on greedy decoding (paper).

For each problem fix model, prompt, temperature, top-p, token limit and the extractor from the previous lesson. If the same answer appears as 0.5 and 1/2, an extractor that does not unify them splits its votes. Decide beforehand how to handle failed extractions and ties; excluding them without reporting changes the denominator and can favor a condition.

Self-consistency relates to minimizing Bayes risk using exact-match utility: the answer matching the most samples maximizes empirical utility. Similarity to MBR decoding does not mean all textual utility reduces to exact match. For free-form answers a model can choose among similar candidates: universal self-consistency avoids a rigid extraction rule but introduces selector cost and bias (Chen and colleagues).

In best-of-N, a scorer rates each chain and the best is selected. Mean log-likelihood is one possible score, but expresses only how predictable the text was to the model under the stated policy; it does not guarantee correctness. Weighted voting sums weights per answer and can use an external score or weights derived from each chain. If already sampling from the policy and reweighting each occurrence by its probability, the same marginal estimate is not obtained: frequent trajectories receive extra weight twice. Compare methods including scoring, selection and input/output token costs.

The correct mode and sample size

Let pcp_c be the probability of the correct answer and pip_i those of mm possible incorrect answers. With NN independent samples, counts nc,n1,…,nmn_c,n_1,\dots,n_m have a multinomial distribution. Exact vote-win probability is

∑nc+∑ini=NN!nc!∏ini!pcnc∏ipini t(nc,n1,…,nm),\sum_{n_c+\sum_i n_i=N}\frac{N!}{n_c!\prod_i n_i!}p_c^{n_c}\prod_i p_i^{n_i}\,t(n_c,n_1,\ldots,n_m),

where tt is zero if another answer has more votes and, if the correct answer ties r−1r-1 answers at the maximum, is 1/r1/r under uniform tie-breaking. Here “majority” means plurality: it can win without exceeding half the votes. If pcp_c is the unique mode, the vote converges to correct; if an incorrect answer has strictly higher probability, it converges to failure. Probability ties require separate treatment.

InteractiveWhen does the vote succeed?
00.20.40.60.81Correct0.4B0.3C0.3
0.40
0.50
5
Exact0.447
Simulation0.461
ModeCorrect
The curve enumerates all three-answer compositions; independent simulation repeats the draw 5000 times. The control divides the remainder between B and C; ties are resolved uniformly.

Vote scaling admits a simple bound. If pc−pi≥δ>0p_c-p_i\ge\delta>0 for each alternative, define Xj=1X_j=1 if sample jj is correct, −1-1 if it is alternative ii and 00 otherwise. Its expectation is at least δ\delta and Xj∈[−1,1]X_j\in[-1,1]. By Hoeffding, P(ni≥nc)≤e−Nδ2/2P(n_i\ge n_c)\le e^{-N\delta^2/2}. Applying a union bound over the mm alternatives gives

P(el voto no elige la correcta)≤me−Nδ2/2.P(\text{el voto no elige la correcta})\le m e^{-N\delta^2/2}.

This is an upper bound that can exceed one if NN is small; it can be capped at one. Independence and positive margin are assumptions, not automatic properties of samples sharing context or seeds.

Coverage and selection

Repeated-sampling coverage asks whether at least one of kk answers is correct. For individual probability pp and independence it is 1−(1−p)k1-(1-p)^k, even if no selection rule can identify it. With nn samples and cc correct, the without-replacement pass@k estimator is

pass@k^=1−(n−ck)(nk),k≤n,\widehat{\mathrm{pass@}k}=1-\frac{\binom{n-c}{k}}{\binom nk},\qquad k\le n,

taking the numerator as zero when n−c<kn-c<k. The estimator averages all subsets of size kk; it does not require selecting one subset and discarding the rest. By contrast, maj@k estimates vote accuracy, for example by resampling subsets without replacement and resolving ties with a recorded seed. The gap between curves is opportunity left unused by imperfect selection.

Brown and colleagues observed coverage growth over several orders of magnitude and some selectors plateauing in their experiments (Large Language Monkeys). This is not a universal law for every model: difficulty distribution matters. If pp varies across problems according to a Beta with parameters α,β\alpha,\beta, mean coverage is 1−B(α,β+k)/B(α,β)1-B(\alpha,\beta+k)/B(\alpha,\beta) under conditional independence; problems with pp near zero require many more attempts. A fraction with p=0p=0 is never solved under the same policy.

InteractiveCoverage versus k
  • Beta model
  • 200 real problems
1.0
3.0
8
Hypothetical coverage0.727
Mean over 200 problems0.662
Samples per problem64
The Beta curve is hypothetical; the other averages the pass@k estimator over 200 GSM8K problems with 64 samples each. These are the first test-set problems, not a random sample.
InteractiveCoverage versus selection
  • Coverage
  • Vote
  • Weighted vote
  • Simulated verifier
0.80
0.80
Coverage, k=640.87
Simulated selection, k=640.45
Across 20 subsets drawn per problem and k from the 200 × 64 campaign, coverage, voting and weighted voting are compared. The verifier curve exactly averages independent simulated decisions that know labels. If it accepts no candidates, the selector chooses one randomly. 'No extraction' remains a category.

For weighting, the figure uses the exponential of each chain’s mean base-model log probability, stored to six decimals in the interactive resource: this is a descriptive score, not calibrated correctness probability or sequence probability under temperature and top-p. The simulated verifier uses the reference to assign each sample an acceptance probability at chosen rates and exactly averages independent decisions for each subset. It does not measure a real classifier and subsets introduce variation; the comparison shows the gap between coverage and selection.

Even aggregate vote accuracy can rise then fall. In an easy group with binary correct probability 0.7, more samples help; in a harder group with probability 0.45, the vote converges to error. Mixing groups can produce an interior maximum, as studied by Chen and colleagues. More coverage does not imply better selection. Raising temperature can increase diversity and lower per-sample quality: measure both instead of assuming diversity always helps.

InteractiveA mixture that can rise and fall
0.50
Best N shown17
Maximum accuracy shown0.649
Limit as N grows0.50
The curve calculates exact binary voting for odd N on a logarithmic scale. The limit is the fraction of easy problems, since each group has a different unique mode.

Laboratory: enumerate and resample

The next cell calculates exact multinomial probability for three answers and compares it with simulation. Ties were drawn uniformly in both procedures. Enumeration is useful for small NN; it grows quickly for many sizes or categories.

[ ]Exact and simulated votingBrowser
from math import factorial, exp
from random import Random

def exacto(n, probs):
    assert len(probs) == 3 and all(p >= 0 for p in probs) and abs(sum(probs)-1) < 1e-9
    total = 0.0
    for a in range(n+1):
        for b in range(n-a+1):
            cuentas = (a, b, n-a-b)
            mayor = max(cuentas)
            if a != mayor:
                continue
            masa = factorial(n)
            for cuenta, p in zip(cuentas, probs):
                masa *= p**cuenta / factorial(cuenta)
            total += masa / cuentas.count(mayor)
    return total

def simulado(n, probs, repeticiones=20000, semilla=42):
    rng = Random(semilla)
    aciertos = 0
    for _ in range(repeticiones):
        cuentas = [0, 0, 0]
        for _ in range(n):
            x = rng.random()
            cuentas[0 if x < probs[0] else 1 if x < probs[0]+probs[1] else 2] += 1
        mayor = max(cuentas)
        ganadores = [i for i, cuenta in enumerate(cuentas) if cuenta == mayor]
        aciertos += rng.choice(ganadores) == 0
    return aciertos / repeticiones

probs = [0.4, 0.3, 0.3]
print('Exacta:', round(exacto(5, probs), 5))
print('Simulada:', round(simulado(5, probs), 5))
delta = min(probs[0]-p for p in probs[1:])
print('Cota de error:', min(1.0, 2*exp(-5*delta**2/2)))
for n in (1, 5, 21, 99):
    mezcla = 0.5*exacto(n, [0.7, 0.3, 0]) + 0.5*exacto(n, [0.45, 0.55, 0])
    print('N', n, 'mezcla', round(mezcla, 4))

For already generated answers, this maj@k estimator draws subsets without replacement within each problem. Tie drawing is part of the estimator, not a model property. Bootstrap intervals must resample whole problems; treating each trajectory as an independent problem would artificially reduce between-task uncertainty.

[ ]Coverage and voting by subsetsBrowser
from math import comb
from collections import Counter
from random import Random

def pass_at_k(n, c, k):
    if not (0 <= c <= n and 1 <= k <= n):
        raise ValueError('n, c o k fuera de rango')
    return 1 - (comb(n-c, k) / comb(n, k) if n-c >= k else 0)

def maj_at_k(answers, correct, k, draws=1000, seed=42):
    if len(answers) != len(correct) or not answers:
        raise ValueError('Se necesita una referencia por problema')
    rng = Random(seed)
    successes = 0
    for candidates, target in zip(answers, correct):
        if not 1 <= k <= len(candidates):
            raise ValueError('k fuera del tamaño disponible')
        for _ in range(draws):
            counts = Counter(rng.sample(candidates, k))
            top = max(counts.values())
            winners = [answer for answer, count in counts.items() if count == top]
            successes += rng.choice(winners) == target
    return successes / (len(answers)*draws)

answers = [['A', 'A', 'B', 'C'], ['B', 'B', 'A', 'C']]
print('Cobertura primer problema, k=2:', pass_at_k(4, 2, 2))
print('Voto medio, k=2:', round(maj_at_k(answers, ['A', 'A'], 2), 3))

Local laboratory: generate and retain samples

The following design uses the first 200 GSM8K test problems, 64 samples per problem and Qwen2.5-1.5B-Instruct. It produces 12,800 continuations and requires GPU, time and log space. Each batch is saved for resumption after interruption. Sampling parameters and batch composition are part of the experiment; changing hardware, implementation or batch can change outputs even with the same seed. Recorded log probability is from the unprocessed base model, not the distribution altered by temperature, top-p and penalty. The final run uses batches of 32 and captures original logits at each step without storing the entire vocabulary matrix throughout generation. In an eight-sequence pilot, incremental capture differed by at most 0.000046 from retained original logits; later recomputation over the full sequence differed by up to 0.677 and is not used. The file rejects rows from another protocol. The first 888 samples obtained in the batch-8 pilot were retained separately and not mixed into the final set.

To analyze the documented run exactly, download the 12,800 compressed samples. The decompressed JSONL SHA256 is 8abb79c6265c9dca427004acdd7958ee02b54f0ef9454d05c2e04d224606d003. Decompress it in the working directory with Python:

python -c "import gzip,pathlib; pathlib.Path('muestras_200x64.jsonl').write_bytes(gzip.decompress(pathlib.Path('muestras_200x64.jsonl.gz').read_bytes()))"

The file includes text, extraction, log probability and cost for each trajectory; it contains public data and model outputs. To generate your own samples, run the cell in a different folder.

[ ]Local samples and scoringLocal GPU
import json, os, re, time
from decimal import Decimal, InvalidOperation
from pathlib import Path
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, LogitsProcessor, LogitsProcessorList

model_id = 'Qwen/Qwen2.5-1.5B-Instruct'
revision = '989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
data = load_dataset('openai/gsm8k', 'main', revision='740312add88f781978c0658806c59bc2815b9866')
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, dtype=torch.bfloat16).to('cuda').eval()
eos = model.generation_config.eos_token_id
eos = set(eos if isinstance(eos, list) else [eos])

def extraer(texto):
    numero = r'[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?![\d,]|\.\d)'
    hits = re.findall(r'####\s*\$?\s*(' + numero + r')', texto)
    if not hits: hits = re.findall(r'\\boxed\{\s*(' + numero + r')\s*\}', texto)
    if not hits: hits = re.findall(r'(?i)\b(?:the\s+)?answer\s+is\s*[:$]?\s*(' + numero + r')', texto)
    if not hits: hits = re.findall(r'(?i)\b(?:the\s+)?final\s+(?:number|answer)\s+(?:is\s*)?[:]?[\s]*\*{0,2}\$?\s*(' + numero + r')', texto)
    if not hits:
        m = re.fullmatch(r'\s*\$?\s*(' + numero + r')\s*(?:[A-Za-z%]+)?[.\s]*', texto)
        hits = [m.group(1)] if m else []
    try:
        return str(Decimal(hits[-1].replace(',', '')).normalize()) if hits else None
    except InvalidOperation:
        return None

class RawScores(LogitsProcessor):
    def __init__(self,batch):
        self.current=None;self.previous=None
        self.sums=torch.zeros(batch,device='cuda')
        self.active=torch.ones(batch,dtype=torch.bool,device='cuda')
    def hook(self,module,inputs,output):
        self.previous=self.current
        self.current=output[:,-1,:].detach().float().clone()
    def add(self,raw,token):
        value=raw.gather(1,token[:,None]).squeeze(1)-torch.logsumexp(raw,dim=-1)
        self.sums+=value*self.active
        for t in eos:self.active &= token!=t
    def __call__(self,input_ids,scores):
        if self.previous is not None:self.add(self.previous,input_ids[:,-1])
        self.previous=None
        return scores
    def finish(self,sequences):
        self.add(self.current,sequences[:,-1])
        return self.sums.cpu().tolist()

archivo = Path('muestras_200x64.jsonl')
previas = [json.loads(linea) for linea in archivo.read_text(encoding='utf-8').splitlines()] if archivo.exists() else []
hechos = {(r['problema'], r['muestra']) for r in previas}
if len(hechos) != len(previas):
    raise ValueError('Registros duplicados en el archivo')
lote_tamano = 32
if any(r.get('lote') != lote_tamano or r.get('puntuacion') != 'logits_originales_stream' for r in previas):
    raise ValueError('Archivo de otro protocolo: usa un archivo nuevo')
for indice in range(200):
    row = data['test'][indice]
    mensaje = 'Solve step by step. ' + row['question'] + '\nGive the final numerical answer on its own line as #### followed by the number.'
    base = tokenizer.apply_chat_template([{'role':'user', 'content':mensaje}], add_generation_prompt=True, return_tensors='pt')['input_ids'].to('cuda')
    for inicio in range(0, 64, lote_tamano):
        if all((indice, inicio+j) in hechos for j in range(lote_tamano)):
            continue
        if any((indice, inicio+j) in hechos for j in range(lote_tamano)):
            raise ValueError('Lote parcial: revisa el archivo antes de reanudar')
        entradas = base.repeat(lote_tamano, 1)
        torch.manual_seed(indice*64 + inicio)
        tracker = RawScores(lote_tamano)
        handle = model.lm_head.register_forward_hook(tracker.hook)
        tic = time.perf_counter()
        try:
            with torch.inference_mode():
                salida = model.generate(input_ids=entradas, attention_mask=torch.ones_like(entradas), do_sample=True,
                    temperature=0.8, top_p=0.9, top_k=0, repetition_penalty=1.1, max_new_tokens=256,
                    pad_token_id=tokenizer.eos_token_id, return_dict_in_generate=True,
                    logits_processor=LogitsProcessorList([tracker]))
                logps = tracker.finish(salida.sequences)
        finally:
            handle.remove()
        torch.cuda.synchronize()
        segundos = time.perf_counter()-tic
        generados = salida.sequences[:, entradas.shape[1]:].tolist()
        lote = []
        for j in range(lote_tamano):
            ids = generados[j]
            parada = next((i for i, token in enumerate(ids) if token in eos), None)
            longitud = parada+1 if parada is not None else len(ids)
            texto = tokenizer.decode(ids[:longitud], skip_special_tokens=True)
            lote.append({'problema':indice, 'muestra':inicio+j, 'pregunta':row['question'],
                'referencia':extraer(row['answer']), 'respuesta':extraer(texto), 'texto':texto,
                'logp_modelo_base':logps[j], 'tokens_entrada':base.shape[1], 'tokens_salida':longitud,
                'truncada':parada is None, 'semilla_lote':indice*64+inicio,
                'lote':lote_tamano,'puntuacion':'logits_originales_stream', 'segundos_lote_generacion_y_puntuacion':segundos})
        with archivo.open('a', encoding='utf-8') as f:
            f.write(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in lote))
            f.flush(); os.fsync(f.fileno())
        print('Problema',indice,'muestras',inicio+lote_tamano,'segundos',round(segundos,2),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The file contains one row per trajectory, not per independent problem. When repeating the experiment retain prompt, full configuration and software version with the file. Audit extraction before interpreting coverage or voting; here an unextracted output is retained as a separate voting category, not counted automatically correct. In the full 12,800-sample run, 8847 were unextracted and 5709 reached the output limit; these categories can overlap. pass@1 is 0.229 and pass@64 0.870; with 100 subsets per problem, voting at k=64 scores 0.123 and mean-log-probability selection 0.185. Problem bootstrap interval for pass@64 is [0.825, 0.910]. Extraction and grouping unextracted answers affect this gap, which should not be interpreted as a pure measure of mathematical ability.

Counts also show observed heterogeneity: 26 problems have no extracted success in 64, 55 have one to eight, 99 have nine to 32 and 20 have more than 32. Zero in this finite sample does not prove zero success probability; it may reflect chance, truncation or an answer the extractor did not recognize. The mean curve mixes these situations, so its shape alone does not identify a Beta difficulty distribution.

The next cell requires all 64 outputs for each of 200 problems. It calculates pass@k analytically and selection rules on 100 subsets per problem, including mean-log-probability selection and voting weighted by the exponential of that score. The bootstrap interval resamples problems, not trajectories. Its bands reflect variability among observed problems and chosen resampling noise; they do not make the first 200 problems representative by themselves.

[ ]Coverage, voting and bands by problemLocal GPU
import json, math
from pathlib import Path
from collections import defaultdict, Counter
from random import Random
from math import comb

def pass_at_k(n,c,k):
    return 1-(comb(n-c,k)/comb(n,k) if n-c>=k else 0)

filas = [json.loads(linea) for linea in Path('muestras_200x64.jsonl').read_text(encoding='utf-8').splitlines()]
grupos = defaultdict(list)
for fila in filas:
    grupos[fila['problema']].append(fila)
if set(grupos) != set(range(200)) or any(sorted(r['muestra'] for r in grupo) != list(range(64)) for grupo in grupos.values()):
    raise ValueError('Se necesitan exactamente 64 muestras distintas por problema')
aciertos = [sum(r['respuesta'] is not None and r['respuesta']==grupo[0]['referencia'] for r in grupo)
            for grupo in grupos.values()]
print('Problemas con 0, 1-8, 9-32 y 33-64 aciertos:',
      sum(c==0 for c in aciertos),sum(1<=c<=8 for c in aciertos),
      sum(9<=c<=32 for c in aciertos),sum(c>=33 for c in aciertos))

def elegir(masas, rng):
    mayor = max(masas.values())
    ganadores = [a for a, masa in masas.items() if abs(masa-mayor) < 1e-12]
    return rng.choice(ganadores)

rng = Random(123)
ks = [1, 2, 4, 8, 16, 32, 64]
por_problema = []
for indice in range(200):
    grupo = grupos[indice]
    referencia = grupo[0]['referencia']
    c = sum(r['respuesta'] is not None and r['respuesta'] == referencia for r in grupo)
    for k in ks:
        votos = ponderados = mejor = tokens = 0
        for _ in range(100):
            seleccion = rng.sample(grupo, k)
            cuentas = Counter(r['respuesta'] for r in seleccion)
            pesos = defaultdict(float)
            for r in seleccion:
                pesos[r['respuesta']] += math.exp(r['logp_modelo_base']/r['tokens_salida'])
            mayor = max(r['logp_modelo_base']/r['tokens_salida'] for r in seleccion)
            maximos = [r for r in seleccion if abs(r['logp_modelo_base']/r['tokens_salida']-mayor) < 1e-12]
            votos += elegir(cuentas, rng) == referencia
            ponderados += elegir(pesos, rng) == referencia
            mejor += rng.choice(maximos)['respuesta'] == referencia
            tokens += sum(r['tokens_entrada']+r['tokens_salida'] for r in seleccion)
        por_problema.append({'indice':indice, 'k':k, 'pass':pass_at_k(64, c, k), 'voto':votos/100,
                             'ponderado':ponderados/100, 'mejor_logp':mejor/100, 'tokens':tokens/100})

salidas = []
for k in ks:
    grupo = [r for r in por_problema if r['k'] == k]
    for metodo in ('pass', 'voto', 'ponderado', 'mejor_logp'):
        valores = [r[metodo] for r in grupo]
        promedio = sum(valores)/len(valores)
        boot = sorted(sum(rng.choice(valores) for _ in valores)/len(valores) for _ in range(1000))
        salida = {'k':k, 'metodo':metodo, 'media':promedio, 'intervalo_95':[boot[25], boot[974]],
                  'tokens_medios':sum(r['tokens'] for r in grupo)/len(grupo)}
        salidas.append(salida)
        print(salida)
Path('curvas_por_problema.json').write_text(json.dumps(por_problema, ensure_ascii=False, indent=2), encoding='utf-8')
Path('curvas_resumen.json').write_text(json.dumps(salidas, ensure_ascii=False, indent=2), encoding='utf-8')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
for metodo in ('pass', 'voto', 'ponderado', 'mejor_logp'):
    puntos = [r for r in salidas if r['metodo']==metodo]
    x = [r['tokens_medios'] for r in puntos]
    ax.plot(x,[r['media'] for r in puntos],marker='o',label=metodo)
    ax.fill_between(x,[r['intervalo_95'][0] for r in puntos],
                    [r['intervalo_95'][1] for r in puntos],alpha=.12)
ax.set(xscale='log',xlabel='Tokens medios de entrada y salida',ylabel='Acierto o cobertura',ylim=(0,1))
ax.legend(); fig.tight_layout(); plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

You can also run the batched selector with vLLM: download the selector and its launcher to the same directory. Retain muestras_200x64.jsonl from the previous cell and use python run_universal_vllm.py --model-path "$SNAPSHOT_15" --samples muestras_200x64.jsonl --output seleccion_universal.jsonl, where SNAPSHOT_15 points to pinned revision 989aa7980e4cf806f80c7fef2b1adb7bc71aa306. This BF16 backend uses a 17,408-token window to retain complete candidates and logs its own manifest; it does not assume bitwise equality with Transformers.

Studying universal self-consistency requires paying for an additional call that reads candidates. This cell uses one fixed subset per problem and kk, requests the number of the most consistent candidate and retains invalid choices. This is exploratory: repeating subsets and orders, as well as including that cost, is needed to compare with the previous 100 selections. The cell also measures one greedy answer per problem; one call does not have the same budget as kk calls.

[ ]Universal selection and greedy answerLocal GPU
from random import Random
import re, hashlib, transformers

def generar_uno(mensaje, max_new):
    entrada = tokenizer.apply_chat_template([{'role':'user', 'content':mensaje}],
        add_generation_prompt=True, return_tensors='pt')['input_ids'].to('cuda')
    with torch.inference_mode():
        out = model.generate(input_ids=entrada, attention_mask=torch.ones_like(entrada), do_sample=False,
            repetition_penalty=1.1, max_new_tokens=max_new, pad_token_id=tokenizer.eos_token_id)
    ids = out[0, entrada.shape[1]:].tolist()
    parada = next((i for i, t in enumerate(ids) if t in eos), None)
    if parada is not None: ids = ids[:parada+1]
    return tokenizer.decode(ids, skip_special_tokens=True), entrada.shape[1], len(ids)

selecciones = Path('seleccion_universal.jsonl')
manifiesto = selecciones.with_suffix('.protocol.json')
protocolo = {'modelo':model_id,'revision':revision,'torch':torch.__version__,
             'transformers':transformers.__version__,'decodificacion':'voraz',
             'repetition_penalty':1.1,'selector_max_new':32,'voraz_max_new':256,
             'lote':1,'muestras_sha256':hashlib.sha256(Path('muestras_200x64.jsonl').read_bytes()).hexdigest()}
if selecciones.exists() and not manifiesto.exists(): raise ValueError('Archivo sin manifiesto de protocolo')
if manifiesto.exists():
    if json.loads(manifiesto.read_text(encoding='utf-8')) != protocolo:
        raise ValueError('El protocolo o las muestras cambiaron: usa otro archivo')
else:
    manifiesto.write_text(json.dumps(protocolo,ensure_ascii=False,indent=2),encoding='utf-8')
previas = [json.loads(x) for x in selecciones.read_text(encoding='utf-8').splitlines()] if selecciones.exists() else []
hechos = {(r['indice'], r['k']) for r in previas}
if len(hechos)!=len(previas) or any(i not in range(200) or k not in [0,1,2,4,8,16,32,64] for i,k in hechos):
    raise ValueError('Registro duplicado o fuera de alcance')
for indice in range(200):
    grupo = sorted(grupos[indice], key=lambda r:r['muestra'])
    for k in [0, 1, 2, 4, 8, 16, 32, 64]:
        if (indice, k) in hechos: continue
        if k == 0:
            prompt = 'Solve step by step. ' + grupo[0]['pregunta'] + '\nGive the final numerical answer on its own line as #### followed by the number.'
            texto, entrada, salida = generar_uno(prompt, 256)
            resultado = {'indice':indice, 'k':0, 'respuesta':extraer(texto), 'texto':texto,
                         'tokens_total':entrada+salida}
        else:
            candidatos = Random(1000*indice+k).sample(grupo, k)
            lista = '\n\n'.join(str(j+1)+'. '+r['texto'] for j, r in enumerate(candidatos))
            prompt = 'Choose the candidate most consistent with the others. Return only its integer number.\nQuestion: ' + grupo[0]['pregunta'] + '\nCandidates:\n' + lista
            texto, entrada, salida = generar_uno(prompt, 32)
            m = re.fullmatch(r'\s*(\d+)\s*[.\s]*', texto)
            elegido = int(m.group(1))-1 if m and 1 <= int(m.group(1)) <= k else None
            respuesta = candidatos[elegido]['respuesta'] if elegido is not None else None
            resultado = {'indice':indice, 'k':k, 'respuesta':respuesta, 'texto':texto,
                         'muestras':[r['muestra'] for r in candidatos], 'elegido':elegido,
                         'tokens_total':entrada+salida+sum(r['tokens_entrada']+r['tokens_salida'] for r in candidatos)}
        resultado['referencia'] = grupo[0]['referencia']
        resultado['acierto'] = resultado['respuesta'] is not None and resultado['respuesta'] == resultado['referencia']
        with selecciones.open('a', encoding='utf-8') as f:
            f.write(json.dumps(resultado, ensure_ascii=False)+'\n'); f.flush(); os.fsync(f.fileno())
        print(indice, k, resultado['acierto'], flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the documented BF16/vLLM selector run with pinned Qwen2.5-1.5B-Instruct revision, all 200 problems were evaluated in eight conditions with complete candidates. The greedy answer solved 43/200, bootstrap interval [0.160, 0.275], with 144 unextracted answers and mean 335 tokens. Universal selection solved 14/200 at k=16k=16 and 4/200 at k=64k=64; at the latter size 165/200 outputs were not valid indices, and mean cost was 35,007 tokens including candidates and selection call. Many outputs returned a mathematical answer or explanation despite requesting an index. A standalone integer can also be ambiguous if it matches both an answer and an index: the protocol interprets it as an index. These failures limit conclusions about model capability; they show behavior of this particular system and format, not a general impossibility of universal self-consistency.

The next graph includes problem-bootstrap bars; pass is coverage with access to the reference, not a deployable selector. The greedy answer uses a different budget from the rest. Download the 1600 selection and greedy-answer rows, their manifest, coverage and vote summaries and universal summary.

Accuracy and coverage versus generation and selection cost, with per-problem intervals

An invalid choice is not equivalent to confidently choosing a wrong answer: it counts as operational failure and is reported separately. To compare costs, plot accuracy against tokens_total and include both candidate-generation tokens and the selector call. Equal kk does not imply equal budget.

[ ]Summarize universal selectionLocal GPU
resultados = [json.loads(linea) for linea in Path('seleccion_universal.jsonl').read_text(encoding='utf-8').splitlines()]
resumen_universal = []
for k in [0, 1, 2, 4, 8, 16, 32, 64]:
    grupo = [r for r in resultados if r['k'] == k]
    if sorted(r['indice'] for r in grupo) != list(range(200)):
        raise ValueError('Faltan problemas para k=' + str(k))
    rng = Random(99+k)
    valores = [int(r['acierto']) for r in grupo]
    boot = sorted(sum(rng.choice(valores) for _ in valores)/len(valores) for _ in range(1000))
    invalidos = sum(r.get('elegido') is None for r in grupo) if k else sum(r['respuesta'] is None for r in grupo)
    print('voraz' if k == 0 else 'universal k='+str(k),
          'acierto', sum(valores)/len(valores), 'IC bootstrap', (boot[25], boot[974]),
          'sin elección/extraída', invalidos,
          'tokens medios', sum(r['tokens_total'] for r in grupo)/len(grupo))
    resumen_universal.append({'k':k,'media':sum(valores)/len(valores),
                              'intervalo_95':[boot[25],boot[974]],
                              'tokens_medios':sum(r['tokens_total'] for r in grupo)/len(grupo)})

base = json.loads(Path('curvas_resumen.json').read_text(encoding='utf-8'))
plt.rcParams.update({'font.size': 12})
fig, ax = plt.subplots(figsize=(5.3, 4.2))
for metodo in ('pass','voto','ponderado','mejor_logp'):
    puntos = [r for r in base if r['metodo']==metodo]
    ax.errorbar([r['tokens_medios'] for r in puntos],[r['media'] for r in puntos],
                yerr=[[r['media']-r['intervalo_95'][0] for r in puntos],
                      [r['intervalo_95'][1]-r['media'] for r in puntos]],
                marker='o',capsize=2,label=metodo)
u = resumen_universal[1:]
ax.errorbar([r['tokens_medios'] for r in u],[r['media'] for r in u],
            yerr=[[r['media']-r['intervalo_95'][0] for r in u],
                  [r['intervalo_95'][1]-r['media'] for r in u]],marker='o',label='universal')
voraz = resumen_universal[0]
ax.errorbar([voraz['tokens_medios']],[voraz['media']],
            yerr=[[voraz['media']-voraz['intervalo_95'][0]],[voraz['intervalo_95'][1]-voraz['media']]],
            fmt='o',capsize=2,label='voraz')
ax.set(xscale='log',xlabel='Tokens medios de entrada y salida',ylabel='Acierto',ylim=(0,1))
ax.legend(fontsize=10);fig.tight_layout();plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofBound voting error
Prove: The correct answer has probability p_c and each of m alternatives at most p_c − δ, with positive δ. The N samples are independent.
0
For a fixed alternative, use a variable equal to 1 for the correct answer, −1 for that alternative and 0 otherwise.

Step 1 of 2. Which event covers defeat by an alternative?

Numeric
With five independent samples and probabilities 0.4 for the correct answer and 0.3 for each of two incorrect answers, what is the probability the vote wins with uniform tie-breaking?
Code
Implement maj_at_k_curve(answers, correct, ks, n_boot), returning a list with voting accuracy for each k. answers contains a list of samples per problem and correct its correct answer; sample subsets without replacement and break ties at random, using seed 42.
def maj_at_k_curve(answers, correct, ks, n_boot):
  pass
Shift+Enter to run
Code
Implement weighted_self_consistency(answers, weights): sum non-negative weights by answer and return the answer with the highest sum; in a tie return the first answer seen. Reject empty lists, unequal lengths, or negative weights.
def weighted_self_consistency(answers, weights):
  pass
Shift+Enter to run
Quiz
The correct answer appears with probability 0.35 and an incorrect answer with probability 0.40. What happens to the vote as N increases under independence and fixed probabilities?
Key idea
Coverage measures whether a correct sample exists; the vote or verifier determines whether you can select it.