Module contents
Stage 8 of 8Advanced 100 min

Comprehensive evaluation and export

Compare base, SFT, DPO, and GRPO using the harness fixed in the first stage across domain, instruction following, mathematical reasoning, and general tasks, with intervals, length-controlled win rates, and alignment tax. Check contamination, merge adapters, and export the final quantized model for the local agent.

After this lesson you can

  • Run the full harness on all four variants with the same seeds and templates.
  • Calculate intervals, length-controlled win rates, and alignment tax.
  • Check contamination between training data and evaluations.
  • Merge, quantize, and export the final model and check that the exported version retains its metrics.

Before you start

A table that supports a decision

After fitting, you need to know whether a configuration improves, what it sacrifices, and how much it costs to serve. The post-training evaluation report compares base, SFT, DPO, and GRPO on the same tasks with the same tokenizer, template, subset, seed, and generation parameters. It identifies each variant’s checkpoint and lineage: a GRPO branch started from SFT is not automatically a continuation of DPO.

Use the CWE test frozen in p08-l04 only after fixing the selection. Also retain the small twelve-question memory exam from p08-l01: it is a different task with a strict integer extractor that must not be confused with the p08-l04 CWE extractor. General questions help measure forgetting; GSM8K evaluates one type of reasoning, and IFEval evaluates instructions with checkable constraints. None alone summarizes an assistant’s full utility. Tülu 3 distinguishes development and unseen evaluations, standard protocols, and decontamination; that design matters more than copying a number from another model.

Paired differences and alignment tax

For a task with the same nn questions across two variants, define di=bi−aid_i=b_i-a_i, where each indicator is one when the variant is correct. The accuracy difference is dˉ\bar d. A paired bootstrap resamples question indices and recomputes dˉ\bar d; it does not resample each variant separately because that would lose correlation between answers to the same problem. Record the seed, replicate count, and interval method. With small datasets or few disagreements, a percentile interval can be unstable; also report correct-to-incorrect and incorrect-to-correct counts.

When comparing many tasks and model pairs, some individual intervals can exclude zero by chance. Prespecify the primary comparison and distinguish it from exploratory analyses; for simultaneous claims, use an appropriate adjustment and explain its scope. Question bootstrap measures uncertainty in the evaluated sample under its resampling scheme; it does not itself include variation across training seeds or correct selection of the best configuration on the same set.

InteractiveWhat pairing gains
  • Same questions
  • Independent questions
200
20 %
Paired standard error (pp)3.16
Unpaired standard error (pp)5.00
This explicit model assumes accuracy 0.5 for both variants and equal probability of changing from correct to incorrect and vice versa. Move the disagreement rate: when answers usually agree, evaluating the same questions reduces uncertainty in the difference.

In that model, dd is the probability that variants disagree. Since per-question difference takes values −1,0,1-1,0,1 with mean zero, its variance is dd and paired standard error is d/n\sqrt{d/n}. For two independent samples with accuracy 0.5 it is 0.5/n\sqrt{0.5/n}. Pairing does not always reduce error: above 0.5 disagreement, correlation is negative and the difference can be less precise. The figure is a theoretical calculation, not the project’s results table.

One definition of mean alignment tax over KK tasks, with scores oriented so higher is better and expressed on the same scale, is

impuesto⁡=1K∑k=1K(sbase,k−sajustada,k).\operatorname{impuesto}=\frac1K\sum_{k=1}^K (s_{\rm base,k}-s_{\rm ajustada,k}).

A positive sign indicates average decline, not that every task worsens. Do not let the mean hide a serious regression on one task. If metrics use different scales or units, a raw mean has no interpretation: report each task and justify any transformation or weighting before viewing results.

There are two different choices when summarizing tasks. A per-task mean weights each score equally even if one has 2000 questions and another 200; a per-question mean weights the larger set more. Neither is universally correct. The first describes equally weighted tasks and the second a mixture of questions weighted by chosen set sizes. If sizes were cut for computational convenience, the second also inherits that arbitrary choice. Keep both metrics separate and declare weighting before deciding which result is better.

