Module contents
Lesson 8 of 26Core 110 min

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

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.

InteractiveWindows and stride

Fixed teaching sequence over the A/B alphabet. Each target is scored once; the first position is excluded. A successive window reuses overlap as context without including it again in loss.

0A1A2B3B4A5A6B7A8B9B10B11A12B13A14A15B16B17A18A19A20B21B22A23B24A25B26B27A28A29B30B31A

Target 12: B; window [8, 16) and context used: B A. Colors distinguish used context and target; other window tokens do not affect this second-order model.

Explicit model: with empty context P(A)=0.5; with one token P(A)=0.7 if A and 0.3 if B; with two, P(A)=0.85 if equal and 0.25 if different. P(B)=1−P(A). PPL is exp of mean −ln P of the target. There is no training or real model measurement.

In disjoint windows the first target of each later window is calculated here with the empty-context distribution. A real causal model must specify BOS or exclude that target: conventions change the denominator. A smaller stride often provides more total context, but not necessarily at every position and does not guarantee lower PPL for each sequence. See the perplexity documentation.

8
4
12
Sequence PPL
2.273
Scored targets
31
Selected window
3
P(observed token)
0.750
Observe the context each target receives and what changes with window and stride.

Perplexity with finite memory

For targets xtx_t scored once, define ℓt=−log⁡pθ(xt∣ct)\ell_t=-\log p_\theta(x_t\mid c_t), where ctc_t is the context available under the protocol. Sliding-window perplexity is

PPL⁡=exp⁡ ⁣(1M∑t∈Sℓt),M=∣S∣.\operatorname{PPL}=\exp\!\left(\frac{1}{M}\sum_{t\in S}\ell_t\right),\qquad M=|S|.

A model with maximum context LL cannot see an arbitrarily long prefix. A window of up to LL tokens moves with stride s≤Ls\leq L. 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 s<Ls<L, overlap of up to L−sL-s 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 s=Ls=L 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 aia_i completes the same context cc and receives the sum of its token log probabilities conditioned on both context and the preceding part of the alternative:

si=∑j=1milog⁡pθ(aij∣c,ai,<j).s_i=\sum_{j=1}^{m_i}\log p_\theta(a_{ij}\mid c,a_{i,<j}).

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 mim_i of tokens or by UTF-8 bytes in the continuation. Another option subtracts an unconditional score log⁡pθ(ai)\log p_\theta(a_i) 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.

InteractiveFour ways to score an option

Toy context: “En la escena aparece” (“In the scene appears”). The four endings are sequence prefixes without scoring an end token. Each displayed piece is a token of the explicit model; adding “ hoy” (“ today”) recalculates its probability, rather than changing the length of a fixed measurement.

Sum
log P(ending | context)
luz ★−0.916
frío hoy −1.427
lluvia −1.609
nubes −2.303
Per token
log P(ending | context) / tokens
luz −0.916
frío hoy ★−0.714
lluvia −1.609
nubes −2.303
Per byte
log P(ending | context) / bytes
luz −0.229
frío hoy ★−0.143
lluvia −0.230
nubes −0.384
Unconditional
log P(ending | context) − log P(ending)
luz 2.079
frío hoy ★2.955
lluvia −0.405
nubes −1.792
luz
1 token · 4 bytes
log cond. −0.916 · log incond. −2.996
frío hoy
2 tokens · 10 bytes
log cond. −1.427 · log incond. −4.382
lluvia
1 token · 7 bytes
log cond. −1.609 · log incond. −1.204
nubes
1 token · 6 bytes
log cond. −2.303 · log incond. −0.511

Verifiable model: first-piece conditional probabilities are (0.4; 0.3; 0.2; 0.1) and unconditional probabilities (0.05; 0.05; 0.3; 0.6). After each first piece, conditional probability of “ hoy” is respectively (0.15; 0.8; 0.6; 0.4), and unconditional probability is 0.25. Each subsequent “ hoy” has probabilities 0.6 and 0.5 respectively; remaining mass belongs to other continuations. Logs are natural. Division by bytes includes the initial space. Each card’s bars use their own scale; do not compare lengths across rules.

