The long pretraining run
Launch pretraining of the 124M architecture with a budget of 1 to 3 billion tokens across several nights. This stage covers long-run engineering: atomic checkpoints with exact resumption, monitoring and alerts, periodic samples, and diagnosis of loss spikes and instability.
After this lesson you can
- Choose token budget and hyperparameters using the pilot and literature.
- Implement atomic checkpoints with complete state and demonstrate exact resumption.
- Monitor loss, norms, throughput, and samples with automatic alerts.
- Diagnose and document each loss spike or instability.
Before you start
- P06Throughput optimizationFitting training into 8 GBWarmup and decay learning rate schedulePretraining data pipeline
- 00Full training checkpointAtomic writes and checkpoint rotationExact resumptionComplete seeding of a training runGPU nondeterminism and deterministic mode
- 20Pretraining run monitoringNeural scaling lawsCompute-optimal allocation
- 18Attention entropy collapseQuery-key normalization
A run that can survive interruption
In training over several nights, a downward curve is not enough: we must reconstruct what was processed, what changed, and where continuation is possible. A checkpoint is a snapshot of a training machine’s state, not just its weights. The strongest test compares a continuous run with one interrupted and resumed at the same point using the same data and a deterministic environment.
In this lesson you launch pretraining of the pathway’s GPT: GPT-2 small architecture, 12 blocks, width 768, context 1024, with the 513-ID vocabulary from the data lesson, trained on about 1730 million FineWeb-Edu tokens. On the RTX 4060 this takes tens of hours across several nights, with pauses, resumptions, and probably incidents. We study the engineering that turns those nights into one verifiable experiment.
The panel shows real records from a short lab run: a two-block model trained for 400 updates on p06-l02 data, with an incident deliberately induced at update 300. There are three variants: one batch replaced by random IDs, five updates with learning rate multiplied by 30, and one batch consisting of a repeated 32-token fragment. Each replay starts from the checkpoint saved after update 290 and changes one thing. Start with the random batch and its replay without that batch; then choose the multiplied-rate run as A and compare which intervention corrects it. Once you have your own run, load the lab report’s forensics.json.
Long-run training monitoring combines per-step metrics, separate evaluations, samples, and system events with configuration and data identifiers. To interpret a curve, know what its axis represents: optimizer steps, processed targets, or elapsed time. With accumulation, one optimizer step comprises several microbatches. An evaluation should state its number of valid targets and must not contribute to training gradients. This is the project-scale version of pretraining monitoring.
Budget: tokens, hours, and scaling
For a budget of tokens and sustained effective rate tokens per second, ideal training time is . This excludes pauses, validation, checkpoints, and data preparation. The relevant rate is for the full path, including batch reading, copying, forward and backward passes, clipping, and AdamW, rather than an isolated kernel. Measure it under actual configuration and load.
Start with model size. With vocabulary , context , blocks, and width , the tied-weight count from p06-l03 is
With , , , and , this gives parameters. GPT-2 small has 124439808 under the same formula; the difference is entirely in the token table ( versus ). “124M” names the architecture, not the parameter count of our model.
The study by Hoffmann and colleagues trained more than 400 models ranging from 70 million to over 16 billion parameters on budgets of 5 to 500 billion tokens. In their regime, optimal model and data size grow approximately together as compute increases, the compute-optimal allocation. Their Chinchilla model uses 70 billion parameters and 1.4 trillion tokens, a ratio of 20 tokens per parameter. This is guidance from a particular range, tokenizer, and corpus, not a guarantee that 20 is optimal for each small model, architecture, or inference budget. For our model, tokens.
The lab plan rounds to 3300 updates of 524288 tokens: , about 20.06 tokens per parameter, within the 1000-to-3000-million range allowing work across several nights. There is a qualification absent from the rule: one token from our vocabulary contains less text than a GPT-2 token. On the 1000 p06-l02 documents, the custom vocabulary produced 2440430 IDs and GPT-2 produced 1057455 for 4910435 bytes: 2.01 bytes per custom token versus 4.64. Our 1730 million tokens are about 3.5 GB of text, which GPT-2 would encode in about 750 million. Matching the text implied by the rule with GPT-2’s tokenizer would require about 4000 million custom tokens and over twice the hours.
Training compute is approximated by FLOPs. With the p06-l03 formula, which adds attention multiplications at , each token costs FLOPs, forward plus backward at twice the cost, and the total rises to . Per token, the 513-vocabulary model performs 71% of the multiplications of the 50257-vocabulary model because almost all final projection disappears.
For time, the measured reference is p06-l05: 8842 tokens per second with vocabulary 50257, microbatch 1, BF16, cuDNN attention, and fused AdamW, or 11717 with compilation. In this lab’s short check, the 513-vocabulary model at microbatch 4 achieved 11301 and 9853 tokens per second in two 8192-token updates while the GPU was shared with other processes. These are short-run measurements, not a promise. The script prints every update’s rate, and your first training hour establishes the actual estimate.
| Sustained rate | Hours for 1730150400 tokens | Nine-hour nights |
|---|---|---|
| 10000 tokens/s | 48.1 | 5.3 |
| 12000 tokens/s | 40.0 | 4.4 |
| 15000 tokens/s | 32.0 | 3.6 |
Hyperparameters come from literature and the pilot. Table 2.1 and appendix B of GPT-3 specify for its 125-million-parameter model peak rate , batches of 0.5 million tokens, Adam with , , and , weight decay 0.1, global norm clipping at 1, linear warmup, and cosine decay to 10% of peak. The llm.c GPT-2 reproduction uses the same rate and batch. GPT-3 warmed up for 375 million tokens in a 300-billion-token plan; with 3300 updates we use 200, about 105 million tokens or 6% of the plan, a choice that must be logged. The p06-l04 pilot, 13 million parameters and 1000 updates, gave validation 2.164 at peak and 2.244 at : an indication that is already aggressive at that scale, not a rule transferable without qualification to a model almost seven times larger. We use no dropout: each token is seen once and validation monitors overfitting.
What should we expect at the end? There is no published figure for a 513-ID tokenizer, but a reference can be converted to a common unit. Compare loss across tokenizers in bits per byte,
where is target ‘s loss in nats and its bytes. The llm.c reproduction trained the same architecture on 10 billion GPT-2 FineWeb tokens, ending at roughly 3.29 training nats per token and reaching 29.9% on HellaSwag versus 29.4% for published GPT-2. At 4.64 bytes per GPT-2 token, this loss is about bits per byte. This is approximate because bytes per token were measured on our FineWeb-Edu sample, not FineWeb. Our budget sees about 3.5 GB of text versus about 46 GB, so expect substantially more bits per byte than that reference. A fair comparison with public GPT-2 comes in the next lesson using the same evaluator and documents.
Sufficient state to resume
Exact resumption requires saving at least model parameters and buffers, AdamW state, schedule, step and token count, loader state, and generator state for Python, NumPy, PyTorch CPU, and each GPU used, plus the scaler if applicable. Also save configuration, code version, vocabulary identity, and shard fingerprints. If the checkpoint is taken during accumulation, partial gradients and microbatch position are also needed. It is simpler to save immediately after the optimizer step, when no gradients are pending. This applies the training checkpoint and exact resumption from m00 at project scale.
Proof
Induct on . The case is the hypothesis . If , then because is a function. Loss equality follows by applying to equal states.
∎The proof is trivial; satisfying its hypotheses is difficult, and each practical failure breaks one.
- Saved state is not . A component is missing. If AdamW moments are lost and its counter reset, the first update has and , so each coordinate moves : a step of size in every coordinate, including those where gradient is pure noise. Keeping the counter but losing moments gives with . In normal steady state, is small where the gradient is noisy.
- is not a function. Kernels with atomic additions or variable reduction order give different results on identical runs because floating-point addition is not associative, the GPU nondeterminism problem. Without deterministic mode, resumption can only target the same distribution of trajectories.
- depends on something outside . Examples include a prefetch queue from workers, a generator living in another process, a rate derived from wall-clock time, or periodic sampling consuming the global training generator.
Restoration order matters. First construct compatible objects and load their states; then restore generators before requesting the next batch or running dropout. The loader must save its own cursor and generator if used. Asynchronous workers may have prefetched data: either record that queue and their states, or design a synchronization point that can reconstruct it. An isolated initial seed does not recover an advanced generator state, as covered in the seeding strategy.
This small control runs a CPU model with dropout, AdamW, and a loader with cursor. It compares a continuous eight-step trajectory with another saved after four and restored before continuing. It is the minimum mechanism test; the lab repeats the comparison between separate processes and on GPU.
import copy, os, random, tempfile
from pathlib import Path
import numpy as np
import torch
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
def init():
random.seed(17); np.random.seed(17); torch.manual_seed(17)
model = torch.nn.Sequential(torch.nn.Linear(3, 8), torch.nn.Tanh(),
torch.nn.Dropout(0.25), torch.nn.Linear(8, 1))
optimizer = torch.optim.AdamW(model.parameters(), lr=0.01)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.9)
return model, optimizer, scheduler
def steps(model, optimizer, scheduler, cursor, count):
losses = []
for _ in range(count):
# El cursor reconstruye este lote determinista; dropout usa el RNG de torch.
x = torch.tensor([[float(cursor % 5), 1., -1.]])
y = torch.tensor([[float(cursor % 3)]])
optimizer.zero_grad(set_to_none=True)
loss = (model(x) - y).square().mean()
loss.backward(); optimizer.step(); scheduler.step()
losses.append(loss.item()); cursor += 1
return cursor, losses
def save(path, model, optimizer, scheduler, cursor):
state = dict(model=model.state_dict(), optimizer=optimizer.state_dict(),
scheduler=scheduler.state_dict(), cursor=cursor,
py=random.getstate(), np=np.random.get_state(), rng=torch.get_rng_state())
fd, tmp = tempfile.mkstemp(prefix=path.name + '.', dir=path.parent)
try:
with os.fdopen(fd, 'wb') as f:
torch.save(state, f); f.flush(); os.fsync(f.fileno())
os.replace(tmp, path)
finally:
if os.path.exists(tmp): os.unlink(tmp)
def load(path, model, optimizer, scheduler):
# Solo archivos propios confiables: este formato contiene objetos de Python.
state = torch.load(path, map_location='cpu', weights_only=False)
model.load_state_dict(state['model']); optimizer.load_state_dict(state['optimizer'])
scheduler.load_state_dict(state['scheduler'])
random.setstate(state['py']); np.random.set_state(state['np'])
torch.set_rng_state(state['rng'])
return state['cursor']
model, opt, sched = init()
cursor, full = steps(model, opt, sched, 0, 8)
reference = copy.deepcopy(model.state_dict())
reference_opt = copy.deepcopy(opt.state_dict())
reference_sched = copy.deepcopy(sched.state_dict())
model, opt, sched = init()
cursor, first = steps(model, opt, sched, 0, 4)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'checkpoint.pt'
save(path, model, opt, sched, cursor)
resumed, opt2, sched2 = init()
cursor = load(path, resumed, opt2, sched2)
cursor, second = steps(resumed, opt2, sched2, cursor, 4)
assert full == first + second
assert all(torch.equal(reference[k], resumed.state_dict()[k]) for k in reference)
def same(a, b):
if isinstance(a, torch.Tensor): return torch.equal(a, b)
if isinstance(a, dict): return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
if isinstance(a, (list, tuple)): return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
return a == b
assert same(reference_opt, opt2.state_dict()) and same(reference_sched, sched2.state_dict())
print('Pérdidas continuas y reanudadas idénticas:', full == first + second)
print('Parámetros finales idénticos:', all(torch.equal(reference[k], resumed.state_dict()[k]) for k in reference))
print('Optimizador y calendario idénticos:', same(reference_opt, opt2.state_dict()) and same(reference_sched, sched2.state_dict()))
print('Cursor final:', cursor, 'pérdidas posteriores:', [round(x, 7) for x in second])npm run lab and open the connection link.To replace a checkpoint without leaving a half-written destination, create a temporary file in the same directory, write and flush its data, close it, and replace the destination with os.replace, an atomic write. Replacement protects readers from partial files within filesystem guarantees. Power-loss durability also requires directory and device synchronization appropriate to the system. Do not overwrite the only checkpoint: write a new one with the step number in its name, publish a latest.json pointer with its hash, and only then remove older checkpoints exceeding the retention count. Checkpoints before an incident are marked protected for replay.
Never load a serialized checkpoint from an untrusted source: Python pickle can execute code during deserialization. The lab therefore stores only tensors and simple types, lists, numbers, and strings, and loads with torch.load(..., weights_only=True), which rejects other objects.
Deterministic mode reduces known variation sources but does not promise identity across versions, platforms, or devices. PyTorch documents reproducibility limits and options. In the same environment, compare loss, next batch, parameters, and optimizer state. If they differ, locate the first divergent step and inspect loader, generators, and kernels. A short passing test is necessary but does not automatically prove that a long run in another environment will be identical.
Monitoring and alerts
Each lab update writes a JSON line with step, cumulative tokens, mean microbatch loss, rate, global gradient norm before clipping, duration, and tokens per second. Every ten updates it adds per-block norms and maximum attention logits, and every twenty, GPU temperature, power, and clock. Validation, samples, and events go to separate files. After resumption from step , the script drops lines for steps after written before interruption; otherwise the curve would contain two versions of the same steps.
A spike is defined relative to a reference adapting to decreasing loss. With and factor , exponentially weighted mean and variance update as
giving the observation from steps ago weight proportional to . With , effective memory is about steps. The alert fires when and : the first measures surprise relative to recent noise, and the second avoids alerts for tiny deviations when noise is nearly zero. A second rule monitors gradient norm, alerting above 2.5 times its exponential mean. Observations triggering an alert do not update the reference; otherwise a spike would raise mean and variance and hide the next one.
This detector has blind spots. Gradual degradation moves the reference along with it and may never trigger the loss rule; periodic validation and trend comparison cover that. And below-normal loss is not a loss alert, although its gradient can be one.
A NaN or loss that does not recover requires preserving evidence and stopping or pausing to investigate. The script checks loss and norm are finite before opt.step(). If they are not, it logs the batch, loader state, and last checkpoint, leaves weights unchanged, and exits with code 3. Returning to an earlier checkpoint permits repeating the incident; lowering rate, modifying the batch, or adding mitigation are distinct interventions and should be recorded.
On a laptop, record temperature, power, and sustained rate when available, and establish a pause policy compatible with the hardware. The script periodically reads nvidia-smi; if temperature reaches max_temp, 85 °C by default and adjustable to your machine’s documentation, it saves a checkpoint and waits for a ten-degree drop. Throughput below 60% of the median of the last 50 updates triggers another alert. Temperature, shared load, data waits, or shape changes may contribute; one number does not identify the cause. Separate training alerts from system alerts and retain time and context for each.
Periodic samples, three fixed prompts, temperature 0.8, top-k 50, use their own fixed-seed torch.Generator, and attention logits are measured with the model in evaluation mode. Both decisions have the same motivation: if observation consumed the global generator, the trajectory would depend on observation timing and resumption would cease to be exact.
From symptom to diagnosis
Loss spike investigation starts by recording the batch and preceding checkpoint. A moving average detects deviations, but a hard batch does not necessarily imply divergence. Check data for repetition, corruption, unexpected IDs, or distribution shift; compare validation and see whether the next step recovers. Record pre-clipping global norm, per-block norms, rate, nonfinite gradients, maximum attention logits, and memory. If a quantity was not instrumented, mark it absent rather than inferring it from the curve.
Text repeated thousands of times in a batch justifies inspecting its origin and replaying it from the previous checkpoint. It does not by itself prove the text caused the spike. A controlled replay holds state and seed constant, changes one variable, and compares several trajectories when affordable. PaLM’s experience is instructive: its largest model suffered around 20 spikes despite gradient clipping. The authors mitigated them by restarting from a checkpoint about 100 updates before the spike and skipping 200 to 500 batches. Training on those same batches from a different earlier checkpoint did not reproduce the spike, so they concluded the spikes arose from particular batches combined with a particular parameter state, not “bad data” alone.
Two instability mechanisms are well documented. Attention logit growth: if grows, logits rise sharply, softmax concentrates on one position, and attention entropy collapses, the entropy collapse mechanism. Query and key normalization bounds those logits. Output logit divergence can be restrained by an auxiliary loss proportional to , where is the final softmax partition function. Wortsman and colleagues reproduce both in small models trained at high rates and show these mitigations work at that scale. This does not automatically explain every observed spike. The lab logs maximum attention logits as a direct measurement of the first mechanism.
The panel’s three variants teach how to read these signals; all come from the same short run and one seed.
- Random-ID batch. Loss jumps from 4.343 to 7.708 at update 300, with exponential reference 4.358 and standard deviation 0.066, and gradient norm reaches 6.65 while its mean was around 1. Both rules fire. The next update returns to 4.371. Skipping that batch removes the spike. Reducing the rate by 10 does not: update-300 loss is measured before the rate is applied, so a rate intervention can change only what follows. Skipping the batch does not improve subsequent loss either: mean loss over updates 306 to 320 is 4.332 when skipped and 4.324 when not skipped. Skipping changes all subsequent batches, so this difference is on the order of batch noise.
- Rate multiplied by 30 for five updates. There is no isolated jump but a rise: 4.212, 4.497, 4.515, 4.578, and 4.761 at updates 300 to 304. The loss rule misses it because the reference rises with it; the norm rule fires at 304, with 3.78. Skipping batch 300 changes nothing, with mean loss over 306 to 320 of 4.554 versus 4.553 without intervention. Reducing the rate for those five updates restores the normal trajectory, 4.324. Validation went from 4.3059 at update 250 to 4.3469 at 300; in the random-batch variant, with the same first 299 updates, it fell to 4.2500.
- Repeated fragment. Loss falls to 4.087 because repeated text is easy to predict, but gradient norm rises to 2.86. Only the norm rule detects it, and the saved batch has a distinct-token proportion of 0.22.
Maximum attention logits moved in the direction predicted by the first mechanism: between updates 295 and 320, they reached 4.95 in the rate variant, versus 3.25 and 3.28 in the other two. These are small values in a two-block model, and one run is insufficient to attribute the loss rise to them. In the long run, a sustained rise in that curve is worth monitoring. The full record also contains four norm-rule alerts between updates 52 and 79, early in training when norm still fluctuates greatly, and real throughput alerts: the GPU was shared with other processes during the run.
Lab
The lab is a roughly 1000-line pretrain.py script written by the first cell to p06_pretrain, configurable with P06_PRETRAIN_DIR, and tested on CPU. It requires p06-l02 preparation: it reads and hash-verifies that lesson’s manifest and vocabulary from p06_data or P06_DATA_DIR. It does not copy prior code: it extracts the p06-l01 BPE encoder, p06-l02 pipeline and TokenLoader, and p06-l03 GPT class from current MDX and saves their hashes in every checkpoint. Install PyTorch with CUDA, numpy, pyarrow, matplotlib, and p06-l01 dependencies regex, tiktoken, and hypothesis. You need about 13 GB disk: 4.3 GB parquet, 3.6 GB shards, about 1 GB per full checkpoint, and 345 MB per weights-only copy.
Script commands are selftest, prepare, train, resume-test, spike-demo, replay, and report. The full configuration contains the plan above: microbatch 4, context 1024, 128 microbatches per update, 3300 updates, validation every 100 on 160 fixed windows, samples every 250, a full checkpoint every 50, retaining the last two and protected ones, and a weights-only copy every 500 for the next lesson’s evaluation. The short check peaked at 4.59 GiB tensor memory for microbatch 4 and 7.39 GiB for microbatch 8, too close to the card’s 8 GB.
"""Escribe el laboratorio de p06-l06 en P06_PRETRAIN_DIR y ejecuta sus pruebas rápidas en CPU."""
import json
import os
import subprocess
import sys
from pathlib import Path
import matplotlib # el informe dibuja la curva; se comprueba aquí que está instalado
def project_root():
configured = os.environ.get('P06_PROJECT_ROOT')
for c in ([Path(configured)] if configured else [Path.cwd(), *Path.cwd().parents]):
if (c / 'src/content/lessons/p06').is_dir():
return c.resolve()
raise FileNotFoundError('Define P06_PROJECT_ROOT con la raíz del proyecto')
PROJECT = project_root()
DATA = Path(os.environ.get('P06_DATA_DIR', 'p06_data')).resolve()
LAB = Path(os.environ.get('P06_PRETRAIN_DIR', 'p06_pretrain')).resolve()
LAB.mkdir(parents=True, exist_ok=True)
source = r'''
"""Preentrenamiento largo y reanudable del GPT de la ruta p06 (lección p06-l06).
Órdenes (ejecútalas desde cualquier carpeta; las rutas salen de paths.json o del entorno):
python pretrain.py selftest pruebas rápidas en CPU, sin datos
python pretrain.py prepare --files 2 corpus FineWeb-Edu tokenizado con el BPE de p06-l02
python pretrain.py train --preset full ejecución larga; repite la orden para reanudar
python pretrain.py resume-test reanudación exacta entre procesos (modo determinista)
python pretrain.py spike-demo pico inducido en un modelo pequeño y reproducciones
python pretrain.py replay --run R --from C --at S --intervention skip
python pretrain.py report --run R curva, incidencias y JSON para el panel forense
"""
import argparse
import hashlib
import json
import math
import os
import random
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from pathlib import Path
if '--deterministic' in sys.argv or (len(sys.argv) > 1 and sys.argv[1] in ('resume-test', 'spike-demo')):
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # antes de inicializar CUDA
import numpy as np
HERE = Path(__file__).resolve().parent
_paths = json.loads((HERE / 'paths.json').read_text(encoding='utf-8')) if (HERE / 'paths.json').exists() else {}
OUT = Path(os.environ.get('P06_PRETRAIN_DIR', HERE)).resolve()
DATA02 = Path(os.environ.get('P06_DATA_DIR', _paths.get('data', OUT.parent / 'p06_data'))).resolve()
def find_root():
configured = os.environ.get('P06_PROJECT_ROOT', _paths.get('root'))
candidates = [Path(configured)] if configured else [HERE, *HERE.parents, Path.cwd(), *Path.cwd().parents]
for c in candidates:
if (c / 'src/content/lessons/p06').is_dir():
return c.resolve()
raise FileNotFoundError('No encuentro src/content/lessons/p06: define P06_PROJECT_ROOT')
ROOT = find_root()
os.environ['P06_PROJECT_ROOT'] = str(ROOT)
os.environ['P06_DATA_DIR'] = str(DATA02)
# ---------------------------------------------------------------- código de las lecciones anteriores
def lesson_cell(filename, title):
text = (ROOT / 'src/content/lessons/p06' / filename).read_text(encoding='utf-8')
marker = '`' * 3 + f'python run runtime=local title="{title}"\n'
return text.split(marker, 1)[1].split('\n' + '`' * 3, 1)[0]
def sha(text):
return hashlib.sha256(text.encode('utf-8')).hexdigest()
_cache = {}
def l02():
"""Pipeline de p06-l02: TokenLoader, file_hash, verify_manifest y la regla de partición."""
if 'l02' not in _cache:
cell = lesson_cell('l02-datos-de-preentrenamiento.mdx', 'Descarga, tokenización en procesos y shards')
quotes = "'" * 3
code = cell.split('source = r' + quotes + '\n', 1)[1].split('\n' + quotes, 1)[0]
env = {'__name__': 'pipeline_p06_l02'}
exec(compile(code, 'p06-l02.mdx', 'exec'), env)
_cache['l02'] = (env, sha(code))
return _cache['l02']
def l03():
"""Clase GPT de p06-l03 (sin ejecutar sus controles)."""
if 'l03' not in _cache:
cell = lesson_cell('l03-modelo-gpt-y-paridad.mdx', 'GPT propio y controles')
code = cell.split('\nattention_test()\nbehavior_test()', 1)[0]
env = {'__name__': 'modelo_p06_l03'}
exec(compile(code, 'p06-l03.mdx', 'exec'), env)
_cache['l03'] = (env, sha(code))
return _cache['l03']
def l01_encoder(ranks, eot):
os.environ['BPE_DATA_DIR'] = str(OUT / 'bpe_cache')
code = lesson_cell('l01-tokenizador-bpe.mdx', 'Codificador y entrenador BPE incremental')
env = {'__name__': 'bpe_p06_l01'}
exec(compile(code, 'p06-l01.mdx', 'exec'), env)
return env['make_text_encoder'](ranks, special_id=eot)
def vocabulary():
"""Vocabulario de p06-l02, verificado contra su manifiesto."""
env, _ = l02()
manifest = json.loads((DATA02 / 'manifest.json').read_text(encoding='utf-8'))
env['verify_manifest'](manifest)
payload = json.loads((DATA02 / manifest['vocab_file']).read_text(encoding='utf-8'))
ranks = {bytes.fromhex(k): v for k, v in payload['vocab_hex'].items()}
eot = payload['special_id']
rev = {v: k for k, v in ranks.items()}
rev[eot] = payload['special_literal'].encode('utf-8')
return manifest, ranks, eot, rev
def file_sha256(path):
d = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1 << 22), b''):
d.update(chunk)
return d.hexdigest()
def atomic_bytes(path, writer):
"""Escribe en un temporal del mismo directorio, fsync y os.replace."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix=path.name + '.', suffix='.tmp', dir=path.parent)
try:
with os.fdopen(fd, 'wb') as f:
writer(f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
def atomic_json(path, obj):
atomic_bytes(path, lambda f: f.write(json.dumps(obj, ensure_ascii=False, indent=1).encode('utf-8')))
def append_jsonl(path, obj):
with open(path, 'a', encoding='utf-8') as f:
f.write(json.dumps(obj, ensure_ascii=False) + '\n')
def read_jsonl(path):
if not Path(path).exists():
return []
rows = []
for line in Path(path).read_text(encoding='utf-8').splitlines():
try:
rows.append(json.loads(line))
except json.JSONDecodeError:
pass # una última línea cortada por una interrupción
return rows
def truncate_jsonl(path, last_step):
"""Tras reanudar desde el paso c, descarta registros de pasos > c escritos antes del corte."""
if Path(path).exists():
rows = [r for r in read_jsonl(path) if r.get('step', -1) <= last_step]
atomic_bytes(path, lambda f: f.write(''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in rows).encode('utf-8')))
# ---------------------------------------------------------------- corpus a escala
REPO = 'HuggingFaceFW/fineweb-edu'
def hub_json(url):
import urllib.request
with urllib.request.urlopen(url, timeout=60) as r:
return json.loads(r.read())
def download(revision, entry, folder):
"""Descarga reanudable (cabecera Range) y verificación SHA-256 del fichero LFS."""
import urllib.request
target = folder / Path(entry['path']).name
if target.exists() and target.stat().st_size == entry['size']:
return target
part = target.with_suffix('.part')
url = f'https://huggingface.co/datasets/{REPO}/resolve/{revision}/{entry["path"]}'
for attempt in range(20):
have = part.stat().st_size if part.exists() else 0
if have == entry['size']:
break
request = urllib.request.Request(url, headers={'Range': f'bytes={have}-'} if have else {})
try:
with urllib.request.urlopen(request, timeout=120) as r, open(part, 'ab' if have and r.status == 206 else 'wb') as f:
while chunk := r.read(1 << 23):
f.write(chunk)
except OSError as error:
print('descarga interrumpida, reintento:', error, flush=True)
time.sleep(min(120, 5 * 2 ** attempt))
print(f'{target.name}: {part.stat().st_size / 1e9:.2f} de {entry["size"] / 1e9:.2f} GB', flush=True)
if file_sha256(part) != entry['lfs']['oid']:
raise ValueError(f'SHA-256 distinto en {target.name}: borra {part} y repite')
os.replace(part, target)
return target
ENCODER = None
def _worker_init(ranks, eot):
global ENCODER
ENCODER = l01_encoder(ranks, eot)
def _worker(text):
ids = ENCODER(text)
arr = np.asarray(ids, dtype=np.int64)
return arr.astype('<u2').tobytes(), int(arr.min(initial=0)), int(arr.max(initial=0)), len(ids)
class ShardWriter:
"""Acumula IDs uint16 y publica shards con el hash en el nombre."""
def __init__(self, folder, name, shard_tokens):
self.folder, self.name, self.size = Path(folder), name, shard_tokens
self.buffer = np.empty(shard_tokens, dtype='<u2')
self.fill, self.shards, self.tokens, self.docs = 0, [], 0, 0
def add(self, ids):
self.docs += 1
while len(ids):
take = min(len(ids), self.size - self.fill)
self.buffer[self.fill:self.fill + take] = ids[:take]
self.fill += take
ids = ids[take:]
if self.fill == self.size:
self.flush()
def flush(self):
if not self.fill:
return
data = self.buffer[:self.fill].tobytes()
digest = hashlib.sha256(data).hexdigest()
path = self.folder / f'{self.name}-{len(self.shards):05d}-{digest}.bin'
atomic_bytes(path, lambda f: f.write(data))
self.shards.append({'file': path.name, 'tokens': self.fill, 'sha256': digest})
self.tokens += self.fill
self.fill = 0
def split_of(raw):
"""La misma regla que p06-l02: primeros 8 bytes del SHA-256, módulo 10."""
key = hashlib.sha256(raw).digest()
return key, ('valid' if int.from_bytes(key[:8], 'big') % 10 == 0 else 'train')
def prepare(args):
import itertools
import multiprocessing
import pyarrow.parquet as pq
manifest02, ranks, eot, _ = vocabulary()
corpus = OUT / 'corpus'
corpus.mkdir(parents=True, exist_ok=True)
if args.parquet:
sources = [{'path': str(Path(p).resolve()), 'sha256': file_sha256(p)} for p in args.parquet]
files, revision = [Path(s['path']) for s in sources], 'local'
else:
revision = hub_json(f'https://huggingface.co/api/datasets/{REPO}/revision/main')['sha']
tree = hub_json(f'https://huggingface.co/api/datasets/{REPO}/tree/{revision}/sample/10BT')
entries = sorted([e for e in tree if e['path'].endswith('.parquet')], key=lambda e: e['path'])[:args.files]
files = [download(revision, e, OUT / 'downloads') for e in entries]
sources = [{'path': e['path'], 'size': e['size'], 'sha256': e['lfs']['oid']} for e in entries]
writers = {'train': ShardWriter(corpus, 'train', args.shard_tokens), 'valid': ShardWriter(corpus, 'valid', args.shard_tokens)}
caps = {'train': args.max_train_tokens, 'valid': args.max_valid_tokens}
seen, stats = set(), {'documents': 0, 'duplicates': 0, 'valid_over_cap': 0, 'bytes': {'train': 0, 'valid': 0}}
def texts():
for path in files:
for batch in pq.ParquetFile(path).iter_batches(batch_size=1024, columns=['text']):
for text in batch.column(0).to_pylist():
raw = text.encode('utf-8')
key, split = split_of(raw)
stats['documents'] += 1
if key in seen:
stats['duplicates'] += 1
continue
seen.add(key)
if writers[split].tokens + writers[split].fill >= caps[split]:
if split == 'valid':
stats['valid_over_cap'] += 1
continue
return
stats['bytes'][split] += len(raw)
yield split, text
start, done, stream = time.time(), 0, texts()
# Se envían bloques acotados de documentos: un map sobre todo el corpus lo cargaría entero en memoria.
with multiprocessing.Pool(args.workers, initializer=_worker_init, initargs=(ranks, eot)) as pool:
while chunk := list(itertools.islice(stream, 2048)):
for (split, _), (data, low, high, n) in zip(chunk, pool.map(_worker, [t for _, t in chunk], chunksize=64)):
if n and (low < 0 or high >= eot):
raise ValueError('ID fuera del vocabulario ordinario')
ids = np.frombuffer(data, dtype='<u2')
writers[split].add(np.concatenate([ids, np.array([eot], dtype='<u2')]))
done += len(chunk)
print(f'{done} documentos, tokens', {k: w.tokens + w.fill for k, w in writers.items()},
f'{time.time() - start:.0f} s', flush=True)
for w in writers.values():
w.flush()
env, l02_sha = l02()
manifest = {
'dataset': REPO, 'config': 'sample-10BT', 'revision': revision, 'sources': sources,
'split': 'sha256-primeros-8-bytes-modulo-10 (igual que p06-l02)', 'dedup': 'SHA-256 exacto del texto UTF-8',
'documents_read': stats['documents'], 'duplicates': stats['duplicates'], 'valid_docs_over_cap': stats['valid_over_cap'],
'eot_id': eot, 'dtype': '<u2', 'vocab_file': manifest02['vocab_file'], 'vocab_sha256': manifest02['vocab_sha256'],
'tokenizer_code_sha256': manifest02['tokenizer_code_sha256'], 'pipeline_code_sha256': l02_sha,
'parts': {k: {'documents': w.docs, 'tokens': w.tokens, 'bytes': stats['bytes'][k], 'shards': w.shards} for k, w in writers.items()},
'seconds': round(time.time() - start, 1)}
atomic_json(corpus / 'manifest.json', manifest)
print(json.dumps({k: v for k, v in manifest.items() if k != 'parts'}, ensure_ascii=False, indent=1))
for k, p in manifest['parts'].items():
print(f"{k}: {p['documents']} documentos, {p['tokens']} tokens, {p['bytes'] / max(p['tokens'], 1):.3f} bytes por token, {len(p['shards'])} shards")
def open_corpus(kind):
"""Devuelve rutas de shards, identidad del corpus, eot y tabla id -> bytes."""
manifest02, ranks, eot, rev = vocabulary()
if kind == 'l02':
folder, manifest = DATA02, manifest02
parts = {'train': manifest['parts']['train'], 'valid': manifest['parts']['valid']}
else:
folder = OUT / 'corpus'
manifest = json.loads((folder / 'manifest.json').read_text(encoding='utf-8'))
if manifest['vocab_sha256'] != manifest02['vocab_sha256']:
raise ValueError('El corpus se tokenizó con otro vocabulario: repite prepare')
parts = manifest['parts']
for part in parts.values():
for s in part['shards']:
p = folder / s['file']
if p.stat().st_size != 2 * s['tokens']:
raise ValueError(f'Shard incompleto: {p}')
identity = {'corpus': kind, 'vocab_sha256': manifest02['vocab_sha256'],
'shards': [s['sha256'] for part in parts.values() for s in part['shards']]}
paths = {k: [folder / s['file'] for s in parts[k]['shards']] for k in ('train', 'valid')}
return paths, identity, eot, rev
# ---------------------------------------------------------------- configuración
PRESETS = {
# Arquitectura de GPT-2 pequeño con el vocabulario propio; hiperparámetros de GPT-3 Small.
'full': dict(layers=12, heads=12, d=768, context=1024, dropout=0.0, micro_batch=4, batch_tokens=524288,
steps=3300, warmup=200, lr=6e-4, min_lr=6e-5, weight_decay=0.1, beta2=0.95, clip=1.0,
eval_every=100, eval_windows=160, monitor_every=10, sample_every=250, ckpt_every=50,
snapshot_every=500, keep=2, corpus='pretrain'),
# Comprobación de extremo a extremo en minutos.
'smoke': dict(layers=4, heads=4, d=256, context=256, dropout=0.0, micro_batch=8, batch_tokens=8192,
steps=120, warmup=10, lr=1e-3, min_lr=1e-4, weight_decay=0.1, beta2=0.95, clip=1.0,
eval_every=20, eval_windows=32, monitor_every=5, sample_every=60, ckpt_every=10,
snapshot_every=60, keep=2, corpus='l02'),
# Reanudación exacta y pico inducido: dropout activo para ejercitar los generadores.
'tiny': dict(layers=2, heads=4, d=128, context=128, dropout=0.1, micro_batch=4, batch_tokens=1024,
steps=40, warmup=5, lr=1e-3, min_lr=1e-4, weight_decay=0.1, beta2=0.95, clip=1.0,
eval_every=10, eval_windows=16, monitor_every=1, sample_every=0, ckpt_every=10,
snapshot_every=0, keep=100, corpus='l02'),
}
COMMON = dict(seed=1337, data_seed=42, deterministic=False, compile=False, max_temp=85, spike_k=5.0,
spike_rel=0.05, ema=0.05, spike_after=50, grad_ratio=2.5, throughput_drop=0.6, inject_step=-1, inject_kind='',
prompts=['The theory of evolution', 'In mathematics, a prime number', 'The French Revolution began'])
def build_config(args):
cfg = dict(COMMON, **PRESETS[args.preset], preset=args.preset)
for item in args.set or []:
key, value = item.split('=', 1)
if key not in cfg:
raise KeyError(f'Clave desconocida: {key}')
try:
cfg[key] = json.loads(value)
except json.JSONDecodeError:
cfg[key] = value
if args.deterministic:
cfg['deterministic'] = True
tokens_per_micro = cfg['micro_batch'] * cfg['context']
if cfg['batch_tokens'] % tokens_per_micro:
raise ValueError('batch_tokens debe ser múltiplo de micro_batch * context')
cfg['accum'] = cfg['batch_tokens'] // tokens_per_micro
if not 0 < cfg['warmup'] < cfg['steps']:
raise ValueError('Se exige 0 < warmup < steps')
cfg['run'] = args.run or cfg['preset']
return cfg
def lr_at(s, warmup, total, peak, floor):
"""Convención de p06-l04 con s = número de la actualización, 1 <= s <= total."""
if not (0 < warmup < total and 0 <= s <= total and 0 <= floor <= peak):
raise ValueError('parámetros del calendario inválidos')
if s < warmup:
return peak * s / warmup
return floor + 0.5 * (peak - floor) * (1 + math.cos(math.pi * (s - warmup) / (total - warmup)))
# ---------------------------------------------------------------- estado y checkpoints
def rng_state(torch):
np_state = np.random.get_state()
return {'python': random.getstate(), 'numpy': [np_state[0], np_state[1].tolist(), *np_state[2:]],
'torch': torch.get_rng_state(),
'cuda': torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []}
def set_rng_state(torch, state):
v, internal, gauss = state['python']
random.setstate((v, tuple(internal), gauss))
name, keys, pos, has_gauss, cached = state['numpy']
np.random.set_state((name, np.asarray(keys, dtype=np.uint32), pos, has_gauss, cached))
torch.set_rng_state(state['torch'])
if state['cuda']:
torch.cuda.set_rng_state_all(state['cuda'])
def save_checkpoint(run, torch, payload, keep, protected):
folder = run / 'checkpoints'
path = folder / f'ckpt-{payload["step"]:06d}.pt'
atomic_bytes(path, lambda f: torch.save(payload, f))
digest = file_sha256(path)
atomic_json(run / 'latest.json', {'step': payload['step'], 'file': path.name, 'sha256': digest})
olds = sorted(folder.glob('ckpt-*.pt'))
for old in olds[:-keep]:
if int(old.stem.split('-')[1]) not in protected:
old.unlink() # se borra solo después de publicar y apuntar al nuevo
return path
def load_checkpoint(run, torch, step=None):
if step is None:
latest = json.loads((run / 'latest.json').read_text(encoding='utf-8'))
path = run / 'checkpoints' / latest['file']
if file_sha256(path) != latest['sha256']:
raise ValueError('El checkpoint más reciente no coincide con latest.json')
else:
path = run / 'checkpoints' / f'ckpt-{step:06d}.pt'
# weights_only=True: solo tensores y tipos simples; un fichero ajeno no puede ejecutar código al cargarse.
return torch.load(path, map_location='cpu', weights_only=True)
# ---------------------------------------------------------------- bucle de entrenamiento
STOP = {'flag': False}
OMIT = set()
def gpu_status():
try:
out = subprocess.run(['nvidia-smi', '--query-gpu=temperature.gpu,power.draw,clocks.sm,utilization.gpu',
'--format=csv,noheader,nounits', '-i', os.environ.get('CUDA_VISIBLE_DEVICES', '0').split(',')[0]],
capture_output=True, text=True, timeout=10).stdout.strip().split(', ')
return {'temp_c': float(out[0]), 'power_w': float(out[1]), 'sm_mhz': float(out[2]), 'util': float(out[3])}
except Exception:
return None
class Trainer:
def __init__(self, cfg, run, out_metrics=None, save=True):
import torch
import torch.nn.functional as F
self.torch, self.F, self.cfg, self.run, self.save = torch, F, cfg, run, save
self.device = 'cuda' if torch.cuda.is_available() and not cfg.get('cpu') else 'cpu'
if cfg['deterministic']:
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
torch.backends.cuda.matmul.allow_tf32 = not cfg['deterministic']
self.paths, self.identity, self.eot, self.rev = open_corpus(cfg['corpus'])
env, model_sha = l03()
_, l02_sha = l02()
self.identity.update(model_code_sha256=model_sha, pipeline_code_sha256=l02_sha,
script_sha256=file_sha256(Path(__file__)))
torch.manual_seed(cfg['seed'])
self.vocab = self.eot + 1
self.model = env['GPT'](vocab=self.vocab, context=cfg['context'], layers=cfg['layers'], heads=cfg['heads'],
d=cfg['d'], dropout=cfg['dropout']).to(self.device).train()
decay, no_decay = [], []
for name, p in self.model.named_parameters():
(decay if p.ndim >= 2 and name not in ('transformer.wte.weight', 'transformer.wpe.weight') else no_decay).append(p)
self.opt = torch.optim.AdamW([{'params': decay, 'weight_decay': cfg['weight_decay']},
{'params': no_decay, 'weight_decay': 0.0}], lr=cfg['lr'],
betas=(0.9, cfg['beta2']), eps=1e-8, fused=self.device == 'cuda')
self.loader = env_l02()['TokenLoader'](self.paths['train'], cfg['micro_batch'], cfg['context'], seed=cfg['data_seed'])
self.forward = torch.compile(self.model) if cfg['compile'] else self.model
self.step, self.tokens = 0, 0
self.detector = {'mean': None, 'var': 0.0, 'gmean': None, 'n': 0, 'rates': []}
self.metrics = out_metrics or run / 'metrics.jsonl'
self.valid = self.valid_windows()
def backend(self):
from torch.nn.attention import sdpa_kernel, SDPBackend
if self.device != 'cuda' or self.cfg['deterministic']:
return sdpa_kernel(SDPBackend.MATH)
return sdpa_kernel([SDPBackend.CUDNN_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH])
def autocast(self):
import contextlib
if self.device == 'cuda':
return self.torch.autocast(device_type='cuda', dtype=self.torch.bfloat16)
return contextlib.nullcontext()
def valid_windows(self):
"""Ventanas fijas y consecutivas de validación: no consumen aleatoriedad."""
T, out = self.cfg['context'], []
for path in self.paths['valid']:
arr = np.memmap(path, dtype='<u2', mode='r')
for start in range(0, len(arr) - T, T):
out.append(np.array(arr[start:start + T + 1], dtype=np.int64))
if len(out) == self.cfg['eval_windows']:
break
if len(out) == self.cfg['eval_windows']:
break
rows = np.stack(out)
self.valid_bytes = int(sum(len(self.rev[int(t)]) for t in rows[:, 1:].ravel() if t != self.eot))
return rows
def state(self):
return {'step': self.step, 'tokens': self.tokens, 'model': self.model.state_dict(),
'optimizer': self.opt.state_dict(), 'loader': self.loader.state_dict(),
'rng': rng_state(self.torch), 'detector': self.detector, 'config': self.cfg, 'identity': self.identity}
def restore(self, state):
for key in ('config', 'identity'):
mine = {k: v for k, v in getattr(self, 'cfg' if key == 'config' else 'identity').items() if k not in ('cpu',)}
theirs = {k: v for k, v in state[key].items() if k not in ('cpu',)}
if key == 'identity':
mine.pop('script_sha256'); theirs.pop('script_sha256')
if mine != theirs:
diff = sorted(k for k in set(mine) | set(theirs) if mine.get(k) != theirs.get(k))
raise ValueError(f'El checkpoint no corresponde a esta {key}: {diff}')
self.model.load_state_dict(state['model'])
# OMIT solo existe para el control negativo de resume-test: demuestra que la prueba detecta el fallo.
if 'optimizer' not in OMIT:
self.opt.load_state_dict(state['optimizer'])
if 'loader' not in OMIT:
self.loader.load_state_dict(state['loader'])
if 'rng' not in OMIT:
set_rng_state(self.torch, state['rng'])
self.detector = state['detector']
self.step, self.tokens = state['step'], state['tokens']
@property
def protected(self):
p = self.run / 'protected.json'
return set(json.loads(p.read_text(encoding='utf-8'))) if p.exists() else set()
def checkpoint(self):
if self.save:
save_checkpoint(self.run, self.torch, self.state(), self.cfg['keep'], self.protected)
def batch(self, step):
position = (self.loader.epoch, self.loader.cursor)
xs = [self.loader.next() for _ in range(self.cfg['accum'])]
planned = (0, self.cfg['inject_step'] * self.cfg['accum'] * self.cfg['micro_batch'])
if self.cfg['inject_kind'] in ('random', 'repeat') and position == planned:
# Incidente inducido: el cargador entrega un lote anómalo en esa posición de los datos.
g = np.random.default_rng(self.cfg['inject_step'])
for i, (x, y) in enumerate(xs):
if self.cfg['inject_kind'] == 'random':
span = g.integers(0, self.eot, size=(x.shape[0], x.shape[1] + 1))
else: # 'repeat': un mismo fragmento de 32 tokens repetido hasta llenar la ventana
piece = np.concatenate([x[0, :32]] * (x.shape[1] // 32 + 1))[:x.shape[1] + 1]
span = np.tile(piece, (x.shape[0], 1))
xs[i] = (span[:, :-1], span[:, 1:])
return xs
@property
def T(self):
return self.cfg['context']
def attention_logit_max(self, x):
"""Máximo de q·k/sqrt(d_h) sobre posiciones causales, por bloque, en la primera secuencia."""
torch, inputs = self.torch, {}
hooks = [b.attn.register_forward_pre_hook(lambda m, a, i=i: inputs.__setitem__(i, a[0][:1].detach()))
for i, b in enumerate(self.model.transformer.h)]
try:
self.model.eval() # sin dropout: no consume el generador del entrenamiento
with torch.no_grad(), self.backend(), self.autocast():
self.model(x[:1])
self.model.train()
out = []
with torch.no_grad():
for i, block in enumerate(self.model.transformer.h):
h = inputs[i].float()
q, k, _ = block.attn.c_attn(h).float().split(self.cfg['d'], dim=-1)
H, dh = self.cfg['heads'], self.cfg['d'] // self.cfg['heads']
q = q.view(1, -1, H, dh).transpose(1, 2); k = k.view(1, -1, H, dh).transpose(1, 2)
s = (q @ k.transpose(-1, -2)) / math.sqrt(dh)
t = s.shape[-1]
mask = torch.ones(t, t, dtype=torch.bool, device=s.device).tril()
out.append(s.masked_fill(~mask, -float('inf')).amax().item())
return out
finally:
for h in hooks:
h.remove()
def evaluate(self):
torch, F = self.torch, self.F
self.model.eval()
total, count = 0.0, 0
with torch.no_grad(), self.backend(), self.autocast():
for i in range(0, len(self.valid), self.cfg['micro_batch']):
rows = torch.from_numpy(self.valid[i:i + self.cfg['micro_batch']]).to(self.device)
logits = self.forward(rows[:, :-1])
total += F.cross_entropy(logits.float().reshape(-1, self.vocab), rows[:, 1:].reshape(-1), reduction='sum').item()
count += rows[:, 1:].numel()
self.model.train()
loss = total / count
return {'step': self.step, 'tokens': self.tokens, 'val_loss': loss, 'targets': count,
'bits_per_byte': total / (math.log(2) * self.valid_bytes)}
def sample(self, prompt, length=120):
torch = self.torch
enc = getattr(self, 'encoder', None)
if enc is None:
_, ranks, eot, _ = vocabulary()
enc = self.encoder = l01_encoder(ranks, eot)
ids = enc(prompt)
g = torch.Generator(device=self.device).manual_seed(2026) # generador propio: no altera el del entrenamiento
self.model.eval()
with torch.no_grad(), self.backend(), self.autocast():
for _ in range(length):
x = torch.tensor([ids[-self.T:]], device=self.device)
logits = self.model(x)[0, -1].float()
top = torch.topk(logits, 50)
probs = torch.softmax(top.values / 0.8, dim=-1)
token = int(top.indices[torch.multinomial(probs, 1, generator=g)].item())
if token == self.eot:
break
ids.append(token)
self.model.train()
return b''.join(self.rev[i] for i in ids).decode('utf-8', errors='replace')
def describe(self, x):
ids = x[0]
text = b''.join(self.rev[int(t)] for t in ids[:400]).decode('utf-8', errors='replace')
return {'text': text, 'unique_token_ratio': round(len(set(ids.tolist())) / len(ids), 4),
'eot_count': int((ids == self.eot).sum())}
def event(self, kind, **detail):
row = {'step': self.step, 'tokens': self.tokens, 'kind': kind, 'time': time.strftime('%Y-%m-%d %H:%M:%S'), **detail}
append_jsonl(self.run / 'events.jsonl', row)
print('ALERTA', json.dumps(row, ensure_ascii=False)[:600], flush=True)
def train_step(self, lr_scale=1.0, skip=False):
torch, F, cfg = self.torch, self.F, self.cfg
s = self.step + 1
lr = lr_at(s, cfg['warmup'], cfg['steps'], cfg['lr'], cfg['min_lr']) * lr_scale
if cfg['inject_kind'] == 'lr' and cfg['inject_step'] < s <= cfg['inject_step'] + 5:
lr *= 30 # incidente inducido: cinco pasos con la tasa multiplicada por 30
for group in self.opt.param_groups:
group['lr'] = lr
loader_before = self.loader.state_dict()
if skip:
self.batch(self.step) # se descarta el lote de este paso
micro = self.batch(self.step)
monitor = cfg['monitor_every'] and s % cfg['monitor_every'] == 0
t0 = time.perf_counter()
losses = []
with self.backend():
for x, y in micro:
x = torch.from_numpy(np.ascontiguousarray(x)).to(self.device, non_blocking=True)
y = torch.from_numpy(np.ascontiguousarray(y)).to(self.device, non_blocking=True)
with self.autocast():
logits = self.forward(x)
loss = F.cross_entropy(logits.float().reshape(-1, self.vocab), y.reshape(-1))
(loss / cfg['accum']).backward()
losses.append(loss.detach())
losses = torch.stack(losses).float().cpu().tolist()
row = {'step': s, 'tokens': self.tokens + cfg['batch_tokens'], 'loss': sum(losses) / len(losses), 'lr': lr}
if monitor:
row['grad_norms'] = {f'bloque_{i}': math.sqrt(sum(p.grad.float().square().sum().item()
for p in b.parameters() if p.grad is not None)) for i, b in enumerate(self.model.transformer.h)}
row['attention_logit_max'] = max(self.attention_logit_max(torch.from_numpy(np.ascontiguousarray(micro[0][0])).to(self.device)))
norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), cfg['clip']).item()
row['grad_norm'] = norm
if not (math.isfinite(row['loss']) and math.isfinite(norm)):
worst = int(np.argmax([l if math.isfinite(l) else float('inf') for l in losses]))
self.event('no_finito', loss=row['loss'], grad_norm=norm, loader=loader_before, micro_losses=losses,
batch=self.describe(micro[worst][0]))
self.opt.zero_grad(set_to_none=True)
raise FloatingPointError('Pérdida o gradiente no finitos: evidencia guardada, sin actualizar')
self.opt.step()
self.opt.zero_grad(set_to_none=True)
if self.device == 'cuda':
torch.cuda.synchronize()
dt = time.perf_counter() - t0
self.step, self.tokens = s, row['tokens']
row.update(seconds=dt, tokens_per_second=cfg['batch_tokens'] / dt)
# Detectores: media y varianza exponenciales de la pérdida y media exponencial de la norma.
d, a = self.detector, cfg['ema']
alerts = []
if d['mean'] is not None and d['n'] >= cfg['spike_after']:
excess = row['loss'] - d['mean']
if excess > cfg['spike_k'] * math.sqrt(d['var']) and excess > cfg['spike_rel'] * d['mean']:
alerts.append(('pico', {'ema': d['mean'], 'sd': math.sqrt(d['var'])}))
if norm > cfg['grad_ratio'] * d['gmean']:
alerts.append(('norma', {'grad_norm_ema': d['gmean']}))
if alerts:
worst = int(np.argmax(losses))
row['batch'] = self.describe(micro[worst][0])
for kind, extra in alerts:
self.event(kind, loss=row['loss'], grad_norm=norm, micro_losses=losses, loader=loader_before,
batch=row['batch'], checkpoint=self.last_checkpoint(), **extra)
self.protect(self.last_checkpoint())
if d['mean'] is None:
d['mean'], d['gmean'] = row['loss'], norm
elif not alerts: # una anomalía no contamina la referencia
diff = row['loss'] - d['mean']
d['mean'] += a * diff
d['var'] = (1 - a) * (d['var'] + a * diff * diff)
d['gmean'] += a * (norm - d['gmean'])
d['n'] += 1
rates = d['rates'] = (d['rates'] + [row['tokens_per_second']])[-50:]
slow = len(rates) == 50 and row['tokens_per_second'] < cfg['throughput_drop'] * float(np.median(rates))
if slow and not d.get('slow'):
self.event('throughput', tokens_per_second=row['tokens_per_second'], median=float(np.median(rates)))
d['slow'] = slow
return row
def last_checkpoint(self):
p = self.run / 'latest.json'
return json.loads(p.read_text(encoding='utf-8'))['step'] if p.exists() else None
def protect(self, step):
if step is not None and self.save:
atomic_json(self.run / 'protected.json', sorted(self.protected | {step}))
def env_l02():
return l02()[0]
def report_memory(torch):
if torch.cuda.is_available():
print(f'memoria CUDA máxima reservada por tensores: {torch.cuda.max_memory_allocated() / 2**30:.2f} GiB', flush=True)
def run_training(cfg, hours=None, stop_after=None, fresh=False):
import torch
run = OUT / 'runs' / cfg['run']
if fresh and run.exists():
shutil.rmtree(run)
(run / 'checkpoints').mkdir(parents=True, exist_ok=True)
tr = Trainer(cfg, run)
if (run / 'latest.json').exists():
tr.restore(load_checkpoint(run, torch))
print(f'Reanudado tras el paso {tr.step} ({tr.tokens} tokens)', flush=True)
else:
atomic_json(run / 'config.json', {'config': cfg, 'identity': tr.identity})
tr.checkpoint() # estado del paso 0: permite repetir desde el principio
for name in ('metrics.jsonl', 'valid.jsonl', 'samples.jsonl', 'events.jsonl'):
truncate_jsonl(run / name, tr.step)
n = sum(p.numel() for p in tr.model.parameters())
print(f"parámetros {n}, acumulación {cfg['accum']}, tokens por paso {cfg['batch_tokens']}, plan {cfg['steps']} pasos", flush=True)
signal.signal(signal.SIGINT, lambda *a: STOP.__setitem__('flag', True))
start = time.time()
if tr.step == 0:
append_jsonl(run / 'valid.jsonl', tr.evaluate())
while tr.step < cfg['steps']:
if STOP['flag'] or (run / 'STOP').exists() or (hours and time.time() - start > 3600 * hours):
tr.checkpoint()
print(f'Pausa ordenada tras el paso {tr.step}: vuelve a lanzar train para continuar', flush=True)
return tr
try:
row = tr.train_step()
except FloatingPointError as error:
tr.protect(tr.last_checkpoint())
print(f'{error}. Reproduce desde el checkpoint {tr.last_checkpoint()} con replay.', flush=True)
sys.exit(3)
s = tr.step
if cfg['monitor_every'] and s % (cfg['monitor_every'] * 2) == 0 and tr.device == 'cuda':
status = gpu_status()
if status:
row['gpu'] = status
if status['temp_c'] >= cfg['max_temp']:
tr.event('temperatura', **status)
tr.checkpoint()
while (status := gpu_status()) and status['temp_c'] > cfg['max_temp'] - 10:
time.sleep(30)
append_jsonl(run / 'metrics.jsonl', row)
if s % max(1, cfg['monitor_every']) == 0 or s == 1:
print(f"paso {s} pérdida {row['loss']:.4f} norma {row['grad_norm']:.3f} lr {row['lr']:.2e} {row['tokens_per_second']:.0f} tok/s", flush=True)
if cfg['eval_every'] and (s % cfg['eval_every'] == 0 or s == cfg['steps']):
v = tr.evaluate()
append_jsonl(run / 'valid.jsonl', v)
print(f"validación paso {s}: {v['val_loss']:.4f} nats/token, {v['bits_per_byte']:.4f} bits/byte", flush=True)
if cfg['sample_every'] and (s % cfg['sample_every'] == 0 or s == cfg['steps']):
for prompt in cfg['prompts']:
append_jsonl(run / 'samples.jsonl', {'step': s, 'prompt': prompt, 'text': tr.sample(prompt)})
if s % cfg['ckpt_every'] == 0 or s == cfg['steps']:
tr.checkpoint()
if cfg['inject_kind'] and s <= cfg['inject_step'] < s + cfg['ckpt_every']:
tr.protect(s) # incidente inducido: se conserva el estado previo para reproducirlo
if cfg['snapshot_every'] and (s % cfg['snapshot_every'] == 0 or s == cfg['steps']):
snap = run / 'snapshots' / f'model-{s:06d}.pt'
atomic_bytes(snap, lambda f: torch.save({'step': s, 'tokens': tr.tokens, 'model': tr.model.state_dict(),
'config': cfg, 'identity': tr.identity}, f))
if stop_after and s >= stop_after:
tr.checkpoint()
print(f'Interrupción solicitada tras el paso {s}', flush=True)
report_memory(torch)
return tr
print('Plan completado', flush=True)
report_memory(torch)
return tr
def cmd_train(args):
args.preset = args.preset or 'full'
cfg = build_config(args)
run_training(cfg, hours=args.hours, stop_after=args.stop_after, fresh=args.fresh)
def subprocess_train(preset, run, extra, stop_after=None, fresh=False, omit=None):
cmd = [sys.executable, str(Path(__file__)), 'train', '--preset', preset, '--run', run, '--deterministic', *extra]
if omit:
cmd += ['--omit', omit]
if stop_after:
cmd += ['--stop-after', str(stop_after)]
if fresh:
cmd += ['--fresh']
env = dict(os.environ, PYTHONUTF8='1', CUBLAS_WORKSPACE_CONFIG=':4096:8')
result = subprocess.run(cmd, env=env, capture_output=True, text=True, encoding='utf-8')
if result.returncode:
print(result.stdout[-3000:], result.stderr[-3000:])
raise RuntimeError('falló el subproceso de entrenamiento')
return result.stdout
def cmd_resume_test(args):
"""Ejecución continua frente a otra que se corta en un proceso y continúa en otro."""
import torch
extra = []
for item in args.set or []:
extra += ['--set', item]
preset = args.preset or 'tiny'
steps = build_config(argparse.Namespace(preset=preset, set=args.set, deterministic=True, run='x'))['steps']
cut = args.stop_after or steps // 2
subprocess_train(preset, 'resume-continua', extra, fresh=True)
subprocess_train(preset, 'resume-cortada', extra, stop_after=cut, fresh=True)
subprocess_train(preset, 'resume-cortada', extra, omit=args.omit)
a = read_jsonl(OUT / 'runs/resume-continua/metrics.jsonl')
b = read_jsonl(OUT / 'runs/resume-cortada/metrics.jsonl')
keys = ('step', 'tokens', 'loss', 'lr', 'grad_norm')
same_losses = [tuple(r[k] for k in keys) for r in a] == [tuple(r[k] for k in keys) for r in b]
sa = load_checkpoint(OUT / 'runs/resume-continua', torch)
sb = load_checkpoint(OUT / 'runs/resume-cortada', torch)
same_params = all(torch.equal(sa['model'][k], sb['model'][k]) for k in sa['model'])
def same(x, y):
if isinstance(x, torch.Tensor):
return torch.equal(x, y)
if isinstance(x, dict):
return x.keys() == y.keys() and all(same(x[k], y[k]) for k in x)
if isinstance(x, (list, tuple)):
return len(x) == len(y) and all(same(u, v) for u, v in zip(x, y))
return x == y
same_opt = same(sa['optimizer'], sb['optimizer'])
same_loader = sa['loader'] == sb['loader']
first = next((r['step'] for r, q in zip(a, b) if r['loss'] != q['loss']), None)
print(f'Corte tras el paso {cut} de {steps}; pasos registrados {len(a)} y {len(b)}')
print('Pérdidas, tasas y normas idénticas bit a bit:', same_losses, '| primer paso distinto:', first)
print('Parámetros finales idénticos:', same_params, '| AdamW idéntico:', same_opt, '| cargador idéntico:', same_loader)
print('Pérdidas tras el corte:', [round(r['loss'], 6) for r in b if r['step'] > cut][:6])
ok = same_losses and same_params and same_opt and same_loader
if args.omit:
print(f'Control negativo sin restaurar {args.omit}: la prueba', 'NO detectó el fallo' if ok else 'detectó la divergencia')
if ok:
raise SystemExit(1)
elif not ok:
raise SystemExit(1)
def cmd_replay(args):
"""Reproduce desde un checkpoint conservado, con una sola intervención declarada."""
import torch
src = OUT / 'runs' / args.run
cfg = json.loads((src / 'config.json').read_text(encoding='utf-8'))['config']
name = args.name or f"{args.run}-desde-{args.from_step}-{args.intervention.replace('*', 'x')}"
out = OUT / 'replays' / name
if out.exists():
shutil.rmtree(out)
out.mkdir(parents=True)
tr = Trainer(cfg, src, out_metrics=out / 'metrics.jsonl', save=False)
tr.run = out
tr.restore(load_checkpoint(src, torch, args.from_step))
if args.intervention.startswith('lr*'):
label = f'tasa ×{float(args.intervention[3:])} en las actualizaciones {args.at} a {args.at + args.window - 1}'
elif args.intervention == 'skip':
label = f'saltar el lote de la actualización {args.at}'
elif args.intervention == 'none':
label = 'ninguna (misma reproducción)'
else:
raise ValueError("Intervención desconocida: usa none, skip o lr*FACTOR")
atomic_json(out / 'replay.json', {'run': args.run, 'checkpoint': f'{args.run}/ckpt-{args.from_step:06d}',
'intervention': label, 'at': args.at, 'steps': args.steps})
for _ in range(args.steps):
s = tr.step + 1
scale, skip = 1.0, False
if args.intervention.startswith('lr*') and args.at <= s < args.at + args.window:
scale = float(args.intervention[3:])
if args.intervention == 'skip' and s == args.at:
skip = True
row = tr.train_step(lr_scale=scale, skip=skip)
append_jsonl(out / 'metrics.jsonl', row)
print(f'{name}: {label}; pérdidas', [round(r["loss"], 4) for r in read_jsonl(out / "metrics.jsonl")])
def cmd_spike_demo(args):
"""Modelo pequeño, incidente inducido en la actualización 300 y reproducciones desde el checkpoint 290."""
extra = ['--set', 'steps=400', '--set', 'warmup=20', '--set', 'inject_step=299', '--set', f'inject_kind={args.kind}',
'--set', 'keep=3', '--set', 'eval_every=50', '--set', 'monitor_every=1']
run = f'demo-{args.kind}'
subprocess_train('tiny', run, extra, fresh=True)
for intervention, window in (('none', 1), ('skip', 1), ('lr*0.1', 5)):
cmd = [sys.executable, str(Path(__file__)), 'replay', '--run', run, '--from', '290', '--at', '300',
'--steps', '30', '--intervention', intervention, '--window', str(window), '--deterministic']
r = subprocess.run(cmd, env=dict(os.environ, PYTHONUTF8='1'), capture_output=True, text=True, encoding='utf-8')
print(r.stdout.strip()[-800:], r.stderr.strip()[-1500:] if r.returncode else '')
cmd_report(argparse.Namespace(run=run, replays=True))
def cmd_report(args):
run = OUT / 'runs' / args.run
metrics, valid = read_jsonl(run / 'metrics.jsonl'), read_jsonl(run / 'valid.jsonl')
events, samples = read_jsonl(run / 'events.jsonl'), read_jsonl(run / 'samples.jsonl')
def point(r):
p = {'step': r['step'], 'loss': r['loss'], 'grad_norm': r['grad_norm']}
if 'grad_norms' in r:
p['grad_norms'] = r['grad_norms']
if 'attention_logit_max' in r:
p['attention_logit_max'] = r['attention_logit_max']
if 'batch' in r:
b = r['batch']
p['batch'] = f"Proporción de tokens distintos {b['unique_token_ratio']}, separadores {b['eot_count']}.\n{b['text'][:400]}"
return p
keep = {e['step'] for e in events}
stride = max(1, len(metrics) // 4000)
pts = [point(r) for i, r in enumerate(metrics) if i % stride == 0 or r['step'] in keep or 'grad_norms' in r][:5000]
runs = [{'name': f'{args.run}, ejecución completa', 'points': pts}]
for rep in sorted((OUT / 'replays').glob(f'{args.run}-*')) if getattr(args, 'replays', True) and (OUT / 'replays').exists() else []:
meta = json.loads((rep / 'replay.json').read_text(encoding='utf-8'))
start = int(meta['checkpoint'].rsplit('-', 1)[1])
end = start + meta['steps']
if not any(r.get('checkpoint') == meta['checkpoint'] and 'intervention' not in r for r in runs):
runs.append({'name': f'{args.run}, original', 'checkpoint': meta['checkpoint'],
'points': [point(r) for r in metrics if start < r['step'] <= end]})
runs.append({'name': f'{args.run}, reproducción', 'checkpoint': meta['checkpoint'], 'intervention': meta['intervention'],
'points': [point(r) for r in read_jsonl(rep / 'metrics.jsonl')]})
report = {'source': f'p06-l06 pretrain.py, ejecución {args.run}', 'runs': runs}
atomic_json(run / 'forensics.json', report)
lines = [f'# Registro de incidencias de {args.run}', '']
for e in events:
lines.append(f"- paso {e['step']} ({e['time']}): {e['kind']} " + json.dumps({k: v for k, v in e.items() if k not in ('step', 'time', 'kind', 'loader', 'batch')}, ensure_ascii=False))
lines.append('')
lines.append('Completa a mano: hipótesis, reproducción, intervención aislada, resultado y decisión.')
atomic_bytes(run / 'incidents.md', lambda f: f.write('\n'.join(lines).encode('utf-8')))
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4.5))
tok = np.array([r['tokens'] for r in metrics], dtype=float) / 1e9
loss = np.array([r['loss'] for r in metrics])
if len(loss) > 20:
k = 20
ax.plot(tok[k - 1:], np.convolve(loss, np.ones(k) / k, mode='valid'), label='entrenamiento (media de 20 pasos)')
ax.plot([v['tokens'] / 1e9 for v in valid], [v['val_loss'] for v in valid], 'o-', label='validación')
ax.set_xlabel('miles de millones de tokens'); ax.set_ylabel('nats por token'); ax.legend(); ax.grid(alpha=0.3)
fig.tight_layout(); fig.savefig(run / 'curve.png', dpi=120); plt.close(fig)
except ImportError:
pass
if valid:
last = valid[-1]
print(f"validación final: paso {last['step']}, {last['tokens']} tokens, {last['val_loss']:.4f} nats/token, {last['bits_per_byte']:.4f} bits/byte")
print(f'{len(metrics)} pasos registrados, {len(events)} alertas, {len(samples)} muestras; informe en {run}')
def cmd_selftest(args):
"""Pruebas rápidas en CPU: calendario, escritura atómica, recorte del registro y reanudación."""
import torch
assert lr_at(1, 10, 100, 1e-3, 1e-4) == 1e-4 and lr_at(10, 10, 100, 1e-3, 1e-4) == 1e-3
assert abs(lr_at(100, 10, 100, 1e-3, 1e-4) - 1e-4) < 1e-18
env = env_l02()
texts = ['uno', 'dos', 'tres', 'uno', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve', 'diez', 'once']
train, valid, dup = env['dedup_split'](texts)
mine = {t: split_of(t.encode('utf-8'))[1] for t in texts}
assert sorted(train) == sorted(t for t in set(texts) if mine[t] == 'train') and dup == 1
with tempfile.TemporaryDirectory() as d:
d = Path(d)
atomic_json(d / 'a.json', {'x': 1})
try:
atomic_bytes(d / 'a.json', lambda f: (f.write(b'{"x": 2'), 1 / 0))
except ZeroDivisionError:
pass
assert json.loads((d / 'a.json').read_text()) == {'x': 1} and [p.name for p in d.iterdir()] == ['a.json']
for s in range(1, 6):
append_jsonl(d / 'm.jsonl', {'step': s})
with open(d / 'm.jsonl', 'a', encoding='utf-8') as f:
f.write('{"step": 6, "lo') # línea cortada por un apagón
truncate_jsonl(d / 'm.jsonl', 3)
assert [r['step'] for r in read_jsonl(d / 'm.jsonl')] == [1, 2, 3]
GPT = l03()[0]['GPT']
def make():
torch.manual_seed(0)
model = GPT(vocab=64, context=16, layers=1, heads=2, d=16, dropout=0.2)
return model, torch.optim.AdamW(model.parameters(), lr=1e-2)
data = torch.randint(0, 64, (12, 2, 17), generator=torch.Generator().manual_seed(1))
def go(model, opt, a, b):
out = []
for i in range(a, b):
opt.zero_grad()
loss = torch.nn.functional.cross_entropy(model(data[i][:, :-1]).reshape(-1, 64), data[i][:, 1:].reshape(-1))
loss.backward(); opt.step(); out.append(loss.item())
return out
m1, o1 = make(); full = go(m1, o1, 0, 12)
m2, o2 = make(); part = go(m2, o2, 0, 6)
with tempfile.TemporaryDirectory() as d:
run = Path(d)
save_checkpoint(run, torch, {'step': 6, 'model': m2.state_dict(), 'optimizer': o2.state_dict(), 'rng': rng_state(torch)}, 2, set())
state = load_checkpoint(run, torch)
m3, o3 = make()
torch.manual_seed(999) # se pisa a propósito: debe restaurarse
m3.load_state_dict(state['model']); o3.load_state_dict(state['optimizer']); set_rng_state(torch, state['rng'])
assert full == part + go(m3, o3, 6, 12), 'la reanudación en CPU no coincide'
print('selftest: calendario, partición, escritura atómica, registro y reanudación en CPU correctos')
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('command', choices=['selftest', 'prepare', 'train', 'resume-test', 'spike-demo', 'replay', 'report'])
p.add_argument('--preset', choices=sorted(PRESETS))
p.add_argument('--run'); p.add_argument('--set', action='append')
p.add_argument('--deterministic', action='store_true'); p.add_argument('--fresh', action='store_true')
p.add_argument('--hours', type=float); p.add_argument('--stop-after', type=int)
p.add_argument('--files', type=int, default=2); p.add_argument('--parquet', nargs='*')
p.add_argument('--max-train-tokens', type=int, default=1_800_000_000)
p.add_argument('--max-valid-tokens', type=int, default=20_000_000)
p.add_argument('--shard-tokens', type=int, default=100_000_000)
p.add_argument('--workers', type=int, default=int(os.environ.get('P06_WORKERS', '4')))
p.add_argument('--from', dest='from_step', type=int); p.add_argument('--at', type=int)
p.add_argument('--steps', type=int, default=20); p.add_argument('--window', type=int, default=1)
p.add_argument('--intervention', default='none'); p.add_argument('--name')
p.add_argument('--kind', default='random', choices=['random', 'repeat', 'lr'])
p.add_argument('--omit', choices=['optimizer', 'loader', 'rng'])
args = p.parse_args()
if args.omit and args.command == 'train':
OMIT.add(args.omit)
{'selftest': cmd_selftest, 'prepare': prepare, 'train': cmd_train, 'resume-test': cmd_resume_test,
'spike-demo': cmd_spike_demo, 'replay': cmd_replay, 'report': cmd_report}[args.command](args)
if __name__ == '__main__':
main()
'''
SCRIPT = LAB / 'pretrain.py'
SCRIPT.write_text(source.lstrip('\n'), encoding='utf-8')
(LAB / 'paths.json').write_text(json.dumps({'root': str(PROJECT), 'data': str(DATA)}, ensure_ascii=False),
encoding='utf-8')
def pretrain(*args):
"""Ejecuta una orden de pretrain.py en un proceso aparte y muestra su salida en vivo."""
env = dict(os.environ, PYTHONUTF8='1')
with subprocess.Popen([sys.executable, str(SCRIPT), *map(str, args)], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, encoding='utf-8', env=env) as proc:
for line in proc.stdout:
print(line, end='', flush=True)
if proc.returncode:
raise RuntimeError(f'pretrain.py {" ".join(map(str, args))} terminó con código {proc.returncode}')
print('Script:', SCRIPT, '|', len(source.splitlines()), 'líneas')
pretrain('selftest')npm run lab and open the connection link.The resumption test launches three deterministic processes using the tiny configuration, two blocks, dropout 0.1, and two microbatches per update: one continuous for 40 updates, one stopping after 20, and a third resuming from disk. It compares losses, rates, norms, final parameters, AdamW state, and loader state bit for bit. It then runs two negative controls that deliberately omit restoring generators or optimizer during resumption: a test that cannot detect those failures proves nothing.
pretrain('resume-test')
pretrain('resume-test', '--omit', 'rng')
pretrain('resume-test', '--omit', 'optimizer')npm run lab and open the connection link.In the short verification run, resumption matched bit for bit across all 40 updates, with identical parameters, AdamW, and loader. Without restoring generators, the first different loss was update 21: dropout on that pass already uses different numbers. Without restoring the optimizer, the first difference was update 22: loss 21 is computed before the update and matches, but update 21 itself differs. Both negative controls detected divergence.
The next cell reproduces panel data. It trains the small model for 400 updates with each of the three induced incidents, retains checkpoint 290, and launches three 30-update replays from it: unchanged, skipping batch 300, and multiplying rate by 0.1 during updates 300 to 304. Unchanged replay should match the original bit for bit; in verification it matched for all 30 updates in all three variants.
for kind in ('random', 'lr', 'repeat'):
pretrain('spike-demo', '--kind', kind)npm run lab and open the connection link.Corpus preparation resolves the current FineWeb-Edu repository revision, downloads the first two sample/10BT parquet files, 2.15 GB each, with HTTP-range resumption, and checks SHA-256 against the published value. It then applies the same exact deduplication and partition rule as p06-l02, tokenizes in parallel using the p06-l02 vocabulary, and stops at 1800 million training tokens; validation is capped at 20 million. Documents assigned to validation by the rule are never used for training even after that cap. Verified on the 1000 p06-l02 documents packaged as parquet with 50 duplicates added, it produced exactly the same 2204722 and 236708 tokens as p06-l02 and discarded all 50 duplicates. The p06-l01 encoder processed 2.4 to 3.6 MB of text per second per process on that sample, so with four processes, 3.7 GB of text should tokenize in about five to ten minutes, plus download and parquet reading.
pretrain('prepare', '--files', 2, '--workers', os.environ.get('P06_WORKERS', '4'))npm run lab and open the connection link.Launch long training from a terminal so it survives closing the browser. Each train command continues from latest.json if present and checks that configuration, code, and data match the checkpoint. --hours ends the session with a checkpoint when time expires. You can also create a STOP file in the run folder or press Ctrl+C, and the script saves at the end of the current update.
# Desde la carpeta que contiene p06_pretrain (cada noche, la misma orden):
# python p06_pretrain/pretrain.py train --preset full --hours 9
# Para parar antes, crea el fichero p06_pretrain/runs/full/STOP o pulsa Ctrl+C.
If you prefer the notebook, this cell runs a nine-hour session and can be repeated until the plan completes:
pretrain('train', '--preset', 'full', '--hours', 9)npm run lab and open the connection link.Before committing the first night, check output for first-update loss near , sustained rate matching your estimate, and memory away from the limit. On an out-of-memory error, lower micro_batch with --set micro_batch=2: accumulation is recalculated and the effective batch remains 524288 tokens. Changing configuration requires starting a new run, using --run with another name.
When an alert appears, replay reproduces from the protected checkpoint with one intervention, for example pretrain('replay', '--run', 'full', '--from', 2450, '--at', 2461, '--steps', 30, '--intervention', 'skip'), or 'lr*0.5' with --window to reduce rate for several steps. The full configuration does not use deterministic mode, which forces slower mathematical attention, so in the long run an unchanged replay ('none') will not match the original bit for bit. Always launch it: distance from the original measures background noise, and an intervention counts only if it clearly separates from that noise. At completion or any intermediate point, the report plots the curve and generates an incident log to complete manually and the panel JSON:
pretrain('report', '--run', 'full')
from IPython.display import Image
Image(filename=str(LAB / 'runs' / 'full' / 'curve.png'))npm run lab and open the connection link.The lesson’s verifiable result has three parts: the full validation-loss curve in nats per token and bits per byte; the interprocess exact-resumption test; and incidents.md with each alert accompanied by hypothesis, replay, isolated intervention, and decision. If there is no spike, record that too.
Exercises
import json
import os
import tempfile
from pathlib import Path
def save_checkpoint(path, state):
pass
def load_checkpoint(path):
passA long run can be interrupted without loss if its checkpoint contains all state needed by the next step and is written atomically. The interprocess test and negative controls demonstrate this in your environment. Alerts detect anomalies; a replay from the previous checkpoint changing one thing establishes their cause.