The paired interval has a concrete interpretation. If on 100 questions DPO improves ten relative to SFT and worsens eight, the observed difference is two percentage points: the 82 agreements do not directly contribute to the difference, but remain part of the sample. Discordant pairs show what changed and let you inspect whether new errors concentrate in a CWE family. An interval containing zero is compatible with small improvements and losses within its range; it does not prove variants equal. To decide equivalence, fix an acceptable margin and check whether the whole interval lies inside it.

In general, the interval for B−AB-A cannot be correctly obtained by subtracting endpoints of the marginal intervals for AA and BB. Results of both variants on the same advisory are correlated, and that correlation determines the difference’s variability. Two percentages and error bars alone cannot reconstruct it. The harness therefore retains IDs and per-question results, validates matching IDs, and resamples the same index set for both variants. When multiple questions come from the same source or component, the resampling unit must reflect that structure too.

An automatic judge may prefer longer answers. Dubois and colleagues propose a regression model to estimate preference with length difference fixed at zero. Here we use simple regularized logistic regression on length differences for binary-decided pairs: it shares that idea but does not reproduce the full AlpacaEval procedure. The estimate answers a counterfactual question under model assumptions; it does not guarantee that every length difference is bias. Show raw and controlled rates, observed length range, and agreement with a verifiable metric. Without length overlap, extrapolating to zero difference may be unreliable.

One way to investigate position bias is to present each pair twice, swapping which comes first. If the judge picks the same answer in both orders, record a consistent decision; if it always picks the first or returns uninterpretable output, mark the pair unresolved. Identical outputs can count as ties, with half a point per variant. Publish resolved and unresolved counts: a rate among only easy-to-decide cases may not describe the full set. Retaining each judgment’s original text permits review of parser failures and distinction from judge disagreements.

A regression-based length control does not replace that audit. Its estimate at zero length difference depends on model form and input data range. If the two answer types never have similar lengths, evaluating at zero extrapolates. Ties and unresolved answers require an explicit convention: binary regression excluding ties estimates preference among pairs that can receive binary labels, not the raw rate across all pairs. Resample at question level for uncertainty and show how many replicates could be fitted; very few observations from one class can make the fit unstable.

The table must also state what each score means. A multiple-choice question can compare continuation probabilities, while CWE extracts an identifier from generated text and the memory exam requires a complete integer. Changing extractor or template between variants changes the task. Report both ordinary accuracy and the length-normalized variant when the harness provides it, without presenting them as measuring exactly the same thing. In IFEval, strict and flexible satisfaction use different rules; keep results by instruction and by prompt to investigate failing constraints.

A product decision needs a prior criterion. For example, require that the main domain comparison show no degradation beyond a tolerable margin, that general tasks avoid a decline considered serious, and that latency fit the serving budget. Thresholds depend on context; they are not universal DPO or GRPO constants. The highest-mean variant can violate an important constraint, while another with a small difference and wide interval may need more data. Show these uncertainties alongside cost instead of hiding them in a single ranking.

In the documented run, DPO obtained CWE accuracy 0.8026 and SFT 0.7425; the paired difference was +0.0601, with 95% percentile interval [0.0172, 0.1030] over 233 questions. This is exploratory and unadjusted for other tasks and pairs. In DPO versus SFT judging, 227 cases were resolved and 6 unresolved; DPO’s raw score was 0.5286 counting identical answers as half a point. Length regression used only 23 binary-decided pairs and estimated 0.7868 [0.6166, 0.9559]; this is a different estimand, not a guaranteed bias correction. The full report retains every task, and the per-question judgment retains both orders.

InteractivePaired evaluation scorecard

Load the evaluation JSON report to compare variants.

The documented report appears by default; you can load another. Compare two variants per task and review raw and controlled judge rates. Intervals do not adjust for multiple comparisons.

Contamination and export

Search training and evaluations for exact and n-gram matches in source content, not just templates. Long n-grams can miss short texts or paraphrases; short ones can trigger on common phrases. Review matches and retain reasons for exclusion. No matches do not establish absence of semantic contamination or pretraining contamination, whose data may be unknown.

The next audit rereads files generated by p08-l04. Set P08_L04_DIR to that lesson’s directory before starting the lab. The code does not redo the split or choose exclusions; it independently compares its evidence against development and test and counts advisories too short to contain a 13-gram.