Unconditional subtraction is a probability ratio with a stated unconditional context, not a universal correction. In a real tokenizer the boundary can change tokens; tokenize context and continuation jointly and declare how the boundary is assigned. See OLMES, section 3.3.

Option to lengthen
1
Sum
luz
Per token
frío hoy
Per byte
frío hoy
Unconditional
frío hoy
Compare sum, per-token mean, per-byte mean, and unconditional-score correction.

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 kk independent samples passes the tests. Given n≥kn\geq k generated samples of which cc pass, use

pass@k⁡^=1−(n−ck)(nk),\widehat{\operatorname{pass@k}}=1-\frac{\binom{n-c}{k}}{\binom{n}{k}},

with the convention that the numerator is zero when n−c<kn-c<k. 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.

InteractiveUnbiased pass@k

For a problem with probability p per sample, n independent attempts produce c successes with a binomial distribution. Bars are exact expectations across all possible c values, not results from generated code execution.

True value0.5563
Mean unbiased estimator0.5563
Mean naive estimator0.5182

Variance across sets of n samples: unbiased 0.046751; naive 0.043216. Lower variance does not remove bias. At k=1 both coincide; at p=0 or 1 variance is zero.

The target is 1−(1−p)ᵏ. The estimator from HumanEval is 1−C(n−c,k)/C(n,k), with zero ratio if n−c<k. The naive estimator replaces p with c/n in 1−(1−p)ᵏ. Results are averaged per problem; p can vary between problems. Unbiased interpretation requires independent samples from the same distribution for each problem and k≤n.

20
5
15 %
True pass@k
0.5563
Unbiased estimator bias
0.000000
Naive estimator bias
−0.038059
Compare the unbiased estimator and naive substitute under an explicit binomial model.

The proof uses sampling symmetry. Among (nk)\binom nk index selections, (n−ck)\binom{n-c}{k} contain no success. The complementary fraction is the average over all subsets of size kk of the indicator “at least one success”. If the nn generations are independent and identically distributed, any fixed subset of kk has probability 1−(1−p)k1-(1-p)^k 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 kk i.i.d. samples is no longer guaranteed.

By contrast, 1−(1−c/n)k1-(1-c/n)^k substitutes a noisy estimate for the unknown probability before applying a nonlinear function. For k>1k>1 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.

InteractiveOne metric, twenty prompts

Local test: first 20 questions from abstract_algebra, MMLU test; demonstrations come from dev. There are 20 configurations of separator, letters or numbers and example count and order. Labels are scored by log likelihood; the full answer is not evaluated. SmolLM2 is base and Qwen is Instruct: they differ in size and training. Both receive the same plain-text template without a chat template for Qwen.

No examples2/20 · 10.0 %
95% Wilson: 2.8 % to 30.1 % · scale 0 to 100%
0 truncated contexts of 20 · 0 unscored
Other model minus selected model, same template: 20.0 points on 20 common items.
2 examples, order forward6/20 · 30.0 %
95% Wilson: 14.5 % to 51.9 % · scale 0 to 100%
0 truncated contexts of 20 · 0 unscored · versus zero examples: 20.0 points on 20 paired items
Other model minus selected model, same template: −5.0 points on 20 common items.
2 examples, order reverse7/20 · 35.0 %
95% Wilson: 18.1 % to 56.7 % · scale 0 to 100%
0 truncated contexts of 20 · 0 unscored · versus forward order: 5.0 points on 20 paired items
Other model minus selected model, same template: −10.0 points on 20 common items.
1 example, order forward6/20 · 30.0 %
95% Wilson: 14.5 % to 51.9 % · scale 0 to 100%
0 truncated contexts of 20 · 0 unscored · versus zero examples: 20.0 points on 20 paired items
Other model minus selected model, same template: −10.0 points on 20 common items.

