Pretraining a small LLM end to end
Build a reproducible pretraining pipeline using binary token shards and memory-mapped windows, set a token budget, train with a WSD schedule, monitor domain losses, and resume checkpoints.
After this lesson you can
- Build a resumable pipeline that tokenizes data, writes unsigned integer shards, and serves deterministic memory-mapped windows.
- Set the token budget, token batch size, and step count from measured throughput and available GPU time.
- Train a 30 to 60 million parameter decoder using WSD and a final cooldown on selected data.
- Monitor per-domain validation bits per byte, gradient norms, samples, and a multiple-choice check at checkpoints.
- Diagnose data bottlenecks, loss spikes, and divergence, and resume a checkpoint exactly.
Before you start
- 20Causal language modeling objectiveToken-level loss accountingByte-level BPESpecial tokensTokenizer compression metrics
- 18Transformer training recipeResidual-scaled initializationLlama-style block
- 06Learning-rate schedulesMinibatch gradient variance and gradient noise scale
- 15Learning rate warmupOutput logit divergenceLoss spikesCritical batch size
- 00Training memory budgetAutomatic mixed precision in PyTorchFull training checkpointExact resumption
A training run that can be reconstructed
The objective is more than obtaining a weight file: you need to know which texts and tokens were used, how many updates ran, and how to continue after interruption. This lesson prepares a binary stream, trains a small decoder, and records evaluations. The full training run is for your machine. The included check reduces model and steps to verify the pipeline without presenting that test as a finished model.
From documents to windows
A token-stream loader transforms documents into binary shards and supplies training windows. Order matters: identify and split documents before creating windows, train the tokenizer only on training data, and keep validation by domain. Splitting windows from the same document across train and validation can leak text. A hash detects exact duplicates, not near duplicates or contamination from other sources.
TinyStories contains synthetic stories generated to study small models. FineWeb-Edu is an educational selection of web text. Their distributions, licenses, and storage requirements differ. A quality label is a selection criterion, not a guarantee that every document is correct. Record version, hash, provenance, and split; retain original validation documents to count their bytes.
Train byte-level BPE and serialize IDs as uint16 if the largest ID is at most 65,535; with dense IDs that permits up to 65,536 distinct values. The end-of-document token also occupies an ID and must count toward the limit. If a larger ID is needed, use uint32; a silent cast to uint16 changes it. Memory mapping allows access to a shard without copying the entire corpus. If windows may cross document separators, the model trains under that stream convention; if isolation is required, construct and use segment masks.
For resumption, one option makes the batch a deterministic function of seed, step, and microbatch, weighting shards by valid starting positions. The checkpoint must record the manifest and configuration that give those indices meaning. A seed alone does not recover an advanced stateful generator or prefetch queue. Check the next batch and optimizer states when comparing continuous and interrupted runs.
Compute, batch, and time
Token budget and parameter count give a rough approximation of training FLOPs. Long attention, vocabulary projection, and embedding parameters can change cost, especially in small models. State whether includes them and use a more detailed count when needed. The ratio alone does not determine quality; it depends on data, tokenizer, and objective. Chinchilla results are a reference for their regime, not a universal threshold.
Ideal time for tokens and sustained rate is . Measure in your complete run, including loading, copying, and updates. Do not extrapolate an isolated kernel measurement or treat shared-GPU timings as fixed. Allow for validation, checkpoints, and pauses. The token batch size per step is context × sequences per microbatch × accumulated microbatches, if all positions are valid. With variable lengths or masks, count valid targets and normalize as in loss accounting.
Doubling workers or using pinned memory does not guarantee improvement. Compare reading, preparation, copying, and compute with a profiler. Low GPU utilization may mean waiting for data, but may also reflect other operations or shared load. Change one variable at a time and measure the full path. Batch size and any ramp are hyperparameters: a larger batch can change statistical dynamics even when throughput increases.
WSD and cooldown
Cooldown or annealing reduces the learning rate after warmup and a plateau. With warmup-stable-decay, WSD, several budgets can share a stable phase and end with their own declines if suitable states are saved. A decay does not guarantee that every data change improves the model. MiniCPM and Hägele and colleagues study stable-and-decay schedules; count the cost and shape of each branch.
A subset chosen for the final phase can weight text considered useful more heavily, but changing rate and data simultaneously does not by itself attribute improvement to either. To support that claim, compare branches from the same checkpoint that change one variable. With a fixed budget, reserve steps and validation data for decay in advance; do not choose the best checkpoint on the test set.
What to monitor at each checkpoint
Pretraining monitoring combines loss by domain, sample size, learning rate, gradient norm before clipping, accumulated tokens, and generated examples. To compare tokenizers, sum loss in nats on the same reconstructed texts and divide by and their UTF-8 bytes. State the initial context, resets for long text, and whether EOS is scored. Special tokens do not necessarily have ordinary-text bytes to add to the denominator.
A loss spike requires preserving the batch, rate, and previous checkpoint. Repeat from that state and change one variable to investigate; skipping batches or reducing the rate changes the experiment and must be recorded. For NaN or nonfinite gradients, avoid the update and preserve evidence. Logit regularization can be a tool in specific recipes, not an automatic explanation for any spike. A small validation set or one generated sample may fluctuate substantially: report denominators and do not turn tiny differences into conclusions.
Exact resumption requires weights, optimizer, schedule or enough step information to reconstruct it, token count, configuration, and generator states. Save after an update, not during accumulation, unless partial gradients are also saved. Compare the next batch, rate, losses, and states in the same environment. Bitwise identity is not promised across versions, devices, or kernels. See exact resumption.
Lab: preparing and serving data
The pipeline streams only requested documents from TinyStories and FineWeb-Edu. TinyStories’ card declares CDLA-Sharing 1.0 and FineWeb-Edu’s ODC-By; also consult terms applicable to original data. A revision of each repository is pinned and recorded in the manifest. Full training defaults to 200,000 stories and 10,000 educational documents, configurable with ORYON_TINY_DOCS and ORYON_FINE_DOCS. The short test can supply two local Parquet files with an text column through ORYON_LOCAL_PARQUET and ORYON_LOCAL_FINE_PARQUET; their SHA-256 identifies those sources and replaces the remote-revision guarantee. Install datasets, tokenizers, pyarrow, and numpy locally.
The split is computed from the text hash before tokenizer training, so an exact duplicate across both sources falls in the same split. This does not detect near duplicates. Byte-level BPE is trained only on training documents from both sources, with an EOT ID reserved outside the ordinary vocabulary. If the maximum ID does not fit uint16, switch to uint32. Shards use little-endian byte order. Documents are concatenated with EOT, but attention is not blocked between them. Seed, step, and microbatch index determine windows; the manifest and each shard have SHA-256 hashes.
The code runs as an independent script because Windows needs to import child-process functions for multiprocessing. ORYON_DATA_DIR must point to an empty directory. Code is saved alongside the manifest for reuse; the short test does not require downloading the full corpus. JSONL validation files retain each document and hash to measure actual UTF-8 bytes and calculate bits per byte without EOT. Reader tokens per second are a variable local measurement; compare with GPU throughput under the same batch and machine.
import os, subprocess, sys, tempfile
from pathlib import Path
source = r'''"""Pipeline de documentos, fragmentos binarios y ventanas reproducibles.
Instalar: pip install datasets tokenizers pyarrow numpy
"""
import hashlib
import json
import os
import time
from collections import deque
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import numpy as np
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
TINY_REV = 'f54c09fd23315a6f9c86f9dc80f725de7d8f9c64'
FINE_REV = '87f09149ef4734204d70ed1d046ddc9ca3f2b8f9'
ROOT = Path(os.environ.get('ORYON_DATA_DIR', './oryon-data'))
LOCAL_PARQUET = os.environ.get('ORYON_LOCAL_PARQUET')
LOCAL_FINE_PARQUET = os.environ.get('ORYON_LOCAL_FINE_PARQUET')
QUICK = os.environ.get('ORYON_QUICK') == '1'
VOCAB_SIZE = int(os.environ.get('ORYON_VOCAB_SIZE', '2048' if QUICK else '16000'))
TINY_DOCS = int(os.environ.get('ORYON_TINY_DOCS', '512' if QUICK else '200000'))
FINE_DOCS = int(os.environ.get('ORYON_FINE_DOCS', '40' if QUICK else '10000'))
TOKENIZER_DOCS = int(os.environ.get('ORYON_TOKENIZER_DOCS', '300' if QUICK else '50000'))
SHARD_TOKENS = int(os.environ.get('ORYON_SHARD_TOKENS', '4096' if QUICK else '2000000'))
WORKERS = int(os.environ.get('ORYON_WORKERS', '2'))
VAL_PER_THOUSAND = int(os.environ.get('ORYON_VAL_PER_THOUSAND', '100' if QUICK else '10'))
MAX_CHARS = 200000
def sha256_file(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def digest_text(text):
return hashlib.sha256(text.encode('utf-8')).digest()
def split_text(text):
"""Duplicados exactos en cualquier dominio caen en la misma partición."""
return 'validation' if int.from_bytes(digest_text(text)[:8], 'big') % 1000 < VAL_PER_THOUSAND else 'train'
def documents(domain):
limit = TINY_DOCS if domain == 'tiny' else FINE_DOCS
if limit <= 0:
return
local_path = LOCAL_PARQUET if domain == 'tiny' else LOCAL_FINE_PARQUET
if local_path:
import pyarrow.parquet as pq
batches = pq.ParquetFile(local_path).iter_batches(batch_size=128, columns=['text'])
def local_rows():
for batch in batches:
yield from batch.column(0).to_pylist()
rows = local_rows()
else:
from datasets import load_dataset
if domain == 'tiny':
ds = load_dataset('roneneldan/TinyStories', split='train', streaming=True, revision=TINY_REV)
else:
ds = load_dataset('HuggingFaceFW/fineweb-edu', name='sample-10BT', split='train', streaming=True, revision=FINE_REV)
rows = (row['text'] for row in ds)
count = 0
for text in rows:
if isinstance(text, str) and 0 < len(text) <= MAX_CHARS:
yield text
count += 1
if count >= limit:
break
def train_tokenizer(path):
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tok.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer(vocab_size=VOCAB_SIZE, min_frequency=2,
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), show_progress=False)
def training_texts():
seen = 0
sources = deque(iter(text for text in documents(domain) if split_text(text) == 'train')
for domain in ('tiny', 'fineweb'))
while sources and seen < TOKENIZER_DOCS:
source = sources.popleft()
try:
text = next(source)
except StopIteration:
continue
yield text
seen += 1
sources.append(source)
tok.train_from_iterator(training_texts(), trainer=trainer)
tok.save(str(path))
return tok
_WORKER_TOKENIZER = None
def init_worker(tokenizer_path):
global _WORKER_TOKENIZER
_WORKER_TOKENIZER = Tokenizer.from_file(tokenizer_path)
def encode_block(block):
# No hay tokens especiales registrados que puedan coincidir con texto literal.
return [_WORKER_TOKENIZER.encode(text, add_special_tokens=False).ids for text in block]
def blocks(iterator, size=32):
batch = []
for text in iterator:
batch.append(text)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
def ordered_encode(executor, iterator, queue_size):
"""Cola acotada, resultado en orden de origen pese al multiproceso."""
pending = deque()
for block in blocks(iterator):
pending.append((block, executor.submit(encode_block, block)))
if len(pending) >= queue_size:
original, future = pending.popleft()
yield original, future.result()
while pending:
original, future = pending.popleft()
yield original, future.result()
class ShardWriter:
def __init__(self, root, domain, split, dtype):
self.root, self.domain, self.split, self.dtype = root, domain, split, np.dtype(dtype)
self.parts, self.size, self.shards = [], 0, []
self.docs, self.bytes = 0, 0
self.val_file = None
if split == 'validation':
self.val_path = f'{domain}-validation.jsonl'
self.val_file = (root / self.val_path).open('w', encoding='utf-8', newline='\n')
def add(self, text, ids, eot):
self.docs += 1
self.bytes += len(text.encode('utf-8'))
if self.val_file:
self.val_file.write(json.dumps({'text': text, 'sha256': digest_text(text).hex()}, ensure_ascii=False) + '\n')
all_ids = [*ids, eot]
if min(all_ids) < 0 or max(all_ids) > np.iinfo(self.dtype).max:
raise ValueError('El vocabulario excede el entero elegido')
arr = np.asarray(all_ids, dtype=self.dtype)
pos = 0
while pos < len(arr):
n = min(len(arr) - pos, SHARD_TOKENS - self.size)
self.parts.append(arr[pos:pos+n])
self.size += n
pos += n
if self.size == SHARD_TOKENS:
self.flush()
def flush(self):
if self.size == 0:
return
name = f'{self.domain}-{self.split}-{len(self.shards):05d}.bin'
path = self.root / name
np.concatenate(self.parts).tofile(path)
self.shards.append({'path': name, 'tokens': self.size, 'sha256': sha256_file(path)})
self.parts, self.size = [], 0
def close(self):
self.flush()
result = {'shards': self.shards, 'documents': self.docs, 'bytes': self.bytes}
if self.val_file:
self.val_file.close()
result['validation_jsonl'] = self.val_path
result['validation_sha256'] = sha256_file(self.root / self.val_path)
return result
def build_pipeline():
if not 1 <= VAL_PER_THOUSAND <= 999 or SHARD_TOKENS < 2 or WORKERS < 1:
raise ValueError('Configuración inválida')
if ROOT.exists() and any(ROOT.iterdir()):
raise FileExistsError('Elige un directorio de salida vacío para no sobrescribir datos')
ROOT.mkdir(parents=True, exist_ok=True)
path = ROOT / 'tokenizer.json'
tok = train_tokenizer(path)
vocab = tok.get_vocab_size()
eot = vocab # ID reservado fuera del vocabulario ordinario.
dtype = dtype_for_max_id(eot)
print('Vocabulario ordinario:', vocab, 'EOT:', eot, 'tipo:', dtype, flush=True)
groups = {}
with ProcessPoolExecutor(max_workers=WORKERS, initializer=init_worker, initargs=(str(path),)) as pool:
for domain in ('tiny', 'fineweb'):
writers = {split: ShardWriter(ROOT, domain, split, dtype) for split in ('train', 'validation')}
for texts, encoded in ordered_encode(pool, documents(domain), max(2, 2 * WORKERS)):
for text, ids in zip(texts, encoded):
writers[split_text(text)].add(text, ids, eot)
for split, writer in writers.items():
groups[f'{domain}/{split}'] = writer.close()
local_meta = {name: {'path': str(Path(path).resolve()), 'sha256': sha256_file(path)}
for name, path in (('tiny', LOCAL_PARQUET), ('fineweb', LOCAL_FINE_PARQUET)) if path}
manifest = {'version': 1, 'dtype': dtype,
'tokenizer': {'path': 'tokenizer.json', 'sha256': sha256_file(path),
'vocab_size': vocab, 'ordinary_vocab_size': vocab,
'model_vocab_size': vocab + 1, 'max_token_id': eot, 'eot_id': eot},
'groups': groups,
'sources': {'tiny': {'repo': 'roneneldan/TinyStories', 'revision': TINY_REV, 'limit': TINY_DOCS},
'fineweb': {'repo': 'HuggingFaceFW/fineweb-edu', 'revision': FINE_REV,
'config': 'sample-10BT', 'limit': FINE_DOCS},
'local_parquet': local_meta},
'split': {'method': 'sha256 text UTF-8, first 8 bytes modulo 1000', 'validation_per_thousand': VAL_PER_THOUSAND},
'note': 'Documentos contiguos separados por EOT; atención entre documentos no bloqueada.'}
(ROOT / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8')
print('Documentos por grupo:', {k: v['documents'] for k, v in groups.items()}, flush=True)
print('Manifiesto:', ROOT / 'manifest.json', flush=True)
return manifest
def dtype_for_max_id(max_id):
if not 0 <= max_id <= np.iinfo(np.uint32).max:
raise ValueError('ID fuera de rango para uint32')
return '<u2' if max_id <= np.iinfo(np.uint16).max else '<u4'
class WindowSampler:
"""Muestreo uniforme sobre comienzos válidos, sin cruzar shards."""
def __init__(self, root, group, length, seed):
self.root, self.group, self.length, self.seed = Path(root), group, int(length), int(seed)
if self.length <= 0 or self.seed < 0:
raise ValueError('Longitud o semilla inválida')
self.manifest_path = self.root / 'manifest.json'
self.manifest_hash = sha256_file(self.manifest_path)
manifest = json.loads(self.manifest_path.read_text(encoding='utf-8'))
self.dtype = np.dtype(manifest['dtype'])
self.arrays, self.ends = [], []
total = 0
for info in manifest['groups'][group]['shards']:
starts = info['tokens'] - self.length
if starts <= 0:
continue
path = self.root / info['path']
if path.stat().st_size != info['tokens'] * self.dtype.itemsize:
raise ValueError('Tamaño de shard incorrecto')
if sha256_file(path) != info['sha256']:
raise ValueError('El contenido del shard no coincide con el manifiesto')
self.arrays.append(np.memmap(path, mode='r', dtype=self.dtype))
total += starts
self.ends.append(total)
if total <= 0:
raise ValueError('No hay shards con ventanas completas')
self.total = total
def batch(self, step, micro, batch_size):
if step < 0 or micro < 0 or batch_size <= 0:
raise ValueError('Índices o tamaño inválidos')
key = f'{self.seed}:{step}:{micro}'.encode('ascii')
entropy = int.from_bytes(hashlib.sha256(key).digest()[:16], 'little')
rng = np.random.default_rng(entropy)
positions = rng.integers(0, self.total, size=batch_size)
xs, ys = [], []
for pos in positions:
shard = int(np.searchsorted(self.ends, pos, side='right'))
start = int(pos) - (self.ends[shard-1] if shard else 0)
window = np.array(self.arrays[shard][start:start+self.length+1], dtype=np.int64)
xs.append(window[:-1])
ys.append(window[1:])
return np.stack(xs), np.stack(ys)
def checkpoint(self, next_step, next_micro=0):
return {'manifest_sha256': self.manifest_hash, 'group': self.group,
'length': self.length, 'seed': self.seed,
'next_step': int(next_step), 'next_micro': int(next_micro)}
def validate_checkpoint(self, state):
expected = self.checkpoint(state['next_step'], state['next_micro'])
if state != expected:
raise ValueError('El checkpoint no corresponde a este sampler o manifiesto')
if __name__ == '__main__':
build_pipeline()
sampler = WindowSampler(ROOT, 'tiny/train', length=32 if QUICK else 256, seed=2007)
start = time.perf_counter()
for step in range(10):
x, y = sampler.batch(step, 0, 8)
assert np.array_equal(x[:, 1:], y[:, :-1])
elapsed = time.perf_counter() - start
print('Lector: tokens/s de CPU observados:', round(10 * x.size / elapsed), flush=True)
print('La comparación con la GPU requiere medir su rendimiento en el mismo equipo.', flush=True)
'''
with tempfile.TemporaryDirectory(prefix='oryon-data-code-') as temporary:
script = Path(temporary) / 'data_pipeline.py'
script.write_text(source, encoding='utf-8')
result = subprocess.run([sys.executable, str(script)], capture_output=True,
text=True, encoding='utf-8', errors='replace')
print(result.stdout, end='')
if result.returncode:
raise RuntimeError(result.stderr)
root = Path(os.environ.get('ORYON_DATA_DIR', './oryon-data'))
(root / 'data_pipeline.py').write_text(source, encoding='utf-8')
namespace = {'__name__': 'oryon_data_pipeline'}
exec(compile(source, str(root / 'data_pipeline.py'), 'exec'), namespace)
WindowSampler = namespace['WindowSampler']
npm run lab and open the connection link.The tokenizer contains only ordinary IDs. EOT is inserted explicitly and is not a special string recognized in the text. The manifest distinguishes ordinary_vocab_size, model_vocab_size, and max_token_id: the model’s input and output dimension is model_vocab_size = eot_id + 1. Save model and optimizer parameters, scheduler state, and sampler state in each checkpoint. With gradient accumulation, also preserve or restore microbatch position, batch size, and any training random state. Check that the manifest has not changed before continuing.
sampler = WindowSampler(root, 'tiny/train', length=32, seed=2007)
x, y = sampler.batch(step=3, micro=2, batch_size=8)
state = sampler.checkpoint(next_step=3, next_micro=2)
restored = WindowSampler(root, 'tiny/train', length=32, seed=2007)
restored.validate_checkpoint(state)
xp, yp = restored.batch(state['next_step'], state['next_micro'], batch_size=8)
assert (x == xp).all() and (y == yp).all()
assert (x[:, 1:] == y[:, :-1]).all()
print('Ventanas y desplazamiento reproducidos:', x.shape)npm run lab and open the connection link.Short mode checks documents, hashes, and resumption exhaustively:
# En corpora grandes se evita materializar los documentos para QA.
import json
manifest = json.loads((root / 'manifest.json').read_text(encoding='utf-8'))
num_tokens = sum(shard['tokens'] for group in manifest['groups'].values() for shard in group['shards'])
if os.environ.get('ORYON_QUICK') == '1' and num_tokens <= 1_000_000:
checks = r'''"""Comprobaciones de un pipeline ya construido, sin descargar ni entrenar."""
import hashlib
import json
from pathlib import Path
import numpy as np
from tokenizers import Tokenizer
ROOT = root
dtype_for_max_id = namespace['dtype_for_max_id']
sha256_file = namespace['sha256_file']
manifest = json.loads((ROOT / 'manifest.json').read_text(encoding='utf-8'))
tok_meta = manifest['tokenizer']
assert sha256_file(ROOT / tok_meta['path']) == tok_meta['sha256']
tokenizer = Tokenizer.from_file(str(ROOT / tok_meta['path']))
assert tokenizer.get_vocab_size() == tok_meta['vocab_size']
assert tok_meta['eot_id'] == tok_meta['vocab_size']
assert tok_meta['ordinary_vocab_size'] == tok_meta['vocab_size']
assert tok_meta['model_vocab_size'] == tok_meta['eot_id'] + 1
assert tok_meta['max_token_id'] == tok_meta['eot_id']
assert dtype_for_max_id(65535) == '<u2' and dtype_for_max_id(65536) == '<u4'
assert dtype_for_max_id(tok_meta['eot_id']) == manifest['dtype']
try:
dtype_for_max_id(2**32)
except ValueError:
pass
else:
raise AssertionError('uint32 debe rechazar overflow')
by_split = {'train': set(), 'validation': set()}
total_docs = total_tokens = 0
for group, info in manifest['groups'].items():
split = group.split('/')[1]
data = []
for shard in info['shards']:
path = ROOT / shard['path']
assert sha256_file(path) == shard['sha256']
array = np.fromfile(path, dtype=np.dtype(manifest['dtype']))
assert len(array) == shard['tokens']
data.extend(int(x) for x in array)
total_tokens += len(array)
docs, previous = [], 0
for i, value in enumerate(data):
if value == tok_meta['eot_id']:
docs.append(tokenizer.decode(data[previous:i], skip_special_tokens=False))
previous = i + 1
else:
assert 0 <= value < tok_meta['vocab_size']
assert previous == len(data)
assert len(docs) == info['documents']
assert sum(len(d.encode('utf-8')) for d in docs) == info['bytes']
for text in docs:
digest = hashlib.sha256(text.encode('utf-8')).digest()
threshold = manifest['split']['validation_per_thousand']
actual = 'validation' if int.from_bytes(digest[:8], 'big') % 1000 < threshold else 'train'
assert actual == split
by_split[split].add(digest)
if split == 'validation':
path = ROOT / info['validation_jsonl']
assert sha256_file(path) == info['validation_sha256']
rows = [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()]
assert [r['text'] for r in rows] == docs
assert all(r['sha256'] == hashlib.sha256(r['text'].encode('utf-8')).hexdigest() for r in rows)
total_docs += len(docs)
assert by_split['train'].isdisjoint(by_split['validation'])
sampler = WindowSampler(ROOT, 'tiny/train', length=32, seed=2007)
assert sampler.total == sum(max(0, s['tokens'] - 32) for s in manifest['groups']['tiny/train']['shards'])
for step in range(5):
for micro in range(3):
x, y = sampler.batch(step, micro, 8)
assert x.shape == y.shape == (8, 32)
assert np.array_equal(x[:, 1:], y[:, :-1])
assert np.array_equal(x, sampler.batch(step, micro, 8)[0])
assert not np.array_equal(sampler.batch(1, 0, 8)[0], sampler.batch(1, 1, 8)[0])
state = sampler.checkpoint(next_step=3, next_micro=2)
sampler2 = WindowSampler(ROOT, 'tiny/train', length=32, seed=2007)
sampler2.validate_checkpoint(state)
assert all(np.array_equal(a, b) for a, b in zip(sampler.batch(3, 2, 8), sampler2.batch(3, 2, 8)))
for bad in (dict(state, seed=2008), dict(state, length=33), dict(state, manifest_sha256='bad')):
try:
sampler2.validate_checkpoint(bad)
except ValueError:
pass
else:
raise AssertionError('Checkpoint incompatible aceptado')
print('QA: documentos', total_docs, 'tokens', total_tokens,
'entrenamiento y validación disjuntos por texto, EOT y UTF-8 recuperados')
print('QA: hashes, límites uint16/uint32, ventanas y reanudación por paso y micro-lote correctos')
'''
exec(compile(checks, '<qa-datos>', 'exec'), globals())
else:
print('QA de reconstrucción exhaustiva omitida: usa una muestra corta de hasta 1 000 000 de tokens.')
npm run lab and open the connection link.Lab: training and resuming
This cell consumes the manifest and shards from the previous section. Since the m18 implementation may not yet be available, you build a standalone decoder with RMSNorm, RoPE, SwiGLU, causal attention, and shared embeddings. With the full vocabulary its eight blocks have on the order of tens of millions of parameters; the report prints the exact count. PyTorch, NumPy, and tokenizers are required locally.
The full configuration processes approximately 500 million tokens, counting repetitions, with context 256 and 16,384 tokens per update. Adjust ORYON_STEPS before starting according to observed throughput and your budget. By default, the two domains alternate during the plateau and FineWeb-Edu is reserved for final decay. This is an experimental recipe, not a causal demonstration that changing the mixture improves results. Periodic evaluations compare checkpoints before and after decay, subject to noise from limited samples.
Set ORYON_QUICK=1 to check the installation end to end: use a small model and corpus, run four steps, and compare a continuous trajectory with one interrupted at step two. In our short run, losses, weights, and optimizer state matched exactly in the same environment. These are not results of a trained model. bfloat16 precision is enabled on CUDA; ORYON_COMPILE=1 is an option for testing compilation in the full run.
Each checkpoint retains AdamW and generator states as well as step, configuration, and manifest hash. Windows are reconstructed from seed, step, and microbatch. The equality check concerns the same environment and does not guarantee bitwise reproducibility across versions, devices, or kernels. Use ORYON_RESUME=1 with the same output directory and plan to continue; load only your own checkpoints because they contain Python objects.
Validation sums loss in nats and divides by original bytes and ln(2). Long documents are split into blocks with reset context, and the three multiple-choice questions are a minimal diagnostic, not a benchmark. Training windows can cross documents separated by EOT: attention is not blocked at that boundary. If a nonfinite value appears, the program stops the update and identifies step and microbatch. Investigate data and rate before deciding how to recover the run.
"""Decoder pequeño con datos memmap, WSD y recuperación determinista."""
import copy
import gc
import hashlib
import json
import math
import os
import random
import time
from contextlib import nullcontext
from pathlib import Path
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tokenizers import Tokenizer
DATA = Path(os.environ.get('ORYON_DATA_DIR', './oryon-data'))
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './oryon-pretrain'))
OUT.mkdir(parents=True, exist_ok=True)
QUICK = os.environ.get('ORYON_QUICK') == '1'
SEED = 2007
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
ENVIRONMENT = {'torch':torch.__version__, 'cuda':torch.version.cuda, 'device':str(DEVICE),
'gpu':torch.cuda.get_device_name(DEVICE) if DEVICE.type == 'cuda' else None}
def digest(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
manifest_path = DATA / 'manifest.json'
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
if manifest['version'] != 1 or manifest['dtype'] not in ('<u2', '<u4'):
raise ValueError('Manifiesto o dtype no compatibles')
manifest_hash = digest(manifest_path)
tokenizer_path = DATA / manifest['tokenizer']['path']
if digest(tokenizer_path) != manifest['tokenizer']['sha256']:
raise ValueError('El tokenizador no coincide con el manifiesto')
tokenizer = Tokenizer.from_file(str(tokenizer_path))
ORDINARY = int(manifest['tokenizer']['vocab_size'])
EOT = int(manifest['tokenizer']['eot_id'])
V = EOT + 1
if (ORDINARY != tokenizer.get_vocab_size() or EOT != ORDINARY
or manifest['tokenizer'].get('model_vocab_size',V) != V):
raise ValueError('Vocabulario o EOT inválidos')
if manifest['dtype'] == '<u2' and V > 65536:
raise ValueError('uint16 no admite este vocabulario de IDs densos')
class Windows:
"""Ventanas ponderadas por el número de comienzos válidos en cada shard."""
def __init__(self, root, groups, dtype, context):
self.data = {}
self.context = context
for name, spec in groups.items():
if not name.endswith('/train'):
continue
shards, counts = [], []
for item in spec['shards']:
path = root / item['path']
if path.stat().st_size != item['tokens'] * np.dtype(dtype).itemsize:
raise ValueError('Tamaño de shard incompatible: ' + str(path))
if digest(path) != item['sha256']:
raise ValueError('Hash de shard incompatible: ' + str(path))
arr = np.memmap(path, mode='r', dtype=dtype)
windows = len(arr) - context
if windows > 0:
shards.append(arr)
counts.append(windows)
if not shards:
raise ValueError('No hay ventanas en ' + name)
self.data[name] = (shards, np.cumsum(counts, dtype=np.int64))
def batch(self, group, step, micro, size):
key = f'{SEED}:{step}:{micro}'.encode('ascii')
seed = int.from_bytes(hashlib.sha256(key).digest()[:16], 'little')
rng = np.random.default_rng(seed)
shards, cumulative = self.data[group]
rows = []
for draw in rng.integers(0, int(cumulative[-1]), size=size):
index = int(np.searchsorted(cumulative, draw, side='right'))
offset = int(draw - (cumulative[index-1] if index else 0))
rows.append(np.asarray(shards[index][offset:offset+self.context+1], dtype=np.int64))
values = torch.from_numpy(np.stack(rows))
return values[:,:-1].to(DEVICE), values[:,1:].to(DEVICE)
class RMSNorm(nn.Module):
def __init__(self, width):
super().__init__()
self.weight = nn.Parameter(torch.ones(width))
def forward(self, x):
return F.rms_norm(x, (x.shape[-1],), self.weight, 1e-5)
def rotary(x):
_, _, length, dim = x.shape
frequencies = 1.0 / (10000.0 ** (torch.arange(0, dim, 2, device=x.device, dtype=torch.float32) / dim))
angles = torch.arange(length, device=x.device, dtype=torch.float32)[:,None] * frequencies[None,:]
c, s = angles.cos()[None,None,:,:], angles.sin()[None,None,:,:]
even, odd = x[...,0::2].float(), x[...,1::2].float()
return torch.stack((even*c-odd*s, even*s+odd*c), dim=-1).flatten(-2).to(x.dtype)
class Block(nn.Module):
def __init__(self, width, heads, ff):
super().__init__()
self.heads = heads
self.norm1, self.norm2 = RMSNorm(width), RMSNorm(width)
self.qkv = nn.Linear(width,3*width,bias=False)
self.proj = nn.Linear(width,width,bias=False)
self.up = nn.Linear(width,ff,bias=False)
self.gate = nn.Linear(width,ff,bias=False)
self.down = nn.Linear(ff,width,bias=False)
def forward(self, x):
b,t,d = x.shape
q,k,v = self.qkv(self.norm1(x)).chunk(3,dim=-1)
def split(z): return z.reshape(b,t,self.heads,d//self.heads).transpose(1,2)
q,k,v = rotary(split(q)), rotary(split(k)), split(v)
attn = F.scaled_dot_product_attention(q,k,v,is_causal=True)
x = x + self.proj(attn.transpose(1,2).contiguous().reshape(b,t,d))
h = self.norm2(x)
return x + self.down(F.silu(self.gate(h))*self.up(h))
class MiniLlama(nn.Module):
def __init__(self, vocab, width, layers, heads, ff):
super().__init__()
if width % heads or (width//heads) % 2:
raise ValueError('La dimensión por cabeza debe ser par')
self.embedding = nn.Embedding(vocab,width)
self.blocks = nn.ModuleList(Block(width,heads,ff) for _ in range(layers))
self.norm = RMSNorm(width)
self.apply(self.initialize)
@staticmethod
def initialize(m):
if isinstance(m,(nn.Linear,nn.Embedding)):
nn.init.normal_(m.weight,mean=0.0,std=0.02)
def forward(self, ids):
x = self.embedding(ids)
for block in self.blocks:
x = block(x)
return F.linear(self.norm(x),self.embedding.weight)
def learning_rate(step, total, warmup, decay, peak, floor):
if step < warmup:
return peak * (step+1)/warmup
if step < total-decay:
return peak
progress = min(1.0,(step-(total-decay)+1)/decay)
return peak * (floor + (1-floor)*(1-progress))
def atomic_save(path, state):
tmp = path.with_suffix(path.suffix + '.tmp')
with tmp.open('wb') as f:
torch.save(state,f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp,path)
def precision():
return torch.autocast(device_type='cuda',dtype=torch.bfloat16) if DEVICE.type == 'cuda' else nullcontext()
@torch.inference_mode()
def validation(model, group, context, limit):
filename = DATA / manifest['groups'][group]['validation_jsonl']
if digest(filename) != manifest['groups'][group]['validation_sha256']:
raise ValueError('Hash de validación incompatible: ' + str(filename))
total_loss = 0.0
total_bytes = docs = 0
for line in filename.read_text(encoding='utf-8').splitlines():
obj = json.loads(line)
text = obj['text']
if hashlib.sha256(text.encode('utf-8')).hexdigest() != obj['sha256']:
raise ValueError('Documento de validación corrupto')
ids = tokenizer.encode(text).ids
if not ids or tokenizer.decode(ids,skip_special_tokens=False) != text:
continue
# Para textos largos se reinicia el contexto en cada bloque con EOT.
for start in range(0,len(ids),context):
targets = ids[start:start+context]
inputs = [EOT] + targets[:-1]
x = torch.tensor([inputs],device=DEVICE)
y = torch.tensor(targets,device=DEVICE)
with precision(): logits = model(x)[0].float()
total_loss += float(F.cross_entropy(logits,y,reduction='sum'))
total_bytes += len(text.encode('utf-8'))
docs += 1
if docs >= limit: break
if not total_bytes:
raise ValueError('Validación sin texto reversible')
return {'documents':docs,'bytes':total_bytes,'nll_nats':total_loss,
'bits_per_byte':total_loss/(math.log(2)*total_bytes)}
@torch.inference_mode()
def score_choices(model, context):
tasks = [('The opposite of hot is',[' cold',' dog'],0),
('One plus one equals',[' two',' purple'],0),
('She has two',[' cats',' cat'],0)]
correct = 0
items = []
for prompt, options, answer in tasks:
prefix = tokenizer.encode(prompt).ids
scores = []
for option in options:
# Se verifica la frontera de tokenización antes de puntuar.
combined = tokenizer.encode(prompt+option).ids
if combined[:len(prefix)] != prefix or len(combined) <= len(prefix):
scores.append(None)
continue
target = combined[len(prefix):]
if len(combined) > context:
scores.append(None)
continue
x = torch.tensor([[EOT]+combined[:-1]],device=DEVICE)
with precision(): logits = model(x)[0].float()
positions = torch.arange(len(prefix),len(combined),device=DEVICE)
labels = torch.tensor(target,device=DEVICE)
scores.append(float(F.log_softmax(logits[positions],dim=-1).gather(1,labels[:,None]).mean()))
valid = all(x is not None for x in scores)
choice = int(np.argmax(scores)) if valid else None
if valid and choice == answer: correct += 1
items.append({'prompt':prompt,'options':options,'scores_mean_nats':scores,'answer':answer,'chosen':choice})
evaluated = sum(item['chosen'] is not None for item in items)
return {'correct':correct,'total':evaluated,'items':items,
'rule':'log-probabilidad media por token de cada opción'}
@torch.inference_mode()
def generate(model, context, prompt):
ids = [EOT]+tokenizer.encode(prompt).ids
result = []
for _ in range(12):
x = torch.tensor([ids[-context:]],device=DEVICE)
with precision(): token = int(model(x)[0,-1].argmax())
if token == EOT: break
result.append(token)
ids.append(token)
return {'prompt':prompt,'ids':result,'text':tokenizer.decode(result,skip_special_tokens=False)}
def run(total, stop, save_path=None, resume_path=None):
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(SEED)
context, width, layers, heads, ff = (32,64,2,4,192) if QUICK else (256,512,8,8,1536)
micro_batch, accumulation = (2,1) if QUICK else (8,8)
warmup = min(2 if QUICK else 200,max(1,total//4))
decay = min(2 if QUICK else 3000,max(1,total//5))
if warmup + decay > total: raise ValueError('No caben calentamiento y enfriamiento')
model = MiniLlama(V,width,layers,heads,ff).to(DEVICE)
optimizer = torch.optim.AdamW(model.parameters(),lr=3e-4,weight_decay=0.1)
compile_requested = os.environ.get('ORYON_COMPILE') == '1' and not QUICK
if compile_requested and not hasattr(torch,'compile'):
raise ValueError('torch.compile no está disponible; usa ORYON_COMPILE=0')
runner = torch.compile(model) if compile_requested else model
sampler = Windows(DATA,manifest['groups'],manifest['dtype'],context)
start = 0
losses, events = [], []
if resume_path is not None:
# Carga únicamente checkpoints generados por ti: contiene objetos Python.
state = torch.load(resume_path,map_location=DEVICE,weights_only=False)
if (state['manifest_sha256'] != manifest_hash or state['total'] != total
or state['config'] != [context,width,layers,heads,ff,micro_batch,accumulation,compile_requested]
or state['environment'] != ENVIRONMENT):
raise ValueError('Checkpoint incompatible con datos o configuración')
model.load_state_dict(state['model'])
optimizer.load_state_dict(state['optimizer'])
start = state['step']
torch.set_rng_state(state['torch_rng'].cpu())
if DEVICE.type == 'cuda': torch.cuda.set_rng_state_all([x.cpu() for x in state['cuda_rng']])
random.setstate(state['python_rng'])
losses = state['losses']
events = state['events']
params = sum(p.numel() for p in model.parameters())
def checkpoint_at(step):
if save_path is None:
return
state = {'model':model.state_dict(),'optimizer':optimizer.state_dict(),'step':step,'total':total,
'config':[context,width,layers,heads,ff,micro_batch,accumulation,compile_requested],
'environment':ENVIRONMENT,
'manifest_sha256':manifest_hash,'torch_rng':torch.get_rng_state(),
'cuda_rng':torch.cuda.get_rng_state_all() if DEVICE.type == 'cuda' else [],
'python_rng':random.getstate(),'losses':losses,'events':events}
atomic_save(save_path,state)
for step in range(start,stop):
model.train()
group = 'fineweb/train' if step >= total-decay else ('tiny/train' if step % 2 == 0 else 'fineweb/train')
lr = learning_rate(step,total,warmup,decay,3e-4,0.1)
for g in optimizer.param_groups: g['lr'] = lr
optimizer.zero_grad(set_to_none=True)
total_loss = total_z = 0.0
if DEVICE.type == 'cuda': torch.cuda.synchronize()
started = time.perf_counter()
for micro in range(accumulation):
x,y = sampler.batch(group,step,micro,micro_batch)
with precision():
logits = runner(x).float()
ce = F.cross_entropy(logits.reshape(-1,V),y.reshape(-1))
z = torch.logsumexp(logits,dim=-1).square().mean()
loss = (ce+1e-5*z)/accumulation
if not torch.isfinite(loss):
raise FloatingPointError(f'Pérdida no finita en paso {step}, grupo {group}, micro {micro}; conserva el checkpoint anterior')
loss.backward()
total_loss += float(ce.detach())/accumulation
total_z += float(z.detach())/accumulation
norm = nn.utils.clip_grad_norm_(model.parameters(),1.0)
if not torch.isfinite(norm):
raise FloatingPointError(f'Gradiente no finito en paso {step}; no se aplicó la actualización')
optimizer.step()
if DEVICE.type == 'cuda': torch.cuda.synchronize()
elapsed = time.perf_counter()-started
losses.append(total_loss)
after = step+1
if after == stop or after == total or (not QUICK and after % 1000 == 0):
model.eval()
val = {name:validation(model,name,context,2 if QUICK else 20)
for name in ('tiny/validation','fineweb/validation')}
event = {'step':after,'tokens':after*context*micro_batch*accumulation,
'phase':'decay' if step >= total-decay else ('warmup' if step < warmup else 'stable'),
'group':group,'learning_rate':lr,'train_nll':total_loss,'gradient_norm':float(norm),
'mean_logz_squared':total_z,
'train_tokens_per_second':context*micro_batch*accumulation/elapsed,
'validation':val,'choices':score_choices(model,context),
'sample':generate(model,context,'Once upon a time')}
events.append(event)
print('Paso',after,'fase',event['phase'],'loss',round(total_loss,6),
'bpb', {k:round(v['bits_per_byte'],5) for k,v in val.items()},
'opción múltiple',event['choices']['correct'],'/',event['choices']['total'],flush=True)
checkpoint_at(after)
return model,optimizer,losses,events,params
if QUICK:
checkpoint = OUT/'resume-test.pt'
model_a,opt_a,loss_a,events_a,params = run(4,4)
reference = {k:v.detach().cpu().clone() for k,v in model_a.state_dict().items()}
reference_opt = copy.deepcopy(opt_a.state_dict())
del model_a,opt_a
gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
first,opt_first,_,_,_ = run(4,2,save_path=checkpoint)
del first,opt_first
gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
resumed,opt_resumed,loss_b,events_b,_ = run(4,4,resume_path=checkpoint)
def same(a,b):
if isinstance(a,torch.Tensor): return torch.equal(a.cpu(),b.cpu())
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
equal = (loss_a == loss_b and same(reference_opt,opt_resumed.state_dict())
and all(torch.equal(v,resumed.state_dict()[k].cpu()) for k,v in reference.items()))
assert equal, 'La trayectoria reanudada no coincide en este entorno'
print('Reanudación: pérdidas, parámetros y optimizador idénticos:',equal,flush=True)
report = {'quick':True,'parameters':params,'manifest_sha256':manifest_hash,'resume_equal':equal,
'events':events_a,'resumed_events':events_b}
del resumed,opt_resumed
else:
context, micro_batch, accumulation = 256,8,8
total = int(os.environ.get('ORYON_STEPS',math.ceil(500_000_000/(context*micro_batch*accumulation))))
if total < 5: raise ValueError('El plan completo requiere al menos cinco pasos')
checkpoint = OUT/'latest.pt'
resume_requested = os.environ.get('ORYON_RESUME') == '1'
if resume_requested and not checkpoint.exists():
raise FileNotFoundError('ORYON_RESUME=1 pero no existe latest.pt')
if not resume_requested and checkpoint.exists():
raise FileExistsError('Ya existe latest.pt; usa otro directorio o ORYON_RESUME=1')
resume = checkpoint if resume_requested else None
model,opt,losses,events,params = run(total,total,save_path=checkpoint,resume_path=resume)
report = {'quick':False,'parameters':params,'manifest_sha256':manifest_hash,
'tokens_plan':total*context*micro_batch*accumulation,'events':events}
del model,opt
(OUT/'pretrain-report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print('Informe:',OUT/'pretrain-report.json',flush=True)npm run lab and open the connection link.Exercises
import numpy as np
def window(arr, length, seed, step):
pass
The following check reproduces the exercise quantities using the stated values:
N, D, tasa = 50_000_000, 1_000_000_000, 60_000
print('FLOPs aproximados:', 6 * N * D)
print('Horas ideales:', D / tasa / 3600)
print('Bytes para 2000 millones de uint16:', 2_000_000_000 * 2)
print('Mayor ID representable en uint16:', 2**16 - 1)Reproducible pretraining joins identified data, an explicit budget, per-domain evaluation, and enough state to resume. The short test checks the mechanism; full training is a separate experiment.