[ ]Audit CWE evidenceLocal GPU
import json, os, re
from pathlib import Path

folder = os.environ.get('P08_L04_DIR')
if not folder:
    print('Define P08_L04_DIR con el directorio creado en p08-l04.')
else:
    root = Path(folder)
    train = json.loads((root / 'train.json').read_text(encoding='utf-8'))
    held = sum((json.loads((root / f'{s}.json').read_text(encoding='utf-8'))
                for s in ('dev', 'test')), [])
    words = lambda text: tuple(re.findall(r'\w+', text.casefold()))
    train_texts = [words(row['evidence']) for row in train]
    held_texts = [words(row['text']) for row in held]
    held_exact = set(held_texts)
    held_grams = {t[i:i+13] for t in held_texts for i in range(len(t)-12)}
    exact = sum(t in held_exact for t in train_texts)
    shared = sum(any(t[i:i+13] in held_grams for i in range(len(t)-12)) for t in train_texts)
    short = sum(len(t) < 13 for t in held_texts)
    print('evidencias train:', len(train_texts), '· avisos dev y test:', len(held_texts))
    print('coincidencias exactas:', exact, '· evidencias con 13-gramas compartidos:', shared)
    print('avisos de evaluación con menos de 13 palabras:', short)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the pinned catalog reconstruction, 1053 training evidence texts share no exact text or 13-grams with 350 development and test advisories. However, 128 advisories have fewer than 13 words, so the 13-gram filter cannot find matches in them. Exact comparison remains active; semantic search and pretraining analysis remain outstanding.

The reproducible cross-audit extends this search. It separately compares 1053 SFT evidence texts and 7473 planned GRPO training questions with five sets: 233 CWE test advisories, 500 GSM8K questions, 541 IFEval instructions, 2376 ARC-Easy questions, and the first 2000 HellaSwag contexts. The documented run found no exact texts or shared 13-grams in those fields. It checks questions and contexts, not choices, answers, full templates, or pretraining corpora. In addition, 812 ARC-Easy questions and 265 HellaSwag contexts had fewer than 13 words, so that part of the filter could not trigger on them. No matches do not prove absence of contamination.

To repeat it, save the linked Python file, set P08_L04_DIR to the SFT lesson output and optionally P08_FINAL_DIR to a new report directory. The script pins the four public dataset revisions and writes match indices, not just totals. It requires datasets and access to those sets through cache or network. The audit considers all planned GSM8K training even while fitting is still running; it does not claim fitting has completed.

Example likelihood is another signal with different limits. For tokenized text, compute the mean log-probability of each token given its prefix under base and fitted models. An increase on training text may reflect fitting, but also differences in distribution, length, or difficulty; a high value on a test example does not prove it was in training. Keep distributions by split and length, identify model and tokenization, and inspect extremes. A stronger membership audit needs a suitable protocol and reference, not an improvised threshold on one score.

Adapter merging and export adds the LoRA update to the compatible base and compares merged logits with originals against an appropriate tolerance. If that check fails, record the discrepancy and do not present weights as numerically identical; conversion can investigate its effect but cannot erase the failure. The PEFT checkpoint format stores adapter parameters and configuration, not the base: identify and recover original weights too. Do not add adapters trained on incompatible bases or sequences without a combination rule and evaluation. Save hashes of base, adapter, and final artifact, converter version, quantization settings, license, and chat template. Quantization can change decisions near a threshold: reevaluate the served artifact with the same harness and compare the paired difference and interval.

The condition “difference smaller than the confidence interval” does not establish statistical equivalence. To justify equivalence, declare a practical margin δ\delta beforehand and check that an interval for the difference is contained in [−δ,δ][-\delta,\delta]. A wide interval including zero can also include unacceptable degradation.

First compare the active adapter with the merged base using identical tokens and precision. Inspect maximum and mean logit discrepancies, remembering that a small difference can change the chosen token when two logits are close. Then compare the served quantized artifact with the reference variant on identical questions. The serving engine may apply another template, stop at another end token, or transform logits before choosing; record and check these options before attributing all differences to quantization. Latency must state hardware, input and output length, concurrency, and whether prompt processing is included. A CPU measurement alone does not describe GPU deployment.