Range across formats is maximum minus minimum across all model configurations, not only the three or four shown; excluding truncations leaves some with different denominators. Wilson intervals are descriptive under a binomial model; the first 20 rows are not a representative random MMLU sample. Paired differences use only common IDs and preserve the same filters; they are not significance tests. Truncation can remove examples or context and confound format effects. There is no extrapolation to another model or guarantee that a template wins in other subjects.

Model and revision: HuggingFaceTB/SmolLM2-135M, 93efa2f097d58c2a74874c7e644dbc9b0cee75a2. Displayed matrices were measured with float32 parameters; the lab also permits bf16. Test and dev source: cais/mmlu, Dataset Viewer without immutable revision; answer fingerprints and IDs are in the lab-generated JSON. Seed 2008. The experiment changes example count and presence when comparing with zero; the order contrast compares the same two examples. One-example cases are measured only for the newline separator.

Another study: published format changes

Selected examples from table 1 of Sclar and colleagues. Each pair changes one format element on the same task; fields {} are replaced with corresponding text. The published difference for this pair is 78.3 points. The chart shows paper accuracies, not MMLU measurements or local lab results.

Format 1: 4.3 %
passage:{}
 answer:{}
0 %100 %
Format 2: 82.6 %
passage {}
 answer {}
0 %100 %

Pairs are examples selected for their differences, not a random sample of formats. They do not show that removing colons, adding spaces or changing case always improves evaluation. The paper fixed example set and order to isolate format; this table does not measure order effects.

Source: Sclar and colleagues, section 4.3 and table 1, CC BY 4.0 license. Tasks are from Super-NaturalInstructions and the table uses probability ranking. Intervals are not reconstructed: the table lacks paired successes needed to calculate them. Format comparison uses published figures per task and does not compare performance across tasks.

Separator
Labels
Model
HuggingFaceTB/SmolLM2-135M
Recorded formats
20
Range across formats
40.0 points
Truncation exclusion
Disabled
Examine data and conditions of each comparison before attributing variation to format.

For nn independent questions with observed proportion p^\hat p, the estimated standard error of accuracy is p^(1−p^)/n\sqrt{\hat p(1-\hat p)/n}. An approximate normal interval uses p^±1,96 EE\hat p\pm1{,}96\,\mathrm{EE}. 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 di=Ai−Bid_i=A_i-B_i for each question, not the difference between independently calculated intervals. The percentile bootstrap resamples indices and recomputes the mean of did_i, 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.

[ ]PythonBrowser
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.

[ ]Harness: perplexity, choices, and generationLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofAveraging subsets
Prove: Prove unbiasedness of pass@k for n i.i.d. generations of one fixed problem.
0
Let c be the number of correct generations and 1 ≤ k ≤ n.

Step 1 of 3. What does C(n−c, k) count?

NumericAccuracy precision
A model answers 612 of 1000 independent questions correctly. What is the estimated standard error of its accuracy, as a proportion?
NumericFive attempts
With n = 20 samples and c = 3 successes, calculate the unbiased pass@5 estimator.
CodeScore with a shared prefix
Implement score_choices(model, context, choices). model.encode_pair(context, choice) tokenizes jointly and returns (prefix, continuation), ID lists separated at a valid boundary. model.prepare(prefix) returns an immutable state and adds the agreed start if the prefix is empty; model.logprob(state, continuation) returns the continuation log-probability sum without modifying state. Verify that all conditioned alternatives share exactly the same prefix and prepare it once. For each choice return a dictionary with sum, token, byte, and unconditional: sum, sum divided by token count, sum divided by UTF-8 bytes of choice, and sum minus the option's log probability with empty context. Reject empty choices, empty options or tokenless continuations, and differing conditioned prefixes.
def score_choices(model, context, choices):
  pass
Shift+Enter to run
QuizFormat is also a decision
You want to evaluate MMLU with a small base model. Which design makes the result easier to interpret?
Key idea

Evaluation is a reproducible procedure: fix tokens, template, data, extraction, and metric; check a reference and communicate uncertainty and sensitivity.