Evaluating a base model: perplexity, benchmarks and your own harness
Evaluate base models with sliding-window perplexity, multiple-choice likelihood, generative extraction, pass@k, prompt sensitivity, and confidence intervals, and compare a custom harness with a reference.
After this lesson you can
- Calculate long-text perplexity with a sliding window and explain its dependence on window length and stride.
- Implement multiple-choice likelihood evaluation with token, byte, and unconditional-score normalizations.
- Choose between cloze and letter formats using evidence and model scale.
- Implement the unbiased pass@k estimator and prove its unbiasedness.
- Build an evaluation harness, compare it with lm-evaluation-harness, and report confidence intervals.
- Measure sensitivity to prompt format, example count, and ordering.
Before you start
- 20Causal language modeling objectiveText-to-text task format and promptingPretraining run monitoringTokenizer compression metrics
- 07PerplexityBits per byte
- 05Binomial proportion confidence intervalsBootstrap percentile and basic intervalsPaired design and paired test
- 01Permutations and combinationsBinomial theorem
- 21Temperature samplingTop-k samplingNucleus (top-p) sampling
A number needs a protocol
Two tables can both report “MMLU accuracy” while measuring different things. A question can use letters or each answer as a continuation, with or without examples, and different decision rules. Before interpreting a difference between models, identify examples, templates, and the exact operation. This lesson builds those operations and compares results against a reference implementation.
Perplexity seems simpler because it needs no human answer. Even there, however, we must choose which position is scored, how much context it gets, and how tokens are counted. The first figure lets you inspect those choices before reducing them to one number.
Perplexity with finite memory
For targets scored once, define , where is the context available under the protocol. Sliding-window perplexity is
A model with maximum context cannot see an arbitrarily long prefix. A window of up to tokens moves with stride . It keeps overlap as context but marks only new positions as targets. The first token of each window has no previous logit within that window. Count labels actually available after the causal shift, not window size or masked labels. If each fragment is evaluated independently, state what happens to the first token and document boundaries.
With disjoint windows some targets receive less context than with overlapping windows. This often worsens average loss in a good model, but is not a mathematical inequality for every model and text: extra context can increase the loss of an individual target or even the average. Hugging Face documentation shows a GPT-2 example with perplexity 19.44 at stride 1024 and 16.44 at stride 512. These are results of that configuration, not a monotonicity law.
To check an implementation, record each target’s global index, window start, and predicting logit. With , overlap of up to already processed tokens serves as context and is not rescored. To avoid an incorrect mean of means, accumulate the loss sum and valid-target count across all windows, then divide once. A final partial window usually has fewer targets. With and no extra start token, the first prediction of every window is lost. When comparing with an overlapping run, declare that difference in positions or align the evaluated set.
PPL is expressed per token: changing the tokenizer changes both denominator and prediction unit. To compare compression on the same texts, calculate bits per byte, declaring boundaries, special tokens, and context. Neither PPL nor bits per byte alone measures whether an answer is useful or true.
Scoring a continuation
In multiple choice by log-likelihood, each alternative completes the same context and receives the sum of its token log probabilities conditioned on both context and the preceding part of the alternative:
The sum is the logarithm of a joint probability and favors shorter alternatives when strings have very different lengths. Score normalization changes the decision rule: divide by the number of tokens or by UTF-8 bytes in the continuation. Another option subtracts an unconditional score under a fixed start convention to reduce the influence of prior preference for a frequent answer. None of these rules is universally correct: report it and compare it with the benchmark protocol.
The boundary between context and answer is a common source of errors. Tokenize the full concatenation: a leading space may belong to the answer token or change the last context token. Check that the tokenized prefix of the concatenation matches the prefix you intend to reuse. Offsets can detect a token crossing the character boundary, but do not by themselves assign a probability to part of that token. Choose and declare another convention or a valid common boundary. Concatenating two independent tokenizations can score a different sequence. With padding, exclude padding positions from both attention and total targets. A reused KV cache must correspond exactly to the common prefix and must not share mutable state across alternatives.
Unconditional correction is a probability ratio on a logarithmic scale, not a calibrated probability that an option is correct. It depends on how the continuation is represented without context, including BOS and spaces. Per-token mean depends on the tokenizer; per-byte mean also depends on the exact string, even with bytes as a common denominator. A different rule can therefore change the winning option without any of the four calculations being wrong. Break ties deterministically or state how they are resolved.
Letters, cloze, and extraction
Cloze versus letter format changes the observed task. In cloze you score each answer as a continuation. In letter format you show options and score, for example, “A” or “B” after the question. Recognizing the correct option and emitting its label are not necessarily the same capability. OLMES reports 26.5% with letters and 31.1% with cloze for Pythia-1B on MMLU in its setup, macro-averaged over 57 subjects. The contrast supports checking both formats for a small model, not assuming a given size always behaves the same way. Chance also depends on option count and protocol.
In generative tasks you do not choose from a fixed list. A template can include solved examples and ask for a continuation; fix decoding, maximum tokens, and stop condition before evaluation. Generative answer extraction turns output into the unit compared. For example, on GSM8K a declared pattern can extract a numeric answer. An overly permissive extractor may accept an incidental number; an overly strict one may reject an equivalent answer. Report extraction failures and retain original generations for audit.
Few-shot means including examples in the prompt, not training on them. Select them from an allowed split, retain their IDs and order, and avoid using the evaluated item as a demonstration. Share template and set across models when their interfaces allow it. If context length forces truncation or fewer examples, record the difference. Exact match after extracting a number does not prove intermediate reasoning is valid.
How many code samples suffice?
For each problem, the pass@k estimator asks for the probability that at least one of independent samples passes the tests. Given generated samples of which pass, use
with the convention that the numerator is zero when . Calculate the estimator per problem and then average across problems; do not pool all successes first. HumanEval presents this estimate and explains the importance of isolating generated-code execution. Here we do not execute generated code. A real evaluation needs effective process, network, resource, and file isolation appropriate to the environment.
The proof uses sampling symmetry. Among index selections, contain no success. The complementary fraction is the average over all subsets of size of the indicator “at least one success”. If the generations are independent and identically distributed, any fixed subset of has probability of containing a success. By linearity of expectation, the average has that expectation too. This does not require subsets to be independent of one another. If samples are correlated or their generation distribution changes, the conclusion for i.i.d. samples is no longer guaranteed.
By contrast, substitutes a noisy estimate for the unknown probability before applying a nonlinear function. For this generally introduces bias. The lab calculates both expectations exactly under the binomial distribution and checks boundary cases without giant factorials.
Sensitivity and uncertainty
Prompt sensitivity is metric variation when format, examples, or their ordering change while model and data are fixed. Change one condition at a time when attributing an effect. A standardized protocol such as OLMES makes template, example selection, and metric explicit; it does not remove every source of variation. Sclar and colleagues study sensitivity to formatting features in their own tasks and models, so their results should not automatically be transferred to MMLU.
For independent questions with observed proportion , the estimated standard error of accuracy is . An approximate normal interval uses . Near zero or one, or with small or dependent samples, seek an appropriate interval as in binomial intervals. If both models answer the same questions, resample success pairs to estimate uncertainty in their difference. If several items come from one document, the document can be the resampling unit. Prompt dispersion and sampling uncertainty are distinct sources and must not be confused.
In a paired comparison, the quantity of interest is for each question, not the difference between independently calculated intervals. The percentile bootstrap resamples indices and recomputes the mean of , retaining each pair’s agreements and disagreements. Its interpretation requires resampled units to reasonably represent the target population. If you explore many templates and publish only the winner, selection adds optimism even if that template’s interval was correctly calculated. Hold out data for selection or describe the whole search.
Lab: pass@k and paired comparisons
The first cell calculates the estimator using logarithms and expm1, compares its exact binomial expectation with the naive substitute, and calculates intervals for a small sample. Bootstrap keeps each question’s results paired. Its interval depends on available items and does not correct contamination or selection bias.
import math
import numpy as np
def pass_at_k(n, c, k):
if not (0 <= c <= n and 1 <= k <= n):
raise ValueError('Requiere 0 <= c <= n y 1 <= k <= n')
if n - c < k:
return 1.0
return -math.expm1(sum(math.log1p(-c/(n-j)) for j in range(k)))
def esperanza_binomial(n, k, p, estimador):
return sum(math.comb(n,c)*p**c*(1-p)**(n-c)*estimador(n,c,k)
for c in range(n+1))
def ingenuo(n, c, k):
return 1 - (1-c/n)**k
n,k,p = 20,5,0.15
ideal = 1-(1-p)**k
print('pass@1 y pass@5, n=20 c=3:', pass_at_k(20,3,1), pass_at_k(20,3,5))
print('Verdadero, insesgado, ingenuo:', ideal,
esperanza_binomial(n,k,p,pass_at_k), esperanza_binomial(n,k,p,ingenuo))
assert abs(esperanza_binomial(n,k,p,pass_at_k)-ideal) < 1e-12
assert pass_at_k(20,0,5) == 0 and pass_at_k(20,20,5) == 1
phat = 612/1000
se = math.sqrt(phat*(1-phat)/1000)
print('612/1000: exactitud, EE y semianchura normal:', phat, se, 1.96*se)
# Datos de ejemplo definidos aquí, no resultados de un modelo real.
a = np.array([1,1,1,0,1,0,1,0,1,0,1,0],dtype=float)
b = np.array([1,0,1,1,1,0,1,0,0,0,1,0],dtype=float)
rng = np.random.default_rng(2008)
indices = rng.integers(0,len(a),size=(2000,len(a)))
differences = (a[indices]-b[indices]).mean(axis=1)
print('Diferencia pareada y percentiles bootstrap:', (a-b).mean(),
np.quantile(differences,[.025,.975]))Lab: a reproducible harness
A harness should record model and revision, tokenizer, dependency versions, evaluated examples, template, number and order of demonstrations, normalization, and decoding. To compare with lm-evaluation-harness, start with the same items and check per-option scores before comparing aggregate accuracy. Preprocessing, spaces, truncation, or extraction can explain disagreement without either model changing. Reproduction requires matching relevant protocol details and checking the number against the specific source.
Install torch, transformers, tokenizers, datasets, and numpy locally. The program evaluates SmolLM2-135M base and Qwen2.5-0.5B base at pinned revisions. ORYON_QUICK=1 mode uses Qwen2.5-0.5B-Instruct, identified as post-trained, because that checkpoint is available for the test. In short mode each model can run separately with ORYON_QUICK_MODEL=smol, qwen, or mini. Without a filter, both HF models and any configured custom checkpoint are evaluated. Filtering is supported only in short mode. Models load separately and memory is released between them. HF weights use float32 by default; ORYON_EVAL_DTYPE=bf16 enables bfloat16 if supported. Precision is recorded and can change scores; pre-recorded figure measurements used float32. The custom checkpoint remains float32. A short test on few questions does not reproduce published figures or reliably estimate an entire benchmark.
HellaSwag, ARC-Easy, GSM8K, WikiText, and MMLU documents come from declared splits and revisions. ORYON_EVAL_MC, ORYON_EVAL_GSM, ORYON_EVAL_MMLU, and ORYON_EVAL_TEXT_CHARS limit the full experiment budget. Short mode can use ORYON_EVAL_SAMPLES with Dataset Viewer JSON to avoid large downloads; the report records URL and file hash without attributing a revision the viewer does not guarantee. First rows are not a random sample.
Set ORYON_L07_DATA_DIR and ORYON_L07_CHECKPOINT to add the previous lesson’s checkpoint. The adapter reproduces its MiniLlama and verifies manifest and tokenizer hashes; it does not treat that checkpoint as a Hugging Face model. Use only trusted checkpoints you own. If those paths are not configured, the report states that it was omitted. Architectures and tokenizers differ, so per-token PPL is not directly comparable across them.
Windows count every text token exactly once with an explicit initial token; context and stride are reported. Multiple choice encodes context and continuation jointly, rejects ambiguous boundaries, and reuses a prefix cache when the HF model permits. The first test compares the cache with direct teacher forcing. If difference exceeds the stated tolerance, caching is disabled and the reason recorded. Truncation reserves one extra position and uses the same prefix for all options, determined by the longest continuation; any truncation is recorded. Unconditional scoring uses the same continuation, including spaces moved from context. Sums, per-token and per-byte means, differences from unconditional score, and item IDs are saved. The custom checkpoint uses a direct path without key-value caching.
GSM8K uses two training examples, greedy decoding, and extraction of the last number in output, without evaluating expressions or executing code. Fix that rule and template before comparison; they are not presented here as the official GSM8K protocol. Twenty MMLU variants use the same questions and two models, explicit labels and separators, and recorded example count and order. They are not a representative benchmark sample; Wilson intervals describe uncertainty for the subset, not every possible bias.
If lm-eval is installed and compatible with transformers and its dependencies, log-likelihood pairs are compared with the same weights and tokenizer. For the custom MiniLlama, an HF inference wrapper is built and IDs of two short real fragments verified. The report retains differences or the compatibility error. Checking a few pairs does not reproduce a full lm-eval score.
In our short test with lm-eval 0.4.13, two HellaSwag-derived pairs per model had absolute differences under 0.00003 nats for both Hugging Face models and zero for MiniLlama. The latter used short context fragments. These are six pairs, not reproduction of a complete benchmark.
"""Evaluación causal reproducible, con modelos HF y checkpoint propio de m20-l07."""
import copy
import gc
import hashlib
import json
import math
import os
import re
from decimal import Decimal
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tokenizers import Tokenizer
SEED = 2008
QUICK = os.environ.get('ORYON_QUICK') == '1'
QUICK_MODEL = os.environ.get('ORYON_QUICK_MODEL', '').lower()
if QUICK_MODEL and (not QUICK or QUICK_MODEL not in ('smol', 'qwen', 'mini')):
raise ValueError('ORYON_QUICK_MODEL solo admite smol, qwen o mini con ORYON_QUICK=1')
SAMPLES = os.environ.get('ORYON_EVAL_SAMPLES')
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './oryon-eval'))
OUT.mkdir(parents=True, exist_ok=True)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
HF_DTYPE_NAME = os.environ.get('ORYON_EVAL_DTYPE', 'float32').lower()
if HF_DTYPE_NAME not in ('float32', 'bf16'):
raise ValueError('ORYON_EVAL_DTYPE debe ser float32 o bf16')
if HF_DTYPE_NAME == 'bf16' and DEVICE.type == 'cuda' and not torch.cuda.is_bf16_supported():
raise ValueError('La GPU disponible no admite bfloat16')
HF_DTYPE = torch.bfloat16 if HF_DTYPE_NAME == 'bf16' else torch.float32
torch.set_num_threads(1)
torch.manual_seed(SEED)
MODELS = [
('HuggingFaceTB/SmolLM2-135M', '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'),
(('Qwen/Qwen2.5-0.5B-Instruct', '7ae557604adf67be50417f59c2c2f167def9a775') if QUICK else
('Qwen/Qwen2.5-0.5B', '060db6499f32faf8b98477b0a26969ef7d8b9987')),
]
REVISIONS = {
'hellaswag': ('Rowan/hellaswag', 'default', 'validation', '218ec52e09a7e7462a5400043bb9a69a41d06b76'),
'arc': ('allenai/ai2_arc', 'ARC-Easy', 'validation', '210d026faf9955653af8916fad021475a3f00453'),
'gsm': ('openai/gsm8k', 'main', 'test', '740312add88f781978c0658806c59bc2815b9866'),
'gsm_train': ('openai/gsm8k', 'main', 'train', '740312add88f781978c0658806c59bc2815b9866'),
'mmlu_test': ('cais/mmlu', 'abstract_algebra', 'test', 'c30699e8356da336a370243923dbaf21066bb9fe'),
'mmlu_dev': ('cais/mmlu', 'abstract_algebra', 'dev', 'c30699e8356da336a370243923dbaf21066bb9fe'),
'wiki': ('Salesforce/wikitext', 'wikitext-2-raw-v1', 'test', 'b08601e04326c79dfdd32d625aee71d232d685c3'),
}
def file_sha(path):
h = hashlib.sha256()
with open(path, 'rb') as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def get_rows(name, limit):
"""En producción usa revisión fija; QUICK puede usar un JSON del visor con hash."""
if SAMPLES and (Path(SAMPLES) / f'{name}.json').exists():
path = Path(SAMPLES) / f'{name}.json'
data = json.loads(path.read_text(encoding='utf-8'))
return data['rows'][:limit], {**data['source'], 'file_sha256': file_sha(path)}
from datasets import load_dataset
repo, config, split, rev = REVISIONS[name]
ds = load_dataset(repo, config, split=split, revision=rev, streaming=True)
rows = []
for index, row in enumerate(ds):
rows.append({'row_id': index, **row})
if len(rows) >= limit:
break
return rows, {'dataset': repo, 'config': config, 'split': split, 'revision': rev, 'selection': f'primeras {limit} filas'}
# Igual que el modelo MiniLlama de la celda actual de m20-l07, sin importar su script de entrenamiento.
class RMSNorm(nn.Module):
def __init__(self, width):
super().__init__()
self.weight = nn.Parameter(torch.ones(width))
def forward(self, x):
return F.rms_norm(x, (x.shape[-1],), self.weight, 1e-5)
def rotary(x):
_, _, length, dim = x.shape
frequencies = 1.0 / (10000.0 ** (torch.arange(0, dim, 2, device=x.device, dtype=torch.float32) / dim))
angles = torch.arange(length, device=x.device, dtype=torch.float32)[:, None] * frequencies[None, :]
c, s = angles.cos()[None, None, :, :], angles.sin()[None, None, :, :]
even, odd = x[..., 0::2].float(), x[..., 1::2].float()
return torch.stack((even*c-odd*s, even*s+odd*c), dim=-1).flatten(-2).to(x.dtype)
class Block(nn.Module):
def __init__(self, width, heads, ff):
super().__init__()
self.heads = heads
self.norm1, self.norm2 = RMSNorm(width), RMSNorm(width)
self.qkv = nn.Linear(width, 3*width, bias=False)
self.proj = nn.Linear(width, width, bias=False)
self.up = nn.Linear(width, ff, bias=False)
self.gate = nn.Linear(width, ff, bias=False)
self.down = nn.Linear(ff, width, bias=False)
def forward(self, x):
b, t, d = x.shape
q, k, v = self.qkv(self.norm1(x)).chunk(3, dim=-1)
def split(z): return z.reshape(b, t, self.heads, d//self.heads).transpose(1, 2)
q, k, v = rotary(split(q)), rotary(split(k)), split(v)
attn = F.scaled_dot_product_attention(q, k, v, is_causal=True)
x = x + self.proj(attn.transpose(1, 2).contiguous().reshape(b, t, d))
h = self.norm2(x)
return x + self.down(F.silu(self.gate(h))*self.up(h))
class MiniLlama(nn.Module):
def __init__(self, vocab, width, layers, heads, ff):
super().__init__()
self.embedding = nn.Embedding(vocab, width)
self.blocks = nn.ModuleList(Block(width, heads, ff) for _ in range(layers))
self.norm = RMSNorm(width)
def forward(self, ids):
x = self.embedding(ids)
for block in self.blocks:
x = block(x)
return F.linear(self.norm(x), self.embedding.weight)
class Adapter:
def __init__(self, model, tokenizer, bos, eos, context, hf):
self.model, self.tokenizer, self.bos, self.eos, self.context, self.hf = model, tokenizer, bos, eos, context, hf
self.cache_checks = 0
self.cache_usable = True
self.cache_max_difference = None
self.cache_tolerance = None
def encode(self, text):
if self.hf:
return self.tokenizer.encode(text, add_special_tokens=False)
return self.tokenizer.encode(text, add_special_tokens=False).ids
def decode(self, ids):
if self.hf:
return self.tokenizer.decode(ids, skip_special_tokens=True)
return self.tokenizer.decode(ids, skip_special_tokens=False)
def logits(self, x, attention_mask=None, **kwargs):
if self.hf:
return self.model(input_ids=x, attention_mask=attention_mask, **kwargs).logits
return self.model(x)
def load_hf(name, revision):
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained(name, revision=revision)
model = AutoModelForCausalLM.from_pretrained(name, revision=revision, torch_dtype=HF_DTYPE).to(DEVICE).eval()
bos = tok.bos_token_id if tok.bos_token_id is not None else tok.eos_token_id
if bos is None: raise ValueError('El modelo requiere BOS/EOS explícito')
return Adapter(model, tok, int(bos), tok.eos_token_id, 256 if QUICK else 1024, True)
def load_l07(path, data_dir):
"""Cargar solo checkpoints propios de confianza: contienen objetos Python."""
data = Path(data_dir)
manifest = json.loads((data / 'manifest.json').read_text(encoding='utf-8'))
state = torch.load(path, map_location='cpu', weights_only=False)
if state['manifest_sha256'] != file_sha(data / 'manifest.json'):
raise ValueError('El checkpoint y manifiesto pertenecen a ejecuciones distintas')
token_file = data / manifest['tokenizer']['path']
if file_sha(token_file) != manifest['tokenizer']['sha256']:
raise ValueError('Tokenizador distinto del que usó el entrenamiento')
context, width, layers, heads, ff = state['config'][:5]
size = manifest['tokenizer']['model_vocab_size']
model = MiniLlama(size, width, layers, heads, ff).to(DEVICE).eval()
model.load_state_dict(state['model'], strict=True)
tok = Tokenizer.from_file(str(token_file))
return Adapter(model, tok, manifest['tokenizer']['eot_id'], manifest['tokenizer']['eot_id'], context, False)
def encode_pair(adapter, context, continuation):
"""Codifica conjuntamente; no asigna silenciosamente tokens de frontera ambiguos."""
nspaces = len(context) - len(context.rstrip())
if nspaces:
continuation = context[-nspaces:] + continuation
context = context[:-nspaces]
whole = adapter.encode(context + continuation)
prefix = adapter.encode(context)
if whole[:len(prefix)] != prefix:
raise ValueError('Frontera de tokenización ambigua: reformula el separador')
target = whole[len(prefix):]
if not target:
raise ValueError('Continuación vacía')
return (prefix or [adapter.bos]), target, continuation
@torch.inference_mode()
def batch_logprob(adapter, prefix, targets, reuse=True):
"""Puntuación teacher-forced. HF reutiliza KV de prefijo y agrupa continuaciones."""
max_target = max(map(len, targets))
if max_target >= adapter.context:
raise ValueError('Una continuación excede el contexto')
# Convención conservadora: reserva una posición más que el mínimo necesario.
# Todos los candidatos usan el mismo prefijo recortado por la opción más larga.
prefix = prefix[-(adapter.context - max_target):]
batch = len(targets)
used_cache = False
cache = None
if reuse and adapter.hf and adapter.cache_usable and len(prefix) > 1:
x = torch.tensor([prefix[:-1]], dtype=torch.long, device=DEVICE)
try:
output = adapter.model(input_ids=x, use_cache=True, logits_to_keep=1)
except TypeError:
output = adapter.model(input_ids=x, use_cache=True)
cache = copy.deepcopy(output.past_key_values)
if hasattr(cache, 'batch_repeat_interleave'):
cache.batch_repeat_interleave(batch)
used_cache = True
if used_cache:
width = max_target
rows = [[prefix[-1], *target[:-1]] + [adapter.bos] * (width-len(target)) for target in targets]
x = torch.tensor(rows, dtype=torch.long, device=DEVICE)
mask = torch.tensor([[1]*(len(prefix)-1+len(target)) + [0]*(width-len(target)) for target in targets], device=DEVICE)
logits = adapter.logits(x, attention_mask=mask, past_key_values=cache, use_cache=True).float()
offset = 0
else:
width = len(prefix) + max_target - 1
rows = [[*prefix, *target[:-1]] + [adapter.bos]*(max_target-len(target)) for target in targets]
x = torch.tensor(rows, dtype=torch.long, device=DEVICE)
mask = torch.tensor([[1]*(len(prefix)+len(target)-1)+[0]*(max_target-len(target)) for target in targets],device=DEVICE)
logits = adapter.logits(x, attention_mask=mask if adapter.hf else None).float()
offset = len(prefix)-1
logp = F.log_softmax(logits, dim=-1)
result = []
for i, target in enumerate(targets):
positions = torch.arange(offset, offset+len(target), device=DEVICE)
ids = torch.tensor(target, dtype=torch.long, device=DEVICE)
result.append(float(logp[i, positions, ids].sum()))
if used_cache and adapter.cache_checks < 1:
direct = batch_logprob(adapter, prefix, targets, reuse=False)
tolerance = 0.005*max(map(len, targets)) if HF_DTYPE_NAME == 'bf16' else 2e-4
adapter.cache_max_difference = max(abs(a-b) for a, b in zip(result, direct))
adapter.cache_tolerance = tolerance
adapter.cache_checks += 1
if adapter.cache_max_difference > tolerance:
adapter.cache_usable = False
print('Caché desactivada: diferencia en nats', adapter.cache_max_difference,
'mayor que tolerancia', tolerance, flush=True)
return direct
return result
@torch.inference_mode()
def score_choices(adapter, context, choices):
encoded = [encode_pair(adapter, context, choice) for choice in choices]
prefixes = [x[0] for x in encoded]
if any(x != prefixes[0] for x in prefixes):
raise ValueError('Las opciones no comparten el mismo contexto tokenizado')
targets = [x[1] for x in encoded]
totals = batch_logprob(adapter, prefixes[0], targets)
unconditional = []
for _, _, actual in encoded:
prefix, target, _ = encode_pair(adapter, '', actual)
unconditional.append(batch_logprob(adapter, prefix, [target])[0])
return [{'total': total, 'per_token': total/len(target),
'per_byte': total/len(actual.encode('utf-8')),
'pmi': total-base, 'tokens': len(target), 'bytes': len(actual.encode('utf-8')),
'unconditional': base, 'context_tokens':len(prefixes[0]),
'context_tokens_used':min(len(prefixes[0]), adapter.context-max(map(len, targets)))}
for total, target, (_, _, actual), base in zip(totals, targets, encoded, unconditional)]
@torch.inference_mode()
def window_ppl(adapter, text, stride):
"""BOS/EOT explícito; cada token del texto tiene exactamente un destino."""
ids = [adapter.bos] + adapter.encode(text)
if len(ids) < 2 or not 1 <= stride < adapter.context:
raise ValueError('Texto vacío o stride fuera de 1..contexto-1')
total, seen, next_target = 0.0, [], 1
while next_target < len(ids):
end = min(len(ids), next_target + stride)
start = max(0, end-adapter.context)
if start >= next_target: raise AssertionError('Se perdió el contexto del primer destino')
x = torch.tensor([ids[start:end-1]], dtype=torch.long, device=DEVICE)
logits = adapter.logits(x).float()[0]
positions = torch.arange(next_target-start-1, end-start-1, device=DEVICE)
target = torch.tensor(ids[next_target:end], dtype=torch.long, device=DEVICE)
total += float(F.cross_entropy(logits[positions], target, reduction='sum'))
seen.extend(range(next_target, end))
next_target = end
assert seen == list(range(1, len(ids)))
return {'tokens': len(seen), 'nll_nats': total, 'ppl': math.exp(total/len(seen)),
'bytes': len(text.encode('utf-8')), 'bits_per_byte': total/(math.log(2)*len(text.encode('utf-8'))),
'context': adapter.context, 'stride': stride, 'start_token_id': adapter.bos}
def extract_gsm(text):
"""Último número explícito; no evalúa expresiones ni ejecuta código."""
matches = re.findall(r'[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?', text)
if not matches: return None
return str(Decimal(matches[-1].replace(',', '')).normalize())
@torch.inference_mode()
def generate(adapter, prompt, max_new=64):
ids = [adapter.bos] + adapter.encode(prompt)
generated = []
for _ in range(max_new):
x = torch.tensor([ids[-adapter.context:]], dtype=torch.long, device=DEVICE)
token = int(adapter.logits(x)[0, -1].argmax())
if adapter.eos is not None and token == adapter.eos: break
ids.append(token)
generated.append(token)
return adapter.decode(generated)
def wilson(correct, n, z=1.96):
if n == 0: return None
p = correct/n
den = 1 + z*z/n
middle = (p+z*z/(2*n))/den
radius = z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
return [middle-radius, middle+radius]
def mc_item(name, row):
if name == 'hellaswag':
return row['ctx'].rstrip(), [' '+x for x in row['endings']], int(row['label'])
labels = row['choices']['label']
return 'Question: '+row['question']+'\nAnswer:', [' '+x for x in row['choices']['text']], labels.index(row['answerKey'])
def sensitivity_prompt(item, examples, separator, labels):
def render(row, show_answer):
choices = separator.join(f'{labels[i]}. {choice}' for i, choice in enumerate(row['choices']))
answer = ' '+labels[int(row['answer'])] if show_answer else ''
return 'Question: '+row['question']+separator+choices+separator+'Answer:'+answer
return (separator+separator).join([*(render(row, True) for row in examples), render(item, False)])
@torch.inference_mode()
def sensitivity(adapter, test_rows, dev_rows, one_shot_only=False):
cases = []
for sep_id, sep in [('newline','\n'), ('blank','\n\n'), ('pipe',' | ')]:
for label_id, labels in [('letters','ABCD'), ('numbers','1234')]:
if one_shot_only and sep_id != 'newline':
continue
plans = [(1, 'forward')] if one_shot_only else [(0, 'none'), (2, 'forward'), (2, 'reverse')]
for shots, order in plans:
examples = list(dev_rows[:shots])
if order == 'reverse': examples.reverse()
preds, correct, ids, skipped, contexts, used = [], [], [], [], [], []
for row in test_rows:
prompt = sensitivity_prompt(row, examples, sep, labels)
try:
pairs = [encode_pair(adapter, prompt, ' '+label) for label in labels]
if any(pair[0] != pairs[0][0] for pair in pairs[1:]):
raise ValueError('Las opciones no comparten el mismo prefijo tokenizado')
targets = [p[1] for p in pairs]
contexts.append(len(pairs[0][0]))
used.append(min(len(pairs[0][0]),adapter.context-max(map(len,targets))))
scores = batch_logprob(adapter, pairs[0][0], targets)
chosen = int(np.argmax(scores))
except ValueError as error:
chosen = None
skipped.append({'id': row['row_id'], 'reason': str(error)})
if len(contexts) <= len(ids):
contexts.append(None)
used.append(None)
ids.append(row['row_id'])
preds.append(chosen)
correct.append(None if chosen is None else chosen == int(row['answer']))
cases.append({'format_id':f'{sep_id}-{label_id}-{shots}-{order}',
'separator':sep_id, 'labels':label_id, 'shots':shots, 'order':order,
'item_ids':ids, 'correct':correct, 'predictions':preds, 'skipped':skipped,
'context_tokens':contexts, 'context_tokens_used':used,
'dev_item_ids':[row['row_id'] for row in examples]})
return cases
def compare_lm_eval(adapter, examples):
"""Compara loglikelihood por par; MiniLlama se envuelve sin cambiar pesos."""
try:
from lm_eval.api.instance import Instance
from lm_eval.models.huggingface import HFLM
except ImportError as error:
return {'status':'lm-eval no instalado o dependencias ausentes', 'detail':str(error)}
model, tokenizer, backend = adapter.model, adapter.tokenizer, 'default'
if not adapter.hf:
from transformers import PretrainedConfig, PreTrainedModel, PreTrainedTokenizerFast
from transformers.modeling_outputs import CausalLMOutput
# El ID añadido al tokenizer se corresponde exactamente con el EOT reservado.
# El adapter especial solo se usa para los dos pares siguientes sin ese literal.
special = '<oryon-eot>'
tokenizer = PreTrainedTokenizerFast(tokenizer_object=adapter.tokenizer,
bos_token=special, eos_token=special, pad_token=special)
if tokenizer.eos_token_id != adapter.eos or tokenizer.bos_token_id != adapter.bos:
raise ValueError('El EOT del adapter no coincide con el checkpoint')
class MiniConfig(PretrainedConfig):
model_type = 'oryon_mini_llama'
class MiniWrapper(PreTrainedModel):
config_class = MiniConfig
def __init__(self, base):
config = MiniConfig(vocab_size=adapter.eos+1, n_positions=adapter.context,
max_position_embeddings=adapter.context, is_encoder_decoder=False,
bos_token_id=adapter.bos, eos_token_id=adapter.eos, pad_token_id=adapter.eos)
super().__init__(config)
self.base = base
def forward(self, input_ids=None, attention_mask=None, **kwargs):
return CausalLMOutput(logits=self.base(input_ids))
model, backend = MiniWrapper(adapter.model).eval(), 'causal'
# Fragmentos reales breves de dos contextos HellaSwag, no ítems completos.
examples = [('A man is', ' sitting on a roof.'), ('A lady walks', ' to a barbell.')]
for context, choice in examples:
if (adapter.encode(context) != tokenizer.encode(context, add_special_tokens=False)
or adapter.encode(context+choice) != tokenizer.encode(context+choice, add_special_tokens=False)):
raise ValueError('El tokenizador del adapter altera uno de los pares')
lm = HFLM(pretrained=model, tokenizer=tokenizer, backend=backend, batch_size=1,
max_length=adapter.context, add_bos_token=False, softmax_dtype=torch.float32)
requests = [Instance(request_type='loglikelihood', doc={}, arguments=(context, choice), idx=i)
for i, (context, choice) in enumerate(examples)]
official = lm.loglikelihood(requests, disable_tqdm=True)
result = []
for (context, choice), (reference, greedy) in zip(examples, official):
ours = score_choices(adapter, context, [choice])[0]['total']
result.append({'context':context, 'continuation':choice, 'ours':ours,
'lm_eval':float(reference), 'difference':ours-float(reference),
'lm_eval_greedy':bool(greedy)})
tolerance = 0.005 * max(len(encode_pair(adapter, c, x)[1]) for c, x in examples) if adapter.hf and HF_DTYPE_NAME == 'bf16' else 3e-4
if any(abs(row['difference']) > tolerance for row in result):
raise AssertionError('El scoring difiere de lm-eval: revisar tokenización y contexto')
return {'status':'comparado', 'pairs':result,
'tolerance_nats':tolerance, 'adapter':'HF nativo' if adapter.hf else 'wrapper de inferencia para MiniLlama m20-l07'}
def evaluate_adapter(name, revision, adapter, data):
hellaswag, arc, gsm, gsm_train, wiki = (data[k] for k in ('hellaswag','arc','gsm','gsm_train','wiki'))
text = '\n'.join(row['text'] for row in wiki if row['text'].strip())
text = text[:int(os.environ.get('ORYON_EVAL_TEXT_CHARS', '600' if QUICK else '4096'))]
original_context = adapter.context
adapter.context = min(adapter.context, 64) if QUICK else adapter.context
try:
ppl = [window_ppl(adapter, text, stride) for stride in (1, max(1, adapter.context//2), adapter.context-1)]
finally:
adapter.context = original_context
mc = {}
comparisons = []
for task, rows in [('hellaswag',hellaswag), ('arc',arc)]:
items = []
for row in rows:
prompt, choices, gold = mc_item(task, row)
try:
values = score_choices(adapter, prompt, choices)
except ValueError as error:
items.append({'id':row['row_id'], 'skipped':str(error)})
continue
predictions = {key:int(np.argmax([x[key] for x in values]))
for key in ('total','per_token','per_byte','pmi')}
items.append({'id':row['row_id'],'gold':gold,'scores':values,'predictions':predictions})
if len(comparisons)<2:
comparisons.append((prompt,choices[0]))
valid = [x for x in items if 'gold' in x]
metrics = {}
for key in ('total','per_token','per_byte','pmi'):
hits = sum(x['predictions'][key] == x['gold'] for x in valid)
metrics[key] = {'correct':hits, 'total':len(valid), 'wilson95':wilson(hits,len(valid))}
mc[task] = {'items':items,'metrics':metrics, 'format':'continuación cloze, texto crudo; no es plantilla oficial lm-eval'}
gsm_results = []
for row in gsm:
demonstrations = ''.join('Question: '+r['question']+'\nAnswer: '+r['answer']+'\n\n' for r in gsm_train[:2])
prompt = demonstrations+'Question: '+row['question']+'\nAnswer:'
output = generate(adapter, prompt, max_new=16 if QUICK else 128)
gold = extract_gsm(row['answer'].split('####')[-1])
answer = extract_gsm(output)
gsm_results.append({'id':row['row_id'], 'gold':gold,'answer':answer,'correct':answer==gold,'generation':output})
hits = sum(row['correct'] for row in gsm_results)
try:
compare = compare_lm_eval(adapter, comparisons) if comparisons else {'status':'sin pares puntuables'}
except Exception as error:
compare = {'status':'falló la comparación', 'detail':f'{type(error).__name__}: {error}'}
if compare.get('status') == 'comparado':
print('lm-eval:', name, 'pares:', len(compare['pairs']),
'máxima diferencia absoluta en nats:',
max(abs(pair['difference']) for pair in compare['pairs']), flush=True)
else:
print('lm-eval:', name, compare['status'], flush=True)
return {'name':name,'revision':revision,'context':adapter.context,
'parameter_dtype':str(next(adapter.model.parameters()).dtype), 'ppl':ppl,'mc':mc,
'gsm':{'items':gsm_results,'correct':hits,'total':len(gsm_results),'wilson95':wilson(hits,len(gsm_results)),
'format':'2 ejemplos de train; decodificación greedy; último número; no es protocolo oficial'},
'lm_eval':compare, 'cache_checks':adapter.cache_checks,
'cache_validation':{'usable':adapter.cache_usable, 'max_difference_nats':adapter.cache_max_difference,
'tolerance_nats':adapter.cache_tolerance}}
def main():
max_mc = 4 if QUICK else int(os.environ.get('ORYON_EVAL_MC', '200'))
max_gsm = 2 if QUICK else int(os.environ.get('ORYON_EVAL_GSM', '50'))
max_mmlu = int(os.environ.get('ORYON_EVAL_MMLU', '20' if QUICK else '100'))
specs = {'hellaswag':max_mc, 'arc':max_mc, 'gsm':max_gsm, 'gsm_train':2,
'wiki':40 if QUICK else 2000, 'mmlu_test':max_mmlu, 'mmlu_dev':5}
data, sources = {}, {}
for key, count in specs.items():
data[key], sources[key] = get_rows(key, count)
results, sensitivity_models = [], []
selected_hf = [(index, spec) for index, spec in enumerate(MODELS)
if not QUICK_MODEL or (QUICK_MODEL == 'smol' and index == 0)
or (QUICK_MODEL == 'qwen' and index == 1)]
for index, (name, rev) in selected_hf:
print('Evaluando:', name, flush=True)
adapter = load_hf(name, rev)
results.append(evaluate_adapter(name, rev, adapter, data))
(OUT/f'model-{index}-partial.json').write_text(json.dumps(results[-1],ensure_ascii=False,indent=2),encoding='utf-8')
cases = sensitivity(adapter, data['mmlu_test'], data['mmlu_dev'])
cases += sensitivity(adapter, data['mmlu_test'], data['mmlu_dev'], one_shot_only=True)
sensitivity_models.append({'name':name,'revision':rev,'cases':cases})
(OUT/'prompt-sensitivity-partial.json').write_text(json.dumps(
{'seed':SEED,'dataset':sources['mmlu_test'],'dev_dataset':sources['mmlu_dev'],
'models':sensitivity_models},ensure_ascii=False,indent=2),encoding='utf-8')
del adapter
gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
local_data = os.environ.get('ORYON_L07_DATA_DIR')
local_checkpoint = os.environ.get('ORYON_L07_CHECKPOINT')
if QUICK_MODEL == 'mini' and not (local_data and local_checkpoint):
raise ValueError('Para ORYON_QUICK_MODEL=mini configura ORYON_L07_DATA_DIR y ORYON_L07_CHECKPOINT')
if local_data and local_checkpoint and QUICK_MODEL in ('', 'mini'):
adapter = load_l07(local_checkpoint, local_data)
results.append(evaluate_adapter('MiniLlama propio m20-l07',file_sha(local_checkpoint),adapter,data))
del adapter
gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
elif not local_data or not local_checkpoint:
print('MiniLlama omitido: especifica ORYON_L07_DATA_DIR y ORYON_L07_CHECKPOINT.',flush=True)
payload = {'seed':SEED,'quick':QUICK,'quick_model_filter':QUICK_MODEL or None,
'device':str(DEVICE),'hf_parameter_dtype':HF_DTYPE_NAME,'sources':sources,'models':results}
(OUT/'evaluation.json').write_text(json.dumps(payload,ensure_ascii=False,indent=2),encoding='utf-8')
sensitivity_data = {'seed':SEED,'hf_parameter_dtype':HF_DTYPE_NAME,'dataset':sources['mmlu_test'],'dev_dataset':sources['mmlu_dev'],
'selection':'primeras filas de abstract_algebra; no inferir todo MMLU',
'methods':'puntuación de etiquetas; 18 combinaciones de separador, alfabeto y orden, más dos de un ejemplo',
'models':sensitivity_models}
(OUT/'prompt-sensitivity-data.json').write_text(json.dumps(sensitivity_data,ensure_ascii=False,indent=2),encoding='utf-8')
print('Resultados:',OUT/'evaluation.json',flush=True)
print('Sensibilidad:',OUT/'prompt-sensitivity-data.json',flush=True)
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. What does C(n−c, k) count?
def score_choices(model, context, choices):
pass
Evaluation is a reproducible procedure: fix tokens, template, data, extraction, and metric; check a reference and communicate uncertainty and sensitivity.