Merging and quantization solve different problems. LoRA represents a low-rank update that can be incorporated into compatible base weights; quantization changes how those weights are stored and approximated for inference. A GGUF file also identifies metadata used by the server to tokenize and apply the template. Separately save hashes of base, adapter, high-precision merge, and quantized file. If merged-versus-adapter comparison already fails, first resolve the base, modules, precision, or merge implementation before attributing the discrepancy to four-bit quantization.

Combining two adapters requires another decision. If they represent updates ΔW1\Delta W_1 and ΔW2\Delta W_2 on the same base W0W_0, one explicit linear combination is W0+λΔW1+(1−λ)ΔW2W_0+\lambda\Delta W_1+(1-\lambda)\Delta W_2. The base appears once, not twice. Each update must include its LoRA scaling and correspond to the same modules and dimensions; their sum can have rank greater than either summand. Weight combination does not linearly mix answers or guarantee retention of both branches’ capabilities, because the complete model is nonlinear. If testing a mixture, record λ\lambda, both adapters and their lineage, and reevaluate the mixture as a new variant.

Separately averaging the AA and BB matrices of two adapters and multiplying the averages is insufficient: the product introduces cross terms B1A2B_1A_2 and B2A1B_2A_1 absent from the desired sum. To preserve the sum exactly, materialize each BiAiB_iA_i with its scale and sum at sufficient precision, or concatenate factors with weights included and accept the rank increase. Compressing the sum to lower rank is another approximation requiring its own logit check and evaluation.

[ ]Combine two LoRA updatesBrowser
import numpy as np

A1, B1 = np.array([[1., 0.]]), np.array([[1.], [0.]])
A2, B2 = np.array([[0., 1.]]), np.array([[0.], [1.]])
weight = 0.5
desired = weight * (B1 @ A1) + (1-weight) * (B2 @ A2)
separate_average = (weight*B1 + (1-weight)*B2) @ (weight*A1 + (1-weight)*A2)
concatenated = np.concatenate([weight*B1, (1-weight)*B2], axis=1) @ np.concatenate([A1, A2], axis=0)
print('suma deseada:\n', desired, '\npromediar factores:\n', separate_average)
assert np.allclose(concatenated, desired) and not np.allclose(separate_average, desired)

In this example the correct sum is diagonal, with 0.5 on each diagonal. Averaging factors produces 0.25 in all four positions: off-diagonal values are interference absent from both original updates. This is a small-matrix calculation, not a mixture of trained checkpoints.

For the quantized comparison, declare the equivalence margin before opening results. A five-percentage-point margin, for example, accepts differences from -0.05 to 0.05 on the accuracy scale, while another application may need a smaller margin. An interval [-0.03, 0.02] lies inside it; [-0.09, 0.01] includes zero but also a nine-point drop and does not establish equivalence. The conclusion depends on the population and interval procedure; it does not guarantee equal latency, safety, or behavior on unmeasured tasks.

The final manifest must reconstruct the chain without relying on a folder name. Record exact model and data revisions, file hashes, adapter configuration, generation parameters, converter version, quantization type, and hardware. A seed is necessary to repeat random selection but alone does not identify data order or guarantee bitwise reproducibility across devices and libraries. A hash identifies examined content; it does not by itself prove when it was created or whether prior training used it. Keep the manifest with results and record corrections as a new version.

When the server processes a request, separate input preparation time from new-token generation time. An answer ending after two tokens may look fast even if processing a long prompt dominates cost; another can take longer because it produces many tokens despite faster per-token generation. When reporting a median or high percentile, state request count, warmup, and concurrency. Changes in context size, thread count, or GPU offload affect measurement and belong in the same report.

Reproducible lab

The final evaluator uses p08-l04 output (P08_L04_DIR), the p08-l06 sweep (P08_DPO_DIR), and p08-l07 adapter (P08_GRPO_DIR). Also download the GSM8K verifier and retain folder structure l08/evaluar.py and l07/gsm_verifier.py: the evaluator looks for it in the sibling directory. Set P08_FINAL_DIR as the results directory. Base Qwen2.5-0.5B-Instruct and dataset revisions are pinned in the script. The prepared environment uses PyTorch 2.11 with CUDA, Transformers 5.23, PEFT 0.21.3, datasets 5.2, lm-eval 0.4.13, and langdetect 1.0.9; per-row position selection requires a Transformers version accepting two-dimensional tensors in logits_to_keep. Download models and datasets beforehand or prepare them in cache. For example, in PowerShell after defining paths and activating the environment:

