Memory plan and baseline evaluation
Select an open base model of 0.5B to 3B parameters such as Qwen2.5 or SmolLM2 after reviewing its license, estimate what fits in 8 GB for full fine-tuning, LoRA, and QLoRA, and compare with measured memory. Before training, fix a baseline evaluation harness with general lm-evaluation-harness tasks and a custom evaluation for the chosen domain.
After this lesson you can
- Calculate memory for each fine-tuning method and verify it with real measurements.
- Choose and justify a base model, domain, and evaluation tasks.
- Configure lm-evaluation-harness locally with a fixed subset of general tasks.
- Build a domain evaluation with verifiable answers or a rubric.
Before you start
Adaptation begins before training
A GPU can load a model and still run out of memory on the first training step. Weights use only part of the budget: updating parameters also needs gradients, optimizer states, and backward-pass activations. Nominal capacity is not the free memory available to one process on a shared GPU. A useful plan states what it reserves, measures, and leaves out.
The second decision also precedes fitting: how can we recognize domain improvement without losing general capabilities? Fix examples, tasks, templates, metrics, and seeds before touching weights. An evaluation created after seeing generations may accidentally reward answers the model already gave.
The selector uses published dimensions of the 0.5B, 1.5B, and 3B variants. Changing architecture also changes layer count, width, and adapters. The indicator compares a subtotal with an ideal capacity reference; it does not predict whether a particular run will start.
Model, license, and input contract
We choose Qwen2.5-0.5B-Instruct as a candidate for a Spanish-language technical assistant. Its card states Apache-2.0 licensing and approximately 0.49 billion parameters. The model license does not replace review of data, dependency, and application licenses. Its published configuration specifies width 896, intermediate dimension 4864, 24 layers, 14 query heads, and two key-value heads. This is grouped attention, not three identical square matrices. We choose this scale to try all three methods on the same model; the larger variant serves as a budget comparison.
An identifier alone does not pin a model: record the exact weights and tokenizer revisions, library versions, and conversation template. Before evaluation, inspect tokenizer.chat_template and special IDs. For this instruction model use the same message format and generation suffix before and after fitting. A different template changes the token sequence and can change scores without weight changes.
Prepare the environment and local copy
The described tests used Python 3.13 on Windows, PyTorch with CUDA, Transformers, PEFT, bitsandbytes, and lm-eval. Create a separate environment; do not install these dependencies over the shared project environment. The following example pins tested versions; CUDA installation must match the system and driver. Download the snapshot identified by revision into a local directory. Also consult official PyTorch and lm-evaluation-harness instructions if changing platforms.
New-Item -ItemType Directory -Force labs/runs/p08-l01/cache, labs/runs/p08-l01/tmp | Out-Null
$env:HF_HOME = (Resolve-Path labs/runs/p08-l01/cache).Path
$env:PIP_CACHE_DIR = $env:HF_HOME
$env:TEMP = (Resolve-Path labs/runs/p08-l01/tmp).Path
$env:TMP = $env:TEMP
py -3.13 -m venv labs/runs/p08-l01/entorno
$py = (Resolve-Path labs/runs/p08-l01/entorno/Scripts/python.exe).Path
& $py -m pip install --index-url https://download.pytorch.org/whl/cu128 "torch==2.11.0+cu128"
& $py -m pip install "transformers==5.20.2" "peft==0.21.2" "accelerate==1.15.0" "huggingface-hub==2.3.0" "bitsandbytes==0.50.2" "lm-eval==0.4.13" "datasets==5.1.0"
& $py -c "from huggingface_hub import snapshot_download; snapshot_download('Qwen/Qwen2.5-0.5B-Instruct', revision='7ae557604adf67be50417f59c2c2f167def9a775', local_dir='labs/runs/p08-l01/qwen05')"
$env:P08_MODEL_PATH = (Resolve-Path labs/runs/p08-l01/qwen05).Path
$env:P08_PYTHON = $py
$env:P08_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775"
The local runner may start with another working directory, so exported paths are absolute and variables must be set before launching it. Set P08_RUN_MODE to full, lora, or qlora for the memory cell; use P08_RUN_HARNESS=1 or P08_RUN_EVAL=1 for evaluations. Run each test separately to avoid multiple model copies on the GPU. Transitive dependencies are not fully pinned, so also save pip freeze. A declared revision is a label; verify the hashes printed by cells too. Configure cache with HF_HOME and, offline, check the revisions actually retrieved.
The following check queries the selected interpreter without loading the model or using the GPU. It reports missing dependencies so you can complete installation before measuring.
import os, subprocess
interpreter = os.environ.get("P08_PYTHON")
if not interpreter:
print("Pendiente: define P08_PYTHON con la ruta del intérprete aislado.")
else:
program = '''
import importlib.metadata as metadata, json, sys
names = ("torch", "transformers", "peft", "accelerate", "huggingface-hub",
"bitsandbytes", "lm-eval", "datasets")
versions = {}
for name in names:
try:
versions[name] = metadata.version(name)
except metadata.PackageNotFoundError:
versions[name] = "no instalado"
print(json.dumps({"python": sys.version.split()[0], "paquetes": versions}, ensure_ascii=False))
'''
result = subprocess.run([interpreter, "-c", program], capture_output=True,
text=True, encoding="utf-8", check=True)
print(result.stdout)npm run lab and open the connection link.For example, in the same PowerShell terminal select $env:P08_RUN_MODE = "full" and $env:P08_CALIBRATE = "1" before launching npm run lab. For the next method restart the runner with the desired variables and keep the previous file. Do not activate all three measurement and evaluation variables simultaneously if the shared resource cannot accommodate successive workloads or other people are using it.
The chosen domain is training memory accounting: short Spanish questions with verifiable numeric answers. It is bounded and allows unit checks; it does not evaluate all model engineering. The held-out set is generated below by a fixed rule. A fitting corpus does not yet exist here; once built, its documents, examples, and templates must be separated from the held-out set before training. A very short artificial set is an initial test, not a reliable estimate of professional quality.
Separate persistent allocations and activations
In hypothetical full fine-tuning with bf16 weights and gradients, an fp32 master copy and two fp32 AdamW moments occupy per parameter
That excludes activations, temporaries, and CUDA context. This is a specific convention: with PyTorch AMP and fp32 parameters, those parameters may already be the master copy and a second should not be counted; state precision depends on the actual optimizer. Sharding states across devices or offloading to CPU also changes GPU memory. The calculation does not prove impossibility under every imaginable strategy.
Under that convention, a hypothetical 1.5-billion-parameter model exceeds card capacity with per-parameter allocations alone. The exercise asks you to calculate this; the chosen candidate is smaller. Training memory anatomy helps distinguish weight-file size from step peak memory.
For LoRA, a frozen matrix of shape d_out × d_in receives a factorized update of rank r. New parameters are r(d_in+d_out). Store frozen base weights, adapters, adapter gradients, and optimizer states for those parameters; activations remain necessary for their gradients. Hu and colleagues motivate that factorization, not guaranteed improvement for every domain or layer selection.
In QLoRA the base is stored quantized and gradients propagate to adapters. Dettmers and colleagues describe NF4 and double quantization among other techniques. Four bits per weight is an ideal count for the quantized portion: scales, unquantized layers, decompression, activations, and adapter states need additional memory. In particular, do not divide the full peak by four.
The interactive’s teaching model
Fix assumptions so the figure is reproducible. LoRA’s frozen base costs two bytes per parameter. QLoRA uses an ideal case where every parameter is NF4 and scales follow the double-quantization analysis in the QLoRA paper: four bits per parameter plus 8/64 + 32/(64*256) scale bits, divided by eight to obtain bytes. Actual embeddings, normalizations, or other layers may remain at higher precision. Full fine-tuning uses the previous 16 bytes. Adapters use two bytes of weight, two of gradient, and eight of moments per parameter without a master copy; change the count if your optimizer maintains one.
Activations are a partial estimate, not a measurement: it assumes one bf16 tensor of shape B × T × d is saved per block, totaling 2 × B × T × L × d bytes. The recomputation option assumes saving only one tensor of that shape; it is an illustrative extreme, not a library guarantee. Other activations and states remain even with recomputation. It does not explicitly include vocabulary logits, buffers, padding, kernel temporaries, or a quadratic attention matrix; materialized attention can change dependence on T. Recomputation trades operations for memory, but actual savings depend on implementation.
The visual blocks share a scale and values are in GiB, where one GiB is 2**30 bytes. The reference limit is hypothetical capacity, not free memory. The following calculation reproduces the estimate for any valid input:
GIB = 2**30
models = {
"0.5B": (896,128,4864,24,151936),
"1.5B": (1536,256,8960,28,151936),
"3B": (2048,256,11008,36,151936),
}
def plan_memory(size, rank, batch, tokens, mode, checkpoint=False):
if size not in models or rank <= 0 or batch <= 0 or tokens <= 0:
raise ValueError("Los tamaños deben ser positivos")
if mode not in ("full", "lora", "qlora"):
raise ValueError("Modalidad desconocida")
d, kv, ff, layers, vocab = models[size]
n = vocab*d + layers*(2*d*d+2*d*kv+3*d*ff+3*d+2*kv)+d
adapters = layers*rank*(2*(2*d)+2*(d+kv)+3*(d+ff))
quant_bytes = .5 + (8/64+32/(64*256))/8
frozen = 0 if mode == "full" else n*(2 if mode == "lora" else quant_bytes)
trained = n*16 if mode == "full" else adapters*12
activation = 2*batch*tokens*d*(1 if checkpoint else layers)
return {"base":frozen, "entrenables":trained, "activaciones":activation,
"adaptadores":adapters, "parametros":n, "total":frozen+trained+activation}
for size in models:
for mode in ("full", "lora", "qlora"):
row = plan_memory(size,16,1,1024,mode)
print(size, mode, {k:round(v/GIB,4) for k,v in row.items()
if k not in ("adaptadores", "parametros")},
"parametros:",row["parametros"],"adaptadores:",row["adaptadores"])
print("controles: rango 4 a 64 paso 4; secuencia 256 a 4096 paso 256; "
"microlote 1 a 4 paso 1; referencia 8 GiB")Do not calibrate the table to one measurement and treat it as valid for all sizes. The experimental goal is to compare a plan fixed before the step with that configuration’s peak. The project requires relative error below 15% for each method: if missed, retain prediction, measurement, difference, and investigated cause. The preceding figure is not that validation and is not presented as such.
What measuring the peak means
torch.cuda.max_memory_allocated reports peak tensor memory allocated by the process since the last statistics reset. memory_reserved reflects allocator-managed blocks; nvidia-smi may include context, other libraries, and other processes. These quantities are not interchangeable. PyTorch documents these metrics.
For a useful comparison, start each method in a new process and record versions, model and revision, precision, microbatch, length, and recomputation option. Synchronize CUDA before reading, reset statistics before the measured segment, and record the peak during loading, forward, backward, and the first optimizer step. Adam may create its moments on the first step, so measuring loading or forward alone underestimates training. Document whether the peak includes the already-loaded model and whether warmup occurred.
An out-of-memory error is not a numeric peak measurement: it indicates the run did not reach the step. On a shared GPU also record free memory and other occupancy; if other processes cause failure, wait and retry without changing configuration. If the chosen persistent subtotal alone exceeds physical capacity, failure is consistent with the estimate but still is not a measured peak. Release objects and CUDA cache when each process ends.
The GPU lab requires selected weights, PyTorch with CUDA, Transformers, and PEFT; QLoRA also needs a compatible bitsandbytes version. Official bitsandbytes installation details platforms and requirements. Measure all three methods with the same model and configuration for comparison; the estimate alone does not validate the project threshold. Do not use the bars as experimental results.
The test measures one step with random tokens, not training quality or performance. To compare with the plan, adapt it to dtypes and states actually produced by optimizer.state instead of assuming the example’s master copy if the optimizer does not use one. Also save errors from missing dependencies or exhausted memory. One sequence and one step do not characterize all lengths or complete training.
The next cell runs the test in isolation when P08_RUN_MODE and P08_MODEL_PATH are set before starting the runner. For QLoRA, P08_PYTHON can select an isolated interpreter with bitsandbytes; otherwise the current interpreter is used. Without run variables the cell marks the result pending. The process ends and releases tensors afterward; record status and revisions to repeat the comparison. Output includes the interactive subtotal and its error against the peak, but retains the plan’s master-copy and fp32-moment assumptions: the test’s AdamW may use other dtypes for full fitting. Error therefore includes a convention difference as well as omitted activations and temporaries.
With P08_CALIBRATE=1, the cell also makes an empirical forecast: it separately measures lengths 128 and 512, linearly interpolates their peaks, and compares the prediction with a third run at length 384. Each includes loading and the first AdamW step. Lengths were chosen after testing another configuration, so this analysis is exploratory; the third measurement is not used to fit the line. Do not transfer the result to another batch, model, version, or sequence range without validation. A kernel switch, temporary allocation, or loading peak can break the linear approximation.
import json, os, sys, subprocess, time
from pathlib import Path
mode = os.environ.get("P08_RUN_MODE")
model_path = os.environ.get("P08_MODEL_PATH")
if not mode or not model_path:
print("Pendiente: define P08_RUN_MODE y P08_MODEL_PATH para medir.")
else:
if mode not in ("full", "lora", "qlora"):
raise ValueError("Modalidad desconocida")
program = r'''
import gc, hashlib, importlib.metadata, json, os, torch
from pathlib import Path
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
mode, path = os.environ["P08_RUN_MODE"], os.environ["P08_MODEL_PATH"]
if not torch.cuda.is_available():
raise RuntimeError("La medición necesita CUDA")
model = optimizer = tokens = loss = None
try:
torch.cuda.empty_cache()
torch.cuda.synchronize()
free, capacity = torch.cuda.mem_get_info()
torch.cuda.reset_peak_memory_stats()
torch.manual_seed(42)
options = {"local_files_only":True, "dtype":torch.bfloat16}
if mode == "qlora":
options["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True)
options["device_map"] = {"":0}
model = AutoModelForCausalLM.from_pretrained(path, **options)
cfg = model.config
sizes = {(896,4864,24,14,2):(896,128,4864,24),
(1536,8960,28,12,2):(1536,256,8960,28),
(2048,11008,36,16,2):(2048,256,11008,36)}
signature = (cfg.hidden_size, cfg.intermediate_size, cfg.num_hidden_layers,
cfg.num_attention_heads, cfg.num_key_value_heads)
if signature not in sizes or cfg.vocab_size != 151936 or not cfg.tie_word_embeddings:
raise ValueError("Esta comparación requiere una arquitectura Qwen2.5 del plan")
if mode != "qlora":
model = model.to("cuda")
if mode != "full":
if mode == "qlora":
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False)
config = LoraConfig(r=16, lora_alpha=32, task_type="CAUSAL_LM",
target_modules=["q_proj","k_proj","v_proj","o_proj",
"gate_proj","up_proj","down_proj"])
model = get_peft_model(model, config)
model.config.use_cache = False
optimizer = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=1e-4)
length = int(os.environ["P08_TOKENS"])
tokens = torch.randint(0, model.config.vocab_size, (1,length), device="cuda")
loss = model(input_ids=tokens, labels=tokens).loss
loss.backward()
optimizer.step()
torch.cuda.synchronize()
state_bytes = {}
for state in optimizer.state.values():
for value in state.values():
if torch.is_tensor(value):
name = str(value.dtype)
state_bytes[name] = state_bytes.get(name,0) + value.numel()*value.element_size()
versions = {name:importlib.metadata.version(name) for name in ("torch","transformers","peft")}
if mode == "qlora":
versions["bitsandbytes"] = importlib.metadata.version("bitsandbytes")
# El subtotal se fijó antes del paso y no incorpora todos los buffers.
d, kv, ff, layers = sizes[signature]
vocab, rank = cfg.vocab_size, 16
n = vocab*d + layers*(2*d*d+2*d*kv+3*d*ff+3*d+2*kv)+d
adapters = layers*rank*(2*(2*d)+2*(d+kv)+3*(d+ff))
quant_bytes = .5+(8/64+32/(64*256))/8
frozen = 0 if mode == "full" else n*(2 if mode == "lora" else quant_bytes)
trained = n*16 if mode == "full" else adapters*12
predicted = frozen + trained + 2*1*length*d*layers
measured = torch.cuda.max_memory_allocated()
identities = {}
for file in sorted(Path(path).glob("*.safetensors")):
digest = hashlib.sha256()
with file.open("rb") as f:
for chunk in iter(lambda: f.read(8*1024*1024), b""):
digest.update(chunk)
identities[file.name] = digest.hexdigest()
if not identities:
raise ValueError("Faltan archivos safetensors de la copia local")
print(json.dumps({"modo":mode,"revision_declarada":os.environ.get("P08_REVISION","no declarada"),
"pesos_sha256":identities,"configuracion":signature,
"versiones":versions,"libre_inicial":free,
"capacidad":capacity,"asignado_pico":measured,
"reservado_pico":torch.cuda.max_memory_reserved(),"estados_adam":state_bytes,
"entrenables":sum(p.numel() for p in model.parameters() if p.requires_grad),
"subtotal_previsto":predicted,
"error_relativo_subtotal":abs(predicted-measured)/measured,
"batch":1,"tokens":length,"checkpointing":False},ensure_ascii=False))
finally:
del optimizer, model, tokens, loss
gc.collect()
torch.cuda.empty_cache()
'''
interpreter = os.environ.get("P08_PYTHON", sys.executable)
lengths = [128,512,384] if os.environ.get("P08_CALIBRATE") == "1" else [256]
records = []
predicted = None
for length in lengths:
if len(records) == 2:
low, high = records
if (low["pesos_sha256"] != high["pesos_sha256"] or
low["configuracion"] != high["configuracion"] or
low["versiones"] != high["versiones"]):
raise ValueError("La identidad o el entorno cambió en la calibración")
predicted = low["asignado_pico"] + (length-low["tokens"])*(
high["asignado_pico"]-low["asignado_pico"])/(high["tokens"]-low["tokens"])
print("predicción anterior a la validación:",predicted)
env = dict(os.environ,PYTHONUTF8="1",P08_TOKENS=str(length))
for attempt in range(2):
result = subprocess.run([interpreter,"-c",program], env=env,
capture_output=True,text=True,encoding="utf-8",timeout=600)
if result.returncode == 0:
break
if attempt == 0 and "out of memory" in result.stderr.lower():
print("CUDA sin memoria: se espera antes de repetir la misma configuración.")
time.sleep(60)
continue
raise RuntimeError("Medición no terminada; conserva el diagnóstico:\n"+result.stderr)
record = json.loads(result.stdout.strip().splitlines()[-1])
records.append(record)
print(json.dumps(record,ensure_ascii=False))
forecast = None
if len(records) == 3:
low, high, heldout = records
if any(r["pesos_sha256"] != low["pesos_sha256"] or
r["configuracion"] != low["configuracion"] or
r["versiones"] != low["versiones"] for r in records):
raise ValueError("La identidad o el entorno cambió entre mediciones")
measured = heldout["asignado_pico"]
forecast = {"metodo":"interpolacion de picos 128 y 512",
"longitud_validacion":heldout["tokens"], "prediccion":predicted,
"medicion":measured, "error_relativo":abs(predicted-measured)/measured}
print("validación independiente:",json.dumps(forecast,ensure_ascii=False))
print("modo | T | predicción GiB | pico GiB | error relativo")
print(mode,"|",heldout["tokens"],"|",round(predicted/2**30,4),"|",
round(measured/2**30,4),"|",round(forecast["error_relativo"],4))
root = next(p for p in (Path.cwd(), *Path.cwd().parents)
if (p/"src/content/modules/p08-ajuste-lora-dpo.json").is_file())
folder = root/"labs/runs/p08-l01"
folder.mkdir(parents=True,exist_ok=True)
destination = folder/f"memoria-{mode}-{time.time_ns()}.json"
with destination.open("x",encoding="utf-8") as f:
json.dump({"mediciones":records,"validacion":forecast},f,ensure_ascii=False,indent=2)
print("mediciones y predicción:",destination)npm run lab and open the connection link.To gather three rows, provide P08_MEMORY_TABLE as a JSON list of absolute paths to newly generated files, one per method, before starting the runner. The cell rejects mixed models, batches, or lengths. It does not automatically select old files:
$full = Read-Host "Ruta absoluta del JSON de full"
$lora = Read-Host "Ruta absoluta del JSON de LoRA"
$qlora = Read-Host "Ruta absoluta del JSON de QLoRA"
$env:P08_MEMORY_TABLE = ConvertTo-Json -Compress -InputObject @($full,$lora,$qlora)
import json, os
from pathlib import Path
raw_paths = os.environ.get("P08_MEMORY_TABLE")
if not raw_paths:
print("Tabla pendiente: indica en P08_MEMORY_TABLE las tres rutas de calibración.")
else:
paths = json.loads(raw_paths)
if not isinstance(paths,list) or len(paths) != 3:
raise ValueError("Se requieren tres rutas de calibración")
runs = [json.loads(Path(p).read_text(encoding="utf-8")) for p in paths]
rows = {}
for run in runs:
records, validation = run["mediciones"], run["validacion"]
if len(records) != 3 or validation is None:
raise ValueError("Falta la calibración o la medición reservada")
if [r["tokens"] for r in records] != [128,512,384]:
raise ValueError("Las longitudes de calibración no coinciden")
heldout = records[-1]
expected = records[0]["asignado_pico"] + (384-128)*(
records[1]["asignado_pico"]-records[0]["asignado_pico"])/(512-128)
if abs(validation["prediccion"]-expected) > 1e-6:
raise ValueError("La predicción no coincide con las medidas de calibración")
if abs(validation["error_relativo"]-abs(expected-heldout["asignado_pico"])/
heldout["asignado_pico"]) > 1e-12:
raise ValueError("El error relativo no coincide")
mode = heldout["modo"]
if mode not in ("full","lora","qlora") or mode in rows:
raise ValueError("Debe haber una única ejecución de cada modalidad")
rows[mode] = (heldout,validation)
if set(rows) != {"full","lora","qlora"}:
raise ValueError("Falta alguna modalidad")
reference = rows["full"][0]
for record,validation in rows.values():
if (record["pesos_sha256"] != reference["pesos_sha256"]
or record["configuracion"] != reference["configuracion"]
or record["batch"] != reference["batch"]
or record["tokens"] != reference["tokens"]
or record["checkpointing"] != reference["checkpointing"]
or any(record["versiones"].get(k) != reference["versiones"].get(k)
for k in ("torch","transformers","peft"))
or validation["medicion"] != record["asignado_pico"]):
raise ValueError("Las ejecuciones no comparten las condiciones declaradas")
print("modalidad | T | predicción GiB | pico GiB | error relativo")
for mode in ("full","lora","qlora"):
record,validation = rows[mode]
print(mode,"|",record["tokens"],"|",round(validation["prediccion"]/2**30,4),
"|",round(validation["medicion"]/2**30,4),
"|",round(validation["error_relativo"],4))npm run lab and open the connection link.An exploratory run of this cell for Qwen2.5-0.5B-Instruct, batch 1, and no recomputation produced the following table for T=384. Prediction used peaks at T=128 and T=512, including loading and first step; the third run was held out for comparison. Values use PyTorch 2.11.0 with CUDA and the preparation versions; QLoRA used bitsandbytes 0.50.2. Each run’s files retain dtypes, hashes, and metrics:
| Method | Prediction (GiB) | Allocated peak (GiB) | Relative error |
|---|---|---|---|
| Full | 4.6588 | 4.6557 | 0.066 % |
| LoRA | 2.6303 | 2.6099 | 0.781 % |
| QLoRA | 2.5471 | 2.4971 | 2.003 % |
All three errors were below the project threshold in this single held-out configuration. This validates local interpolation at that point, not the interactive subtotal or a guarantee for other lengths, architectures, kernels, or devices. Calibration lengths were chosen after initial exploration; this was not a prospective forecast recorded before all observation.
Freeze evaluation before adaptation
A baseline evaluation harness is an executable, recorded configuration measuring the model before fitting and then applying the same rules to the adapted model. It is more than a list of names: identify data and model versions, subset, examples, seeds, prompts, decoding, extraction, and metric.
The Spanish memory exam alone is insufficient to detect forgetting. Include general reasoning and comprehension tasks and Spanish evaluation when its license and protocol are verified. Compare task by task on the same examples. Small variation on a subset may be noise; report example counts and, where appropriate, paired intervals or seeds. Do not average heterogeneous metrics without explaining weights and meaning.
Scoring method matters. In multiple choice, option likelihood depends on how each continuation is concatenated with the prompt; length normalization changes the question the metric answers. For generation, fix extraction and tolerance before inspecting responses. In appendix F of Tülu 3, Qwen2.5-7B-Instruct achieves MATH scores 0.05, 34.23, and 67.17 under three evaluation settings that change format and examples among other details. These are not our model’s results and do not attribute the whole difference to one factor.
lm-evaluation-harness provides tasks and sample logs. In an isolated environment with the selected version installed, consult its help and pin versions; its interface may change. The next trial uses the first twenty ARC-Easy and HellaSwag indices, zero-shot and at specific dataset revisions. It is a small diagnostic, not an official full-benchmark score.
These general tasks use each task’s prompt without a chat template; later generative domain evaluation does use the tokenizer’s template. Preserve each task’s protocol when comparing base and adapted models. Changing it requires rerunning both. Metrics acc and acc_norm are reported separately because length normalization changes the decision rule. In the harness version used here, acc_norm divides log-likelihood by each option’s character length, not token count.
The cell uses P08_RUN_HARNESS=1, P08_MODEL_PATH, and, if needed, P08_PYTHON to select an interpreter with lm-eval==0.4.13. It uses that version’s internal YAML loader, which may change in others. Dataset revisions must be accessible or cached; check that the cache matches requested revisions. Output includes results and identifiers; individual records are retained in a new report file. Without variables, evaluation remains pending.
import os, subprocess, sys
if os.environ.get("P08_RUN_HARNESS") != "1" or not os.environ.get("P08_MODEL_PATH"):
print("Pendiente: define P08_RUN_HARNESS=1 y P08_MODEL_PATH.")
else:
program = r'''
import gc, hashlib, importlib.metadata, json, os, time
from pathlib import Path
import lm_eval, torch
from lm_eval.tasks import TaskManager
from lm_eval.tasks._yaml_loader import load_yaml
if importlib.metadata.version("lm-eval") != "0.4.13":
raise RuntimeError("Instala lm-eval 0.4.13 en el intérprete seleccionado")
model_dir = Path(os.environ["P08_MODEL_PATH"])
task_dir = Path(lm_eval.__file__).parent/"tasks"
specs = [("arc/arc_easy.yaml","210d026faf9955653af8916fad021475a3f00453"),
("hellaswag/hellaswag.yaml","218ec52e09a7e7462a5400043bb9a69a41d06b76")]
tasks = []
for yaml_path, revision in specs:
config = load_yaml(task_dir/yaml_path, resolve_func=True)
config["dataset_kwargs"] = {"revision":revision}
tasks.append(config)
try:
result = lm_eval.simple_evaluate(
model="hf", model_args={"pretrained":str(model_dir),"dtype":"bfloat16"},
tasks=tasks, device="cuda:0", batch_size=1, num_fewshot=0,
samples={"arc_easy":list(range(20)), "hellaswag":list(range(20))},
bootstrap_iters=0, log_samples=True,
random_seed=0, numpy_random_seed=1234, torch_random_seed=1234,
fewshot_random_seed=1234, task_manager=TaskManager(include_defaults=False))
if result is None:
raise RuntimeError("El arnés no devolvió resultados")
files = sorted({*model_dir.glob("*.safetensors"),
*[p for p in (model_dir/"config.json",model_dir/"tokenizer.json",
model_dir/"tokenizer_config.json",model_dir/"vocab.json",
model_dir/"merges.txt",model_dir/"generation_config.json",
model_dir/"special_tokens_map.json",model_dir/"added_tokens.json") if p.exists()]})
if not any(p.suffix == ".safetensors" for p in files):
raise ValueError("Faltan pesos safetensors en la copia local")
weights = {}
for file in files:
digest = hashlib.sha256()
with file.open("rb") as f:
for chunk in iter(lambda:f.read(8*1024*1024),b""):
digest.update(chunk)
weights[file.name] = digest.hexdigest()
root = next(p for p in (Path.cwd(), *Path.cwd().parents)
if (p/"src/content/modules/p08-ajuste-lora-dpo.json").is_file())
folder = root/"labs/runs/p08-l01"
folder.mkdir(parents=True,exist_ok=True)
destination = folder/f"harness-{time.time_ns()}.json"
versions = {name:importlib.metadata.version(name)
for name in ("lm-eval","transformers","datasets","torch")}
identities = {task:[(s["doc_id"],s["doc_hash"],s["prompt_hash"],s["target_hash"]) for s in samples]
for task,samples in result["samples"].items()}
identity_hash = hashlib.sha256(json.dumps(
identities,sort_keys=True,separators=(",",":")).encode("utf-8")).hexdigest()
result["p08_procedencia"] = {"versiones":versions,"archivos_sha256":weights,
"revision_declarada":os.environ.get("P08_REVISION","no declarada"),
"revisiones_solicitadas":specs,"huella_de_identidades":identity_hash}
with destination.open("x",encoding="utf-8") as f:
json.dump(result,f,ensure_ascii=False,indent=2,default=str)
print("versiones:",versions)
print("revision declarada:",os.environ.get("P08_REVISION","no declarada"))
print("archivos_sha256:",json.dumps(weights,sort_keys=True))
print("revisiones solicitadas de conjuntos:",specs)
print("resultados:",json.dumps(result["results"],ensure_ascii=False,default=str))
print("indices:",{task:[row[0] for row in rows] for task,rows in identities.items()})
print("huella_de_identidades:",identity_hash)
print("muestras y configuración completas:",destination)
finally:
gc.collect()
torch.cuda.empty_cache()
'''
result = subprocess.run([os.environ.get("P08_PYTHON",sys.executable),"-c",program],
env=dict(os.environ,PYTHONUTF8="1"),capture_output=True,
text=True,encoding="utf-8",timeout=900)
if result.returncode:
raise RuntimeError("Evaluación general no terminada:\n"+result.stderr)
print(result.stdout)npm run lab and open the connection link.Also pin the exact model revision and hashes of tokenization files; a task name and limit do not ensure two runs use the same examples. Before computing differences, compare document, prompt, and expected-answer identities between base and adapted models; a hash of that list summarizes the check and the full file supports investigation. The example harness requires installing its dependencies in a separate environment.
A local run of the base candidate at revision 7ae557604adf67be50417f59c2c2f167def9a775 produced these scores. The cells allow repetition and per-sample evidence retention; do not extrapolate them as full-benchmark scores. The domain row uses strict extraction and generation described in the next section.
| Task | Examples | acc | acc_norm |
|---|---|---|---|
| ARC-Easy | 20 | 0.65 | 0.55 |
| HellaSwag | 20 | 0.35 | 0.25 |
| Domain, exact integer | 12 | 0 | Not applicable |
Custom exam with verifiable answers
The following set fixes memory arithmetic questions and integer answers in bytes. Each case states element count and bytes per element; the answer is calculated rather than entered manually. It checks the evaluation protocol and permits inspecting each error. It does not replace open questions, subtopic coverage, or a pretraining/evaluation contamination audit.
import hashlib, json
cases = [(125000,2), (240000,4), (375000,8), (640000,2),
(825000,4), (1150000,8), (1430000,2), (1760000,4),
(2190000,8), (2530000,2), (2870000,4), (3190000,8)]
domain = [{"id":f"mem-{i:02d}",
"prompt":f"Un tensor tiene {n} elementos y cada uno ocupa {b} bytes. "
"¿Cuántos bytes ocupa? Responde solo con un entero.",
"answer":n*b} for i,(n,b) in enumerate(cases)]
serialized = json.dumps(domain,ensure_ascii=False,sort_keys=True,separators=(",",":"))
print("ejemplos:",len(domain))
print("huella del conjunto:",hashlib.sha256(serialized.encode("utf-8")).hexdigest())
print("ids:",[item["id"] for item in domain])Retain this object and its hash before training; a hash identifies content but does not alone establish date or that the set was unused in fitting. Exclude examples and close variants from the training corpus and record deduplication criteria and manual review. If an answer is corrected later, retain the old version and reevaluate both models on the new one.
For model comparison, generate without sampling and accept only an integer occupying the entire answer after whitespace removal. If another convention is needed, fix it beforehand and reprocess both models. Count every unextractable answer as incorrect and retain raw output and extraction. Prompts are few and similar, so the percentage should not be presented as a broad test of technical knowledge.
import re
def extract_integer(text):
text = text.strip()
return int(text) if re.fullmatch(r"[0-9]+", text) else None
def score_domain(rows, outputs):
if len(rows) != len(outputs) or not rows:
raise ValueError("Se requiere una salida por pregunta")
extracted = [extract_integer(s) for s in outputs]
correct = [p == row["answer"] for p,row in zip(extracted,rows)]
return {"correctos":sum(correct), "total":len(rows), "extraidos":extracted}
assert extract_integer(" 1200 ") == 1200
assert extract_integer("1200 bytes") is None
print("Regla: entero decimal completo, sin unidades; respuestas no extraíbles cuentan como error.")The next cell actually runs the domain exam when P08_RUN_EVAL=1 and P08_MODEL_PATH point to the local model copy, and skips the model if they are unset. It generates in bf16 using the tokenizer’s chat template and retains each answer in output. Revision is recorded through P08_REVISION and must match the verified local copy. A separate process releases the GPU afterward.
import os, subprocess, sys
if os.environ.get("P08_RUN_EVAL") != "1" or not os.environ.get("P08_MODEL_PATH"):
print("Evaluación pendiente: define P08_RUN_EVAL=1 y P08_MODEL_PATH.")
else:
program = r'''
import gc, hashlib, importlib.metadata, json, os, re, time, torch
from pathlib import Path
from transformers import AutoModelForCausalLM, AutoTokenizer
cases = [(125000,2),(240000,4),(375000,8),(640000,2),
(825000,4),(1150000,8),(1430000,2),(1760000,4),
(2190000,8),(2530000,2),(2870000,4),(3190000,8)]
rows = [{"id":f"mem-{i:02d}",
"prompt":f"Un tensor tiene {n} elementos y cada uno ocupa {b} bytes. "
"¿Cuántos bytes ocupa? Responde solo con un entero.",
"answer":n*b} for i,(n,b) in enumerate(cases)]
raw = json.dumps(rows,ensure_ascii=False,sort_keys=True,separators=(",",":"))
print("huella del conjunto:",hashlib.sha256(raw.encode("utf-8")).hexdigest(),flush=True)
model = tok = inputs = output = None
try:
path = os.environ["P08_MODEL_PATH"]
tok = AutoTokenizer.from_pretrained(path, local_files_only=True)
files = sorted({*Path(path).glob("*.safetensors"),
*[p for p in (Path(path)/"config.json", Path(path)/"tokenizer.json",
Path(path)/"tokenizer_config.json", Path(path)/"vocab.json",
Path(path)/"merges.txt", Path(path)/"generation_config.json",
Path(path)/"special_tokens_map.json", Path(path)/"added_tokens.json") if p.exists()]})
if not any(p.suffix == ".safetensors" for p in files):
raise ValueError("La copia local no contiene pesos safetensors")
identities = {}
for file in files:
digest = hashlib.sha256()
with file.open("rb") as f:
for chunk in iter(lambda: f.read(8*1024*1024), b""):
digest.update(chunk)
identities[file.name] = digest.hexdigest()
print("archivos_sha256:",json.dumps(identities,sort_keys=True))
template_hash = hashlib.sha256(str(tok.chat_template).encode("utf-8")).hexdigest()
versions = {name:importlib.metadata.version(name) for name in ("torch","transformers")}
print("plantilla_sha256:",template_hash)
print("versiones:",json.dumps(versions))
model = AutoModelForCausalLM.from_pretrained(
path, local_files_only=True, dtype=torch.bfloat16).to("cuda").eval()
for row in rows:
inputs = tok.apply_chat_template(
[{"role":"user","content":row["prompt"]}], tokenize=True,
add_generation_prompt=True, return_tensors="pt", return_dict=True).to("cuda")
with torch.inference_mode():
output = model.generate(**inputs, max_new_tokens=16, do_sample=False,
pad_token_id=tok.eos_token_id)
text = tok.decode(output[0,inputs["input_ids"].shape[-1]:],
skip_special_tokens=True).strip()
generated = output[0,inputs["input_ids"].shape[-1]:]
eos_ids = model.generation_config.eos_token_id
eos_ids = eos_ids if isinstance(eos_ids,list) else [eos_ids]
extracted = int(text) if re.fullmatch(r"[0-9]+",text) else None
row.update({"output":text,"extracted":extracted,
"tokens_generados":int(generated.numel()),
"termina_en_eos":bool(generated.numel() and int(generated[-1]) in eos_ids),
"correct":extracted == row["answer"]})
print(json.dumps(row,ensure_ascii=False),flush=True)
del inputs, output
inputs = output = None
summary = {"tarea":"dominio","correctos":sum(r["correct"] for r in rows),
"total":len(rows),"revision_declarada":os.environ.get("P08_REVISION","no declarada"),
"precision":"bf16","muestreo":False,"max_new_tokens":16,
"archivos_sha256":identities,"plantilla_sha256":template_hash,"versiones":versions,
"conjunto_sha256":hashlib.sha256(raw.encode("utf-8")).hexdigest()}
root = next(p for p in (Path.cwd(), *Path.cwd().parents)
if (p/"src/content/modules/p08-ajuste-lora-dpo.json").is_file())
folder = root/"labs/runs/p08-l01"
folder.mkdir(parents=True,exist_ok=True)
destination = folder/f"dominio-{time.time_ns()}.json"
with destination.open("x",encoding="utf-8") as f:
json.dump({"resumen":summary,"muestras":rows},f,ensure_ascii=False,indent=2)
print(json.dumps(summary,ensure_ascii=False))
print("muestras y configuración completas:",destination)
finally:
del model, tok, inputs, output
gc.collect()
torch.cuda.empty_cache()
'''
result = subprocess.run([os.environ.get("P08_PYTHON",sys.executable),"-c",program],
env=dict(os.environ,PYTHONUTF8="1"),capture_output=True,
text=True,encoding="utf-8",timeout=600)
if result.returncode:
raise RuntimeError("Evaluación no terminada:\n"+result.stderr)
print(result.stdout)npm run lab and open the connection link.A complete run produces one row per general task and one for domain, with version, sample size, and references to individual results. Both cells run separate processes and contribute those rows only when enabled and completed; if one fails or is skipped, its result remains pending. Filling it with estimates or another model’s results would be incorrect.
In a candidate run at the stated revision, the domain exam obtained 0 correct out of 12 under strict extraction and a maximum of 16 new tokens. The cell saves raw answers and whether generation ended with an end token, allowing unsupported formats, numerical errors, and possible truncations to be distinguished. This result describes that protocol and set; it does not alone quantify general model capability.
Exercises
Memory planning requires declaring dtypes, states, activations, and measurement scope. Evaluating adaptation requires fixing tasks and rules before training. Measurements and baseline evaluation are reproducible under their stated conditions; a small sample does not guarantee quality retention after fitting, and memory error must be checked per method.