$env:P08_VARIANTS = 'base,sft'
python evaluar.py
$env:P08_VARIANTS = 'dpo,grpo'
python evaluar.py

If P08_VARIANTS is omitted, the script evaluates all four variants. The selector does not change samples or generation; it allows base and SFT to finish while the DPO sweep completes. The reproduced contract uses adaptadores/r64-att-0.0002 as the SFT branch and DPO’s initial reference; verify that folder exists and corresponds to the training compared. Beta selection uses development data only, and each variant’s manifest pins code, tokenizer, data, library versions, and adapter. CWE, general tasks, and memory save by stage; GSM8K and IFEval save every row. A partial result with a different manifest or incomplete final line requires review and is not silently accepted.

To split the run, P08_STAGE=fixed first computes and retains CWE, ARC-Easy, HellaSwag, and memory for selected variants without writing an incomplete final result. Then P08_STAGE=all reuses those stages and runs GSM8K and IFEval. Source and manifest must match between phases; splitting changes no extractors and does not replace the long evaluation.

In the documented run, the 500 GRPO GSM answers are reused from the p08-l07 post-evaluation: these are historical results, not new inference. Provenance and hashes record checks of questions, input tokens and masks, template, adapter, verifier, and greedy generation. The historical call uses another padding ID, but each input is one unpadded sequence. The earlier log pins the base revision but did not save a hash calculated during that run; aggregate times are not presented as comparable measurements against other variants.

For multiple-choice tasks the model processes the full context but projects to the vocabulary only positions predicting continuation tokens. This avoids allocating logits for unscored prefixes. Each option retains its sum of log-probabilities normalized over the full vocabulary, and acc_norm divides that sum by option character count. All four variants must use the same implementation; an algebraically equivalent optimization can introduce numerical differences across devices or batches.

For the full analysis, also run verosimilitud.py, then juez.py with the local server specified in its header and all four results available. The judge requires scikit-learn, checks both orders and server files, and retains per-question responses. informe.py verifies input hashes and produces report.json, which you can load in the interactive scorecard. The textual audit and likelihood probe answer different questions; neither alone proves absence of contamination.

Full outputs are available for base, SFT, DPO, and GRPO. They retain manifests, IDs, and answers, including the historical GRPO answers whose provenance is described above.

In the recorded likelihood probe, mean per-token log-probability change for SFT versus base was +0.2079 on 1053 training evidence texts and +0.0787 on 233 test texts. The populations and lengths differ; these descriptive means establish neither pretraining membership nor absence of contamination.

The judge uses both Q4_K_M files of Qwen2.5-7B-Instruct-GGUF at the script-pinned revision. Serve the first with llama.cpp b9354 and keep both in one directory; by default the client looks for a local server on port 11441. P08_JUDGE_URL permits another local URL. Before judging, the script checks alias, path, and both shard hashes, and records the served template.

During preparation, the first three ARC-Easy questions, first three HellaSwag questions, and at most the first eight IFEval instructions were mistakenly sent to a profiling run. The process stopped when the error was detected: option choices and times for seven generations were observed, but generated answers were not saved and accuracy was not calculated. This exposure limits interpretation of the held-out set, even though no configuration was selected by those accuracies. The main report retains all questions. Additionally, sensibilidad.py compared the same metrics and intervals with and without those items, counting the eighth instruction as exposed for caution. For example, strict IFEval DPO−SFT difference changed from 0.00185 with 541 questions to 0.00188 with 533. This analysis was decided after the incident and does not establish that the rest of the test is unbiased.

The full sensitivity analysis retains both sizes, estimates, and intervals for all four variants. The exposure must also be considered when interpreting later analyses of the same items.

For export, exportar.py needs llama.cpp code at the indicated revision, P08_LLAMA_SOURCE pointing to the converter directory, P08_LLAMA_QUANTIZE to the quantizer executable, and P08_EXPORT_DIR to a new output. Select the same DPO chosen in development, compare logits before and after merging, and create BF16 and Q4_K_M. Its usual device is CUDA; P08_EXPORT_DEVICE=cpu permits repeating BF16 merging on CPU and P08_EXPORT_THREADS sets threads. In the documented two-thread CPU run, the maximum logit changed at 27 of 1155 positions across eight development advisories; maximum absolute difference was 1.5625 and mean 0.05278. This measures merging in that arithmetic and does not establish CUDA parity. The quantizer fell back to alternative formats in 144 of 290 tensors, and the final file averaged 6.35 bits per weight: Q4_K_M is a mixed recipe, not exactly four bits for every tensor.

Then evaluar_gguf.py, with P08_LLAMA_SERVER pointing to the server, reevaluates the 233 CWE questions. Run it once with P08_GGUF_VARIANT=bf16 and once with P08_GGUF_VARIANT=q4; each output is compared with the reference adapter and stores its own answers and manifest for resumption. comparar_gguf.py then compares BF16 and Q4 with a paired interval and five-percentage-point margin fixed beforehand. Latency includes CPU server requests and may combine sessions, so do not directly compare it with a GPU run. Keep results, manifests, and logs together; an exported file alone does not establish retained quality.

On 233 questions, Q4 minus BF16 accuracy was −0.00858 with paired 95% interval [−0.02575, 0.00858], within the ±0.05 margin for this exam. Q4 answered one question correctly that BF16 missed and missed three BF16 got right. On eight development advisories, with warmup and two CPU threads, median per request was approximately 0.89 s in both formats; output lengths varied and the measurement includes prompt processing and HTTP. Maximum sampled server RSS was 1.12 GB for BF16 and 0.55 GB for Q4. These measurements on this machine do not guarantee equivalence on other tasks or devices.

Review per-question BF16 and Q4 results, the paired comparison, and the CPU benchmark. Those files do not include weights.

The BF16 versus Q4 benchmark needs psutil and uses the same CPU server and eight development advisories for both files, one after the other. It uses two threads by default; P08_LLAMA_THREADS sets another recorded count. It records request times, tokens, and sampled process RSS. It includes warmup and prompt processing; the median of eight requests is indicative and can vary with machine load. RSS is process memory, not GPU memory or necessarily the exact peak between samples.

Using the same file and server, agente_gguf.py tries three queries to a local card tool and saves both calls and answers. The documented run had 0 valid calls out of 3: the model returned only identifiers and did not request the tool. This is a small integration, not the p05 agent battery. That battery pins a specific 3B model; the file exported here comes from a 0.5B base and must retain its real identity and hash without passing as that model. A missing, malformed, or wrong-card call counts as a demonstration failure.

The demonstration log retains all three observed answers and the served file hash.

[ ]Tax by taskBrowser
import numpy as np
base = np.array([0.8, 0.7, 0.6, 0.9, 0.5])
ajustada = np.array([0.78, 0.72, 0.57, 0.88, 0.5])
caidas = base - ajustada
print('caídas por tarea:', caidas.round(3), '· media:', caidas.mean())

Exercises

CodeReport for two variants
Implement paired_report(a, b, reps, seed). Inputs are nonempty NumPy arrays of equal length with one score per question. Calculate mean difference b-a, the 2.5% and 97.5% percentile interval using reps resamples of shared indices, and a flag that is True only if the interval strictly excludes zero. Use default_rng(seed).
import numpy as np

def paired_report(a, b, reps, seed):
  ...
Shift+Enter to run
NumericFive tasks
Base scores are 0.80, 0.70, 0.60, 0.90, and 0.50; fitted scores are 0.78, 0.72, 0.57, 0.88, and 0.50. Calculate mean tax as base minus fitted on the 0-to-1 scale.
QuizChoose a variant
Suppose DPO wins more judge comparisons but ties on verifiable domain performance and produces longer answers. What decision is defensible?
QuizAn unexpected improvement
If GRPO improved on GSM8K, why check for contamination?
Key idea
The final table uses comparable conditions, paired differences, and verifiable provenance. A quantized model is ready for comparison only after evaluation under the same protocol as its unquantized version.