Module contents
Stage 2 of 9Advanced 90 min

Pretraining data in shards

Prepare the corpus with a multi-billion-token FineWeb-Edu sample, exact deduplication, parallel tokenization over 24 cores, uint16 shards, and a resumable memory-mapped loader. Measure whether the loader delivers tokens much faster than the GPU consumes them.

After this lesson you can

  • Download a FineWeb-Edu sample and split validation reproducibly.
  • Tokenize in parallel with multiprocessing and write uint16 shards with document separators.
  • Implement a memory-mapped loader with serializable state for exact resumption.
  • Measure loader throughput and compare it with GPU consumption.

Before you start

Preparing data that can be traversed again

A long training run can fail after consuming millions of batches. If the checkpoint restores the weights but the loader starts over, loss can look normal while the model repeats examples. We need a verifiable chain from documents to every token position, and state that identifies the next batch, not just the last one displayed.

The figure is a toy model, using labels in place of tokens, of the loader we will build in the lab: three shards of 11, 9, and 8 positions, windows of T+1T+1 tokens aligned inside each shard, a permutation of all windows each epoch generated from the seed and epoch, and batches of two windows. Borders mark the next batch, the one consumed when you press the button. Save the state, advance, and restore: the next batch is the same again. Then restore while remembering only the seed, as a checkpoint that does not save the loader would do, and see repeated windows appear. Notice the hatched cells too: they are targets that no window uses, and their number comes from a formula proved below.

InteractiveThe next batch after resuming
S1
0
A₀
1
A₁
2
A₂
3
A₃
4
EOS
5
B₀
6
B₁
7
B₂
8
B₃
9
B₄
10
B₅
S2
0
EOS
1
C₀
2
C₁
3
C₂
4
EOS
5
D₀
6
D₁
7
D₂
8
D₃
S3
0
D₄
1
EOS
2
E₀
3
E₁
4
E₂
5
E₃
6
E₄
7
EOS
  • input x of the next batch
  • target y (shifted one position)
  • target unused by any window
Epoch 0 order (permutation of the 7 windows from seed and epoch):
0: S3·v01: S2·v02: S1·v03: S1·v24: S2·v15: S1·v16: S3·v1

Batches of 2 windows of T + 1 = 4 tokens, aligned within each shard; Sk·vj is window j of shard k, starting at position j·T. Struck through means already consumed this epoch. Restoring also returns weights to the saved state, so later consumption is discarded from the history.

3
When restoring
State (epoch, cursor)(0, 4) of W = 7
Savednone
Next batchS2·v1 (epoch 0), S1·v1 (epoch 0)
Unused targets (Σr + S − 1)4 + 2 = 6 of 27
Repeated windows0
An explicit model of the lab's TokenLoader. The state (epoch, cursor) identifies the next batch; the seed alone does not.

In a pretraining data pipeline, we must pin the source, document selection, deduplication, split, tokenizer and its version, delimiters, and writing process. The result is a binary directory plus a manifest that lets us reconstruct what its files contain. Later lessons train on this stream, so an error here repeats at every model step.

Budget before downloading

For a model with NN parameters and a data budget of DD tokens, choosing DD entails a trade-off between compute, storage, and coverage. Training compute is approximated by C≈6NDC \approx 6ND FLOPs, two per parameter and token in the forward pass and about four in backpropagation. With the model fixed, each additional token costs the same, and the question becomes how many are worthwhile.

Hoffmann and colleagues trained over 400 models ranging from 70 million to more than 16000 million parameters, with between 5000 and 500000 million tokens. Under their conditions, optimal model and data sizes grew approximately proportionally as compute increased. Their Chinchilla model, with 70000 million parameters and 1.4 trillion tokens, gives the familiar reference of about 20 tokens per parameter. This is guidance rather than a law: its constants depend on the model family, corpus, and tokenizer, and it does not replace measuring validation loss.

Let’s calculate the project’s budget. The GPT in p06-l03 has 12 layers, dimension 768, context 1024, and our vocabulary of 513 IDs, giving N=86 236 416N = 86\,236\,416 parameters. The rule yields 20N≈1.72×10920N \approx 1.72\times10^9 tokens. The plan in p06-l06 uses 3300 updates of 524288 tokens, D=1 730 150 400D = 1\,730\,150\,400, about 20.06 per parameter, so C≈6ND≈8.95×1017C \approx 6ND \approx 8.95\times10^{17} FLOPs. To leave headroom, its preparation writes a training stream of 1.8×1091.8\times10^9 IDs. Stored as uint16, they occupy 2⋅1.8×1092 \cdot 1.8\times10^9 bytes, or 3.6 GB. At the 2.018 text bytes per ID measured in the lab, they correspond to about 3.6 GB of UTF-8 text, on the order of 740000 FineWeb-Edu documents, with an average of about 4900 bytes per document in the sample. They are unique tokens only because the plan makes no second pass. With a smaller repeated corpus, compute would be the same but the amount of distinct text would not.

FineWeb-Edu: where the documents come from

The FineWeb paper describes FineWeb as a collection of 15 trillion tokens from 96 Common Crawl snapshots. Its pipeline extracts text from WARC files with trafilatura, filters URLs against a blocklist, keeps English text scoring at least 0.65 under a fastText language classifier, and applies MassiveText quality and repetition filters, some C4 filters, and three of its own. Deduplication is approximate, using MinHash on 5-grams with 112 hash functions in 14 bands of 8, targeting documents with at least 75% similarity, and is performed per snapshot. Globally deduplicating all 96 snapshots barely improved upon no deduplication in the ablations.

FineWeb-Edu adds an educational-content filter. Llama-3-70B-Instruct scored about 460000 pages from one snapshot from 0 to 5. Those labels trained a linear regression head over frozen Snowflake-arctic-embed-m embeddings, and pages with a predicted score of at least 3 were retained. The result has 1.3 trillion tokens counted with the GPT-2 tokenizer. The FineWeb-Edu dataset card offers sample subsets. We use sample-10BT, with 9.67 million documents across 14 parquet files, about 10000 million GPT-2 tokens, and the ODC-By license. Record the revision and selection used, since the repository can change.

The counts change with the tokenizer. The vocabulary from the previous lesson has 512 ordinary IDs and one special ID, and its file records the sample used for training. It is not GPT-2. In this lab we retrain the same algorithm using only documents from the new training split. The resulting vocabulary is different and may assign different IDs. A file advertised as a given number of GPT-2 tokens does not necessarily contain the same number of IDs under our vocabulary. Count the IDs actually written and record the separator convention. To avoid contaminating validation, no document used to train the tokenizer may appear in it.

Unique documents and splits

Exact deduplication computes a cryptographic hash of each document’s bytes and retains one copy per content. To avoid treating a hash collision as logical equality, an implementation needing absolute certainty can compare bytes when hashes match. Also pin normalization: texto.encode('utf-8') compares literal bytes, so changes in spaces, capitalization, or Unicode composition may produce a different document. If normalization precedes hashing, the manifest must describe it; this defines equality differently.

Deduplicating before splitting prevents exact copies from ending up in different partitions. A reproducible assignment can derive from a content hash and fixed seed, or from a recorded order and seed. In either case, retain the identifiers of held-out documents and check that the two hash lists do not overlap. Changing the source, normalization rule, or seed produces a different split and requires a different manifest identity.

The lab uses the simplest rule satisfying these requirements. Let h(x)h(x) be the SHA-256 of document xx‘s UTF-8 bytes and u(x)u(x) the integer represented by its first 8 bytes in big-endian order. Document xx goes to validation if u(x)≡0(mod10)u(x) \equiv 0 \pmod{10} and to training otherwise.

Proof

(a) The assignment is x↦[u(x) mod 10=0]x \mapsto [u(x) \bmod 10 = 0], which depends only on xx‘s bytes. Exact copies have the same bytes and therefore the same value. (b) If h(x)h(x) is uniform, its first 64 bits are uniform in {0,…,264−1}\{0, \dots, 2^{64}-1\}. Since 264=10q+62^{64} = 10q + 6 with q=⌊264/10⌋q = \lfloor 2^{64}/10 \rfloor, remainders 0,…,50,\dots,5 occur q+1q+1 times and remainders 6,…,96,\dots,9 occur qq times; remainder 0 has probability (q+1)/264=⌈264/10⌉/264(q+1)/2^{64} = \lceil 2^{64}/10\rceil/2^{64}. Since q+1=(264+4)/10q + 1 = (2^{64} + 4)/10, that probability is 0.1+0.4⋅2−640.1 + 0.4\cdot 2^{-64}. Independence across distinct documents follows from the oracle model, and the sum of nn independent Bernoulli(p)(p) indicators is binomial. (c) Equality has probability 2−2562^{-256} for each pair; applying the union bound over the (n2)\binom{n}{2} pairs gives the result.

∎

SHA-256 is not a random oracle, but no method is known to distinguish its outputs from uniform outputs on documents that nobody has chosen adversarially, as in our case. With n=1000n = 1000, the expected number of validation documents is 100 with standard deviation 1000⋅0.1⋅0.9≈9.5\sqrt{1000 \cdot 0.1 \cdot 0.9} \approx 9.5: the lab’s 102 is ordinary. With n=107n = 10^7, the collision bound is on the order of 4⋅10−644\cdot 10^{-64}, so comparing bytes after matching hashes protects against code errors rather than the arithmetic.

Exact equality does not detect a page copied with an added sentence. To investigate near-duplicates, generate candidates by similarity and group related documents before splitting. No threshold automatically eliminates every semantic overlap. There are false negatives and false positives, so measure and report the rule. FineWeb studies approximate deduplication per snapshot; this should not be interpreted as a guarantee that no duplicates exist across all snapshots and partitions.

From document to shard

A shard is a segment of the ID stream, not a statistical partition by itself. Each document is tokenized as ordinary text and an end-of-document special ID is explicitly appended. This marker signals a boundary to the model, but does not stop attention or loss from crossing it. Strict isolation requires an attention mask and a target policy that enforce it. Without them, the model can use previous context and predict the next document after the marker. This should be a conscious decision.

In memory-mapped token shards, each ID is stored as a fixed-width integer. uint16 ranges from 0 to 65535. Before conversion, check that IDs are nonnegative integers and that the maximum fits: converting first can truncate an out-of-range value and silently store a different ID. Vocabulary size alone is insufficient if IDs are not contiguous. If the maximum ID exceeds 65535, use a wider type and record its byte order and size.

For a stream of nn uint16 tokens, data occupies 2n2n bytes excluding headers and metadata. A final shard may contain fewer tokens than the target size, so include its actual length. For each file, the manifest must record its name, element count, type, byte order, and content hash. Check that the sum of lengths matches the total emitted IDs, including separators. Writing to a temporary file first and publishing the final name after closing and verifying reduces the risk of mistaking a partial file for a complete one.

Multiprocess tokenization can handle documents in parallel, but concatenation must follow the declared order. A process that emits whichever document finishes first can change the stream between runs. Retain input indices and reorder results before writing. On Windows, new processes start with spawn: worker functions must be importable and the entry point must be guarded with if __name__ == '__main__'. A function defined only in an interactive cell may not be importable in the child. A batch of documents per task reduces overhead, but the optimal size must be measured on the particular machine and corpus.

Memory mapping and resumption

numpy.memmap presents a file as an array without copying the entire file into a resident array. The operating system loads needed pages and can keep them cached. A second read can be much faster because the data is already in memory: a warm-cache measurement does not demonstrate cold-disk speed. Mapping also does not guarantee that the whole file fits in memory or remove the cost of copying batches to the device.

For next-token prediction, a window of length T+1T+1 produces TT inputs and TT targets shifted by one position. The final target is essential: reading only TT IDs leaves the last element without a target. If a window crosses the physical boundary of two shards in the same stream, the loader can join their ends, provided its policy permits the crossing and implements it verifiably. If it does not cross, it must explain which positions are excluded. A file boundary is not automatically a document boundary.

The cost of not crossing can be calculated exactly. Suppose there are SS shards of lengths n1,…,nSn_1, \dots, n_S and N=∑snsN = \sum_s n_s tokens. Concatenated, they offer N−1N - 1 target positions, all but the first. A loader that forms only aligned windows [kT,kT+T][kT, kT+T] inside each shard has W=∑s⌊(ns−1)/T⌋W = \sum_s \lfloor (n_s - 1)/T \rfloor windows and uses TWTW targets.

Proof

By Euclidean division, ns−1=T⌊(ns−1)/T⌋+rsn_s - 1 = T\lfloor (n_s-1)/T \rfloor + r_s for each shard. Summing over ss gives N−S=TW+∑srsN - S = TW + \sum_s r_s, and subtracting both sides from N−1N - 1 yields (N−1)−TW=∑srs+S−1(N-1) - TW = \sum_s r_s + S - 1. The additional S−1S - 1 terms are transitions from the last token of one shard to the first token of the next, which no internal window contains.

∎

Since 0≤rs≤T−10 \le r_s \le T - 1, the loss is at most S T−1S\,T - 1 positions: with shards of 100000 tokens and T=128T = 128, less than 0.13% of the stream. The loss is small and known. What would be unacceptable is not knowing whether it exists.

A resumable state must recover the next batch after restoration. With random order, an initial seed is insufficient if randomness has already been consumed. Save the generator state, the permutation or the rule that regenerates it, the epoch, and position within that permutation. Also record shard identity and order, window length, batch size, and any crossing or dropping policy. A checkpoint with different files must fail explicitly rather than silently continue with changed data.

The stronger test captures state, saves several future batches, and compares them with those produced by another restored loader. Include shard and epoch changes, not just one batch in the middle of a file. In distributed training, every worker needs coherent state and allocation. Restoring only the main process does not guarantee reproducibility for all workers. The experiment in this lesson should make clear whether it implements one reading process or distributed allocation.

Measuring the bottleneck

The useful ratio is tokens per second delivered by the loader divided by tokens per second consumed in training, using the same shapes and conditions. A high read rate does not guarantee fast end-to-end training: it can conceal transfers, conversions, or synchronization. Measure CPU batch construction, copying, and the complete step separately, and state which parts are included. When measuring CUDA, synchronize before and after the interval because operations are launched asynchronously. The PyTorch documentation explains these semantics. Repeat after warmup and report the ratio with the exact configuration: it depends on the GPU, model, batch size, and other activity on the machine.

The headroom we seek is substantial. The GPT training step from p06-l03 consumes on the order of 10410^4 tokens per second on a laptop RTX 4060. p06-l05 measures 8842 using the GPT-2 vocabulary, microbatch 1, BF16, and fused AdamW, and the short p06-l06 check gives 9853 to 11301 with our vocabulary and microbatch 4. Reading from a memmap and slicing windows moves millions of tokens per second on an ordinary CPU. If the ratio falls below 10, the loader ceases to be invisible: gaps appear in GPU utilization and batches must be prefetched in another thread or process.

Lab

Run from the project root. Install numpy, torch, regex, tiktoken==0.14.0, and hypothesis==6.170.12 in the local environment, as in the previous lesson. The first cell downloads the first 1000 FineWeb-Edu sample-10BT documents, retrieves the block titled «Codificador y entrenador BPE incremental» from the current p06-l01 lesson, and runs its trainer on the first 100 documents of the training subset. The algorithm is reused, but a new vocabulary is learned: neither the IDs nor the file saved by the previous experiment are used.

The cells write working files to p06_data, configurable with P06_DATA_DIR; the project root can be set with P06_PROJECT_ROOT. Windows processes need to import their worker functions, so the first cell creates a standalone script in the working directory and executes it with the if __name__ == '__main__' guard. Four processes are used by default. P06_WORKERS adjusts the number, for example to 24 when the machine and workload allow it. Access to the corpus API is required.

The text hash determines the split and removes exact duplicates before vocabulary training, preventing validation documents from contributing to that training. The separator is ID 512, and both IDs and separators fit in uint16. Each ID is checked to be an ordinary integer in range before conversion. Shard and vocabulary filenames include their content hashes; the manifest is replaced only when all are written. The vocabulary retains the pretokenization expression and the manifest identifies the p06-l01 code block by SHA-256. Document order is preserved within each split. Exact deduplication does not remove similar variants of a document.

[ ]Download, multiprocess tokenization, and shardsLocal GPU
from pathlib import Path
import os
import subprocess
import sys

def project_root():
    """Raíz del proyecto: P06_PROJECT_ROOT o la primera carpeta superior que contiene las lecciones."""
    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()
data.mkdir(parents=True, exist_ok=True)
os.environ['P06_PROJECT_ROOT'] = str(project)
os.environ['P06_DATA_DIR'] = str(data)
os.environ['PYTHONIOENCODING'] = 'utf-8'
# Un hilo de BLAS por proceso: con muchos trabajadores, cada NumPy reservaría
# búferes para todos los núcleos y la memoria se agotaría sin necesidad.
child_env = dict(os.environ, PYTHONUTF8='1', OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', MKL_NUM_THREADS='1')
source = r'''
"""Muestra real FineWeb-Edu y shards del tokenizador de p06-l01.

Todos los ficheros producidos quedan en P06_DATA_DIR. El código de p06-l01 se
lee del MDX vigente, que se busca a partir de P06_PROJECT_ROOT.
"""
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import hashlib
import json
import os
import time
import urllib.error
import urllib.request
import numpy as np

def _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')

ROOT = _root()
DATA = Path(os.environ.get('P06_DATA_DIR', 'p06_data')).resolve()
DATA.mkdir(parents=True, exist_ok=True)

def lesson_block():
    mdx = (ROOT / 'src/content/lessons/p06/l01-tokenizador-bpe.mdx').read_text(encoding='utf-8')
    head = '```python run runtime=local title="Codificador y entrenador BPE incremental"\n'
    return mdx.split(head, 1)[1].split('\n```', 1)[0]

def previous_lesson():
    """Usar el código real de la lección anterior, no una copia en informes."""
    block = lesson_block()
    env = {'__name__': 'p06_l01', '__file__': str(DATA / 'lesson01.py')}
    os.environ['BPE_DATA_DIR'] = str(DATA)
    exec(compile(block, 'p06-l01.mdx', 'exec'), env)
    return env

def fetch(offset):
    path = DATA / f'fineweb-{offset:05d}.json'
    if not path.exists():
        url = ('https://datasets-server.huggingface.co/rows?dataset='
               'HuggingFaceFW%2Ffineweb-edu&config=sample-10BT&split=train'
               f'&offset={offset}&length=100')
        for attempt in range(8):
            try:
                with urllib.request.urlopen(url, timeout=90) as r:
                    payload = r.read()
                break
            except urllib.error.HTTPError as error:
                if error.code not in (429, 500, 502, 503, 504) or attempt == 7:
                    raise
                time.sleep(min(60, 5 * 2**attempt))
        path.write_bytes(payload)
    rows = json.loads(path.read_text(encoding='utf-8'))['rows']
    assert len(rows) == 100
    return [r['row']['text'] for r in rows]

def dedup_split(texts):
    seen = {}
    train, valid = [], []
    duplicates = 0
    for text in texts:
        key = hashlib.sha256(text.encode('utf-8')).digest()
        if key in seen:
            if seen[key] != text:
                raise RuntimeError('Colisión SHA-256 entre textos distintos')
            duplicates += 1
            continue
        seen[key] = text
        (valid if int.from_bytes(key[:8], 'big') % 10 == 0 else train).append(text)
    return train, valid, duplicates

ENCODER = None
def worker_init(ranks, eot):
    global ENCODER
    env = previous_lesson()
    ENCODER = env['make_text_encoder'](ranks, special_id=eot)

def worker(text):
    return ENCODER(text)

def file_hash(path):
    digest = hashlib.sha256()
    with open(path, 'rb') as f:
        for block in iter(lambda: f.read(1024 * 1024), b''):
            digest.update(block)
    return digest.hexdigest()

def verify_manifest(manifest):
    actual_code = hashlib.sha256(lesson_block().encode('utf-8')).hexdigest()
    if manifest['tokenizer_code_sha256'] != actual_code:
        raise ValueError('El código de p06-l01 ha cambiado desde la tokenización')
    if file_hash(DATA / manifest['vocab_file']) != manifest['vocab_sha256']:
        raise ValueError('Vocabulario distinto del manifiesto')
    for part in manifest['parts'].values():
        for shard in part['shards']:
            path = DATA / shard['file']
            if path.stat().st_size != 2 * shard['tokens'] or file_hash(path) != shard['sha256']:
                raise ValueError('Shard distinto del manifiesto')

def validate_ids(ids, eot):
    if any(type(t) is not int or t < 0 or t >= eot for t in ids):
        raise ValueError('ID no entero o fuera del vocabulario ordinario')

def write_shards(name, texts, ranks, eot, shard_size=100_000, workers=4):
    paths, buffer, total, doc_count = [], [], 0, 0
    def save(values):
        tmp = DATA / f'{name}-{len(paths):05d}.tmp'
        np.asarray(values, dtype='<u2').tofile(tmp)
        digest = file_hash(tmp)
        path = DATA / f'{name}-{len(paths):05d}-{digest}.bin'
        tmp.replace(path)
        paths.append({'file': path.name, 'tokens': len(values), 'sha256': digest})
    with ProcessPoolExecutor(max_workers=workers, initializer=worker_init,
                             initargs=(ranks, eot)) as pool:
        for ids in pool.map(worker, texts, chunksize=10):
            validate_ids(ids, eot)
            buffer.extend(ids)
            buffer.append(eot)
            doc_count += 1
            while len(buffer) >= shard_size:
                save(buffer[:shard_size])
                total += shard_size
                del buffer[:shard_size]
    if buffer:
        save(buffer)
        total += len(buffer)
    assert sum(s['tokens'] for s in paths) == total
    assert sum(int(np.count_nonzero(np.memmap(DATA / p['file'], dtype='<u2', mode='r') == eot))
               for p in paths) == doc_count
    text_bytes = sum(len(t.encode('utf-8')) for t in texts)
    return {'documents': doc_count, 'tokens': total, 'bytes': text_bytes, 'shards': paths}

class TokenLoader:
    def __init__(self, shard_paths, batch_size, seq_len, seed):
        self.shard_hashes = [file_hash(path) for path in shard_paths]
        self.maps = [np.memmap(path, dtype='<u2', mode='r') for path in shard_paths]
        self.batch_size, self.seq_len, self.seed = batch_size, seq_len, seed
        self.lengths = np.array([(len(a)-1)//seq_len for a in self.maps], dtype=np.int64)
        self.ends = np.cumsum(self.lengths)
        if not self.ends.size or self.ends[-1] == 0:
            raise ValueError('No hay ventanas completas en los shards')
        self.epoch, self.cursor = 0, 0
        self._order()
    def _order(self):
        self.order = np.random.default_rng(np.random.SeedSequence([self.seed, self.epoch])).permutation(int(self.ends[-1]))
    def next(self):
        xs, ys = [], []
        while len(xs) < self.batch_size:
            if self.cursor == len(self.order):
                self.epoch += 1
                self.cursor = 0
                self._order()
            index = int(self.order[self.cursor]); self.cursor += 1
            shard = int(np.searchsorted(self.ends, index, side='right'))
            base = 0 if shard == 0 else int(self.ends[shard-1])
            start = (index-base) * self.seq_len
            span = self.maps[shard][start:start+self.seq_len+1].astype(np.int64)
            xs.append(span[:-1]); ys.append(span[1:])
        return np.stack(xs), np.stack(ys)
    def state_dict(self):
        return {'epoch': self.epoch, 'cursor': self.cursor, 'seed': self.seed,
                'batch_size': self.batch_size, 'seq_len': self.seq_len,
                'shard_lengths': [len(a) for a in self.maps], 'shard_hashes': self.shard_hashes}
    def load_state_dict(self, state):
        for key in ('seed', 'batch_size', 'seq_len'):
            if state[key] != getattr(self, key):
                raise ValueError(f'El estado no corresponde a {key}')
        if state['shard_lengths'] != [len(a) for a in self.maps]:
            raise ValueError('Los shards tienen tamaños distintos')
        if state['shard_hashes'] != self.shard_hashes:
            raise ValueError('El contenido o el orden de los shards ha cambiado')
        self.epoch, self.cursor = state['epoch'], state['cursor']
        if self.epoch < 0 or not 0 <= self.cursor <= int(self.ends[-1]):
            raise ValueError('Estado inválido')
        self._order()

def main():
    assert dedup_split(['a', 'a', 'b'])[2] == 1
    try:
        validate_ids([1.5], 512)
    except ValueError:
        pass
    else:
        raise AssertionError('Un ID fraccionario debe rechazarse')
    docs = [d for start in range(0, 1000, 100) for d in fetch(start)]
    sample_hash = hashlib.sha256()
    for doc in docs:
        raw = doc.encode('utf-8')
        sample_hash.update(len(raw).to_bytes(8, 'big'))
        sample_hash.update(raw)
    train_docs, valid_docs, dup = dedup_split(docs)
    assert set(train_docs).isdisjoint(valid_docs)
    env = previous_lesson()
    ranks, merges = env['train'](train_docs[:100], vocab_size=512)
    eot = len(ranks)
    assert eot <= 65535
    vocab = {'vocab_hex': {b.hex(): rank for b, rank in ranks.items()},
             'merges': merges, 'special_literal': '<|endoftext|>', 'special_id': eot,
             'pretokenization': env['PAT'].pattern}
    vocab_tmp = DATA / 'vocabulario.tmp'
    vocab_tmp.write_text(json.dumps(vocab, ensure_ascii=False, indent=2), encoding='utf-8')
    vocab_hash = file_hash(vocab_tmp)
    vocab_path = DATA / f'vocabulario-{vocab_hash}.json'
    vocab_tmp.replace(vocab_path)
    restored = json.loads(vocab_path.read_text(encoding='utf-8'))
    assert {bytes.fromhex(k): v for k, v in restored['vocab_hex'].items()} == ranks
    print('documentos:', len(docs), 'duplicados:', dup, 'train:', len(train_docs), 'valid:', len(valid_docs), flush=True)
    workers = int(os.environ.get('P06_WORKERS', '4'))
    parts = {name: write_shards(name, texts, ranks, eot, workers=workers) for name, texts in
             [('train', train_docs), ('valid', valid_docs)]}
    manifest = {'dataset': 'HuggingFaceFW/fineweb-edu', 'config': 'sample-10BT',
                'offsets': [0, 1000], 'split': 'sha256-primeros-8-bytes-modulo-10',
                'sample_sha256': sample_hash.hexdigest(), 'numpy_version': np.__version__,
                'duplicates': dup, 'vocab_ordinary': len(ranks), 'eot_id': eot,
                'tokenizer_training': 'primeros 100 documentos del subconjunto train',
                'dtype': '<u2', 'vocab_file': vocab_path.name, 'vocab_sha256': vocab_hash, 'parts': parts}
    manifest['tokenizer_code_sha256'] = hashlib.sha256(lesson_block().encode('utf-8')).hexdigest()
    verify_manifest(manifest)
    manifest_tmp = DATA / 'manifest.tmp'
    manifest_tmp.write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding='utf-8')
    manifest_tmp.replace(DATA / 'manifest.json')
    import shutil
    corrupt = DATA / 'corrupt-check.tmp'
    first = parts['train']['shards'][0]
    shutil.copyfile(DATA / first['file'], corrupt)
    with corrupt.open('r+b') as f:
        original = f.read(1)
        f.seek(0)
        f.write(bytes([original[0] ^ 1]))
    altered = json.loads(json.dumps(manifest))
    altered['parts']['train']['shards'][0]['file'] = corrupt.name
    try:
        try:
            verify_manifest(altered)
        except ValueError:
            print('Corrupción detectada y IDs fraccionarios rechazados', flush=True)
        else:
            raise AssertionError('El manifiesto no detectó la corrupción')
    finally:
        corrupt.unlink()
    altered_code = dict(manifest, tokenizer_code_sha256='0' * 64)
    try:
        verify_manifest(altered_code)
    except ValueError:
        print('Cambio en el código del tokenizador detectado', flush=True)
    else:
        raise AssertionError('No se detectó la discrepancia de código')
    paths = [DATA / x['file'] for x in parts['train']['shards']]
    a = TokenLoader(paths, 16, 128, seed=42)
    for _ in range(10): a.next()
    state = json.loads(json.dumps(a.state_dict()))
    expected = [a.next() for _ in range(20)]
    b = TokenLoader(paths, 16, 128, seed=42); b.load_state_dict(state)
    for x, y in expected:
        xx, yy = b.next()
        assert np.array_equal(x, xx) and np.array_equal(y, yy)
    print('reanudación: 20 lotes idénticos', flush=True)
    edge = a.state_dict(); edge['cursor'] = len(a.order) - 3
    a.load_state_dict(edge); b.load_state_dict(edge)
    xx, yy = a.next(); x2, y2 = b.next()
    assert a.epoch == edge['epoch'] + 1
    assert np.array_equal(xx, x2) and np.array_equal(yy, y2)
    print('reanudación al cruzar una época: idéntica', flush=True)
    for name, part in parts.items():
        used = sum((s['tokens']-1)//128*128 for s in part['shards'])
        possible = part['tokens'] - 1
        print(f'{name}: posiciones objetivo posibles {possible}; '
              f'utilizadas {used}; descartadas {possible-used}', flush=True)
    print('SHA-256 muestra:', sample_hash.hexdigest(), flush=True)
    print('tokens train:', parts['train']['tokens'],
          'tokens valid:', parts['valid']['tokens'],
          'separador:', eot, flush=True)
    for name, part in parts.items():
        ordinary = part['tokens'] - part['documents']
        print(f"{name}: {part['bytes']} bytes de texto, {part['bytes'] / ordinary:.3f} bytes por ID ordinario, "
              f"{len(part['shards'])} shards", flush=True)
    print('Manifiesto:', DATA / 'manifest.json', flush=True)

if __name__ == '__main__':
    main()
'''
script = data / 'pipeline.py'
script.write_text(source, encoding='utf-8')
result = subprocess.run([sys.executable, str(script)], cwd=project, env=child_env,
                        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                        text=True, encoding='utf-8')
print(result.stdout)
result.check_returncode()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The loader builds complete windows of length 128 inside each shard, drops the remainder at the end of each file, and forms no windows crossing shard boundaries. Each epoch it permutes windows and regenerates the order from seed and epoch. It also saves position, dimensions, and ordered file hashes, rejecting a different configuration or data on restoration. The test compares the next 20 batches and another restoration crossing the end of an epoch. This is a single-process reader; distributed allocation is not implemented.

In the recorded run there were 1000 documents, no exact duplicates, 898 training documents, and 102 validation documents. The shards contain 2204722 and 236708 tokens respectively, including separators. The fingerprint of the ordered sample is f5fa05b9ac500a660edc8f8c9719ddbedeab9667fe31cf4e1d903e8e9626add6, calculated by concatenating each document’s length in eight big-endian bytes and its UTF-8 bytes. The API does not guarantee an immutable revision, so retain the download to repeat that sample. The manifest records shard and vocabulary hashes, checks them when opened, and verifies detection of a corrupted copy. The loader retains those hashes in its state to detect changes when resuming.

With windows of 128, the training stream has 2204721 possible target positions if its shards are concatenated. The loader uses 2203904 and drops 817, including transitions between files. In validation it uses 236544 of 236707 and drops 163. These counts depend on shard and window sizes and are printed on every run.

From the lab to the full corpus

The 1000-document sample establishes and checks the rules; the corpus on which you will train is about 700 times larger. What changes when scaling? Three things, only one of which is truly a problem.

  • Download. The rows API serves 100 documents per request. For millions of documents, download the sample/10BT parquet files from the repository, 2.15 GB each except the final 0.54 GB file, with resumption and SHA-256 verification. This is what the prepare command in p06-l06 does, applying the same exact deduplication, split rule, and vocabulary as this cell and writing shards in the same format. Do not duplicate it here: that would produce another 3.6 GB of identical shards.
  • Index memory. dedup_split keeps each document’s text to check collisions; with millions of documents that is the whole corpus in RAM. At scale it is sufficient to store each 32-byte digest in a set, since a SHA-256 collision is practically impossible, requiring a few hundred megabytes for millions of documents.
  • Permutation. This is not a problem: with D=1.8×109D = 1.8\times 10^9 tokens and T=1024T = 1024, there are about 1.76×1061.76\times 10^6 windows and their int64 permutation occupies about 14 MB. A global permutation only becomes unreasonable around a trillion tokens, where it would occupy gigabytes and be replaced by a two-level shuffle, with random shard order and a permutation inside each shard.

The real preparation bottleneck is tokenization: the p06-l01 encoder is written in Python and processes on the order of megabytes per second per process. The next cell measures how it scales with the number of processes on your machine, using the sample’s training text repeated four times by default; P06_SCALE_REPEAT changes that. It estimates the time to tokenize the p06-l06 corpus at that rate and verifies that results do not depend on process count.

[ ]Scaling tokenization with processesLocal GPU
from pathlib import Path
import os
import subprocess
import sys

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()
if not (data / 'pipeline.py').exists():
    raise FileNotFoundError('Ejecuta antes la celda de preparación de esta lección')
os.environ['P06_PROJECT_ROOT'] = str(project)
os.environ['P06_DATA_DIR'] = str(data)
child_env = dict(os.environ, PYTHONUTF8='1', OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', MKL_NUM_THREADS='1')
source = r'''
"""Tokenización de la muestra con 1, 2, 4, ... procesos: tasa, aceleración e identidad del resultado."""
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor
from pipeline import DATA, fetch, dedup_split, worker_init, worker, verify_manifest

def main():
    manifest = json.loads((DATA / 'manifest.json').read_text(encoding='utf-8'))
    verify_manifest(manifest)
    vocab = json.loads((DATA / manifest['vocab_file']).read_text(encoding='utf-8'))
    ranks = {bytes.fromhex(k): v for k, v in vocab['vocab_hex'].items()}
    eot = vocab['special_id']
    docs = [d for start in range(0, 1000, 100) for d in fetch(start)]
    texts = dedup_split(docs)[0] * int(os.environ.get('P06_SCALE_REPEAT', '4'))
    megabytes = sum(len(t.encode('utf-8')) for t in texts) / 1e6
    cpus = os.cpu_count()
    reference, base, best, best_workers = None, None, 0.0, 1
    print(f'{len(texts)} documentos, {megabytes:.1f} MB de texto, {cpus} procesadores lógicos')
    for workers in sorted({w for w in (1, 2, 4, 8, 16, 24, cpus) if w <= cpus}):
        with ProcessPoolExecutor(workers, initializer=worker_init, initargs=(ranks, eot)) as pool:
            list(pool.map(worker, texts[:2 * workers], chunksize=1))   # arranque de los procesos
            start = time.perf_counter()
            out = list(pool.map(worker, texts, chunksize=8))
            seconds = time.perf_counter() - start
        if reference is None:
            reference, base = out, seconds
        assert out == reference, 'El resultado cambió con el número de procesos'
        print(f'{workers:>3} procesos: {megabytes / seconds:6.1f} MB/s, '
              f'aceleración {base / seconds:5.2f}, eficiencia {base / seconds / workers:4.2f}', flush=True)
        if megabytes / seconds > best:
            best, best_workers = megabytes / seconds, workers
    ordinary = manifest['parts']['train']['tokens'] - manifest['parts']['train']['documents']
    bytes_per_id = manifest['parts']['train']['bytes'] / ordinary
    corpus_gb = 1.8e9 * bytes_per_id / 1e9
    print(f'{bytes_per_id:.3f} bytes por ID: 1800 millones de IDs son unos {corpus_gb:.2f} GB de texto, '
          f'unos {corpus_gb * 1e3 / best / 60:.0f} minutos con {best_workers} procesos ({best:.1f} MB/s)')

if __name__ == '__main__':
    main()
'''
script = data / 'scaling.py'
script.write_text(source, encoding='utf-8')
result = subprocess.run([sys.executable, str(script)], cwd=project, env=child_env,
                        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                        text=True, encoding='utf-8')
print(result.stdout)
result.check_returncode()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the verification run on a Core i9-14900HX, with 8 performance cores with two threads each, 16 efficiency cores, 32 logical processors, and other work active on the machine, one process tokenized 6.6 MB/s; two, 9.8; four, 13.9; eight, 16.0, the maximum. Beyond that, throughput fell to 13.0 with 16 processes, 9.6 with 24, and 7.6 with 32. The three results were identical to the one-process result. At the best rate, the 3.63 GB of text in the p06-l06 corpus would tokenize in about 4 minutes. Absolute figures change greatly with machine load, since the p06-l06 check measured 2.4 to 3.6 MB/s per process, but the curve’s shape is the lesson: speedup departs from ideal long before all cores are exhausted because processes compete for cache and memory bandwidth, the two threads on each performance core share execution units, efficiency cores are slower, and the main process receives, orders, and validates each result alone. With a small sample, task distribution adds more overhead. Choose P06_WORKERS using this measurement on your machine rather than os.cpu_count().

The second cell measures three tasks at batch 16 and context 128: building batches on CPU from the memmap, copying a batch from CPU to GPU, and training a provisional two-block transformer on a batch already resident on the GPU. The training step includes forward pass, loss, backpropagation, and AdamW, excluding data loading and transfer. The copy measurement is independent and uses ordinary CPU memory. CUDA is synchronized at both ends, and loader and training are warmed up.

[ ]Loader versus provisional trainingLocal GPU
from pathlib import Path
import os
import subprocess
import sys

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()
if not (data / 'manifest.json').exists():
    raise FileNotFoundError(f'Falta {data / "manifest.json"}: ejecuta antes la celda de preparación')
os.environ['P06_PROJECT_ROOT'] = str(project)
os.environ['P06_DATA_DIR'] = str(data)
child_env = dict(os.environ, PYTHONUTF8='1')
source = r'''
"""Compara el cargador con un transformador provisional, no con el GPT final."""
import json
import time
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from pipeline import TokenLoader, DATA, verify_manifest

class Block(nn.Module):
    def __init__(self, d=128, heads=4):
        super().__init__()
        self.heads, self.d = heads, d
        self.ln1 = nn.LayerNorm(d)
        self.qkv = nn.Linear(d, 3*d)
        self.proj = nn.Linear(d, d)
        self.ln2 = nn.LayerNorm(d)
        self.mlp = nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d))
    def forward(self, x):
        b, t, d = x.shape
        q, k, v = self.qkv(self.ln1(x)).chunk(3, -1)
        shape = lambda z: z.reshape(b, t, self.heads, d//self.heads).transpose(1, 2)
        out = F.scaled_dot_product_attention(shape(q), shape(k), shape(v), is_causal=True)
        x = x + self.proj(out.transpose(1, 2).contiguous().view(b, t, d))
        return x + self.mlp(self.ln2(x))

class ProxyGPT(nn.Module):
    def __init__(self):
        super().__init__()
        self.embedding = nn.Embedding(513, 128)
        self.position = nn.Embedding(128, 128)
        self.blocks = nn.Sequential(Block(), Block())
        self.final = nn.LayerNorm(128)
        self.head = nn.Linear(128, 513, bias=False)
    def forward(self, x):
        return self.head(self.final(self.blocks(self.embedding(x) + self.position(torch.arange(x.shape[1], device=x.device)))))

def main():
    assert torch.cuda.is_available(), 'Se necesita CUDA para la comparación'
    manifest = json.loads((DATA / 'manifest.json').read_text(encoding='utf-8'))
    verify_manifest(manifest)
    paths = [DATA / x['file'] for x in manifest['parts']['train']['shards']]
    loader = TokenLoader(paths, batch_size=16, seq_len=128, seed=43)
    for _ in range(20): loader.next()
    started = time.perf_counter()
    for _ in range(500): loader.next()
    loader_time = time.perf_counter() - started
    batch = loader.next()
    x_cpu, y_cpu = (torch.from_numpy(a) for a in batch)
    x, y = x_cpu.to('cuda'), y_cpu.to('cuda')
    torch.cuda.synchronize()
    copy_started = time.perf_counter()
    for _ in range(50):
        x_copy, y_copy = x_cpu.to('cuda'), y_cpu.to('cuda')
    torch.cuda.synchronize()
    copy_seconds = time.perf_counter() - copy_started
    del x_copy, y_copy
    torch.manual_seed(73)
    model = ProxyGPT().to('cuda')
    optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
    def step():
        optimizer.zero_grad(set_to_none=True)
        logits = model(x)
        loss = F.cross_entropy(logits.flatten(0, 1), y.flatten())
        loss.backward()
        optimizer.step()
        return loss
    for _ in range(10): step()
    torch.cuda.synchronize()
    started = time.perf_counter()
    for _ in range(50): step()
    torch.cuda.synchronize()
    training_time = time.perf_counter() - started
    batch_tokens = 16 * 128
    loader_rate = batch_tokens*500/loader_time
    gpu_rate = batch_tokens*50/training_time
    result = {'gpu': torch.cuda.get_device_name(), 'batch': 16, 'context': 128,
              'proxy_parameters': sum(p.numel() for p in model.parameters()),
              'loader_batches': 500, 'training_steps': 50,
              'transfer_batches': 50, 'transfer_tokens_per_second': batch_tokens*50/copy_seconds,
              'loader_tokens_per_second': loader_rate, 'proxy_training_tokens_per_second': gpu_rate,
              'ratio': loader_rate/gpu_rate}
    print(json.dumps(result, ensure_ascii=False, indent=2))
    (DATA / 'benchmark.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
    del optimizer, model, x, y
    torch.cuda.empty_cache()

if __name__ == '__main__':
    main()
'''
script = data / 'benchmark.py'
script.write_text(source, encoding='utf-8')
result = subprocess.run([sys.executable, str(script)], cwd=project, env=child_env,
                        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                        text=True, encoding='utf-8')
print(result.stdout)
result.check_returncode()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the verification run on a laptop RTX 4060, the loader built 17.5 million tokens per second, the GPU copy moved 46 million, and provisional training with 544512 parameters consumed 692000: a ratio of 25. In another run, with the GPU occupied by other work, training dropped to 69000 tokens per second and the ratio rose to 46. This variation is why the configuration must always be printed and the measurement repeated. The ratio depends on all activity on the machine, and because it uses a batch already on the GPU, it is not an end-to-end measurement. Even a half-million-parameter model leaves the loader headroom; the real GPT consumes fifty times fewer tokens per second.

The next cell is an optional early check. It requires the p06-l03 implementation and reads its current block directly from MDX. First run this lesson’s data preparation cell. The model is initialized from scratch with the manifest’s 513 IDs. It retains 12 layers, 12 heads, and dimension 768, but has 86236416 parameters. The public GPT-2 in the next lesson has 124439808 parameters because its vocabulary has 50257 IDs. Public weights are not used here.

The measurement builds 1000 batches with the loader, copying them to pinned memory, and separately runs the training step with a batch already on the GPU. It uses microbatch 4 and context 1024 as in p06-l06, BF16, gradient clipping, fused AdamW, three warmup steps, and twenty measured steps. With microbatch 4, peak tensor memory is about 4.3 GiB; if less GPU memory is free, set P06_BENCH_MICROBATCH=1. The GPU rate excludes batch construction and transfer, so it is not an end-to-end measurement. The cell verifies the manifest, identifies the sample and model block by hashes, and releases GPU memory when finished.

[ ]Optional comparison with the GPT from the next lessonLocal GPU
"""Comparar el cargador con el paso de entrenamiento real del GPT de p06-l03.

Configuración de la ejecución larga de p06-l06 (microlote configurable): microlote 4, contexto 1024,
12 capas, 12 cabezas, dimensión 768, vocabulario 513, BF16 y AdamW.
Requiere haber ejecutado la primera celda del laboratorio de p06-l02.
"""
import hashlib
import json
import os
import time
from pathlib import Path
import torch
import torch.nn.functional as F

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()
os.environ['P06_PROJECT_ROOT'] = str(project)
os.environ['P06_DATA_DIR'] = str(data)

def lesson_cell(filename, title):
    path = project / 'src/content/lessons/p06' / filename
    mdx = path.read_text(encoding='utf-8')
    marker = f'```python run runtime=local title="{title}"\n'
    return mdx.split(marker, 1)[1].split('\n```', 1)[0]

pipeline_cell = lesson_cell('l02-datos-de-preentrenamiento.mdx',
                            'Descarga, tokenización en procesos y shards')
pipeline_code = pipeline_cell.split("source = r'''\n", 1)[1].split("\n'''", 1)[0]
pipeline = {'__name__': 'pipeline_de_la_leccion'}
exec(compile(pipeline_code, 'p06-l02.mdx', 'exec'), pipeline)
manifest = json.loads((data / 'manifest.json').read_text(encoding='utf-8'))
pipeline['verify_manifest'](manifest)
assert manifest['vocab_ordinary'] == 512 and manifest['eot_id'] == 512

gpt_cell = lesson_cell('l03-modelo-gpt-y-paridad.mdx', 'GPT propio y controles')
gpt_code = gpt_cell.split('\nattention_test()\nbehavior_test()', 1)[0]
gpt = {'__name__': 'gpt_de_la_leccion'}
exec(compile(gpt_code, 'p06-l03.mdx', 'exec'), gpt)
assert torch.cuda.is_available(), 'Se necesita CUDA para la comparación'

# Microlote y contexto de la configuración larga de p06-l06. Con microlote 4 el pico
# de memoria ronda 4.3 GiB; si tu GPU tiene menos libre, P06_BENCH_MICROBATCH=1.
B, T = int(os.environ.get('P06_BENCH_MICROBATCH', '4')), 1024
files = [data / shard['file'] for shard in manifest['parts']['train']['shards']]
loader = pipeline['TokenLoader'](files, batch_size=B, seq_len=T, seed=43)
for _ in range(30):
    loader.next()
start = time.perf_counter()
for _ in range(1000):
    xb, yb = loader.next()
    xb, yb = torch.from_numpy(xb).pin_memory(), torch.from_numpy(yb).pin_memory()
loader_seconds = time.perf_counter() - start
x_array, y_array = loader.next()
model = optimizer = x = y = None
try:
    x, y = torch.from_numpy(x_array).cuda(), torch.from_numpy(y_array).cuda()
    torch.manual_seed(73)
    model = gpt['GPT'](vocab=513, context=1024, layers=12, heads=12, d=768, dropout=0.0).cuda().train()
    count = sum(p.numel() for p in model.parameters())
    assert count == gpt['count_formula'](513, 1024, 12, 768) == 86236416
    assert gpt['count_formula'](50257, 1024, 12, 768) == 124439808
    optimizer = torch.optim.AdamW(model.parameters(), lr=6e-4, betas=(0.9, 0.95), weight_decay=0.1, fused=True)
    def step():
        optimizer.zero_grad(set_to_none=True)
        with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
            logits = model(x)
            loss = F.cross_entropy(logits.flatten(0, 1).float(), y.flatten())
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
    torch.cuda.reset_peak_memory_stats()
    for _ in range(3):
        step()
    torch.cuda.synchronize()
    start = time.perf_counter()
    for _ in range(20):
        step()
    torch.cuda.synchronize()
    train_seconds = time.perf_counter() - start
    loader_rate = B * T * 1000 / loader_seconds
    train_rate = B * T * 20 / train_seconds
    print('GPU:', torch.cuda.get_device_name())
    print(f'12 capas, 12 cabezas, dimensión 768; microlote {B}, contexto {T}, BF16')
    print('Tiempo por paso:', f'{train_seconds / 20 * 1000:.0f} ms')
    print('Vocabulario propio 513: parámetros', count)
    print('GPT-2 con vocabulario 50257: parámetros 124439808')
    print('SHA-256 celda GPT:', hashlib.sha256(gpt_cell.encode('utf-8')).hexdigest())
    print('SHA-256 muestra:', manifest['sample_sha256'])
    print('Lotes cargador:', 1000, 'pasos de entrenamiento medidos:', 20, 'calentamiento:', 3)
    print(f'Cargador (con copia a memoria fijada): {loader_rate:,.0f} tokens/s')
    print(f'Paso de entrenamiento: {train_rate:,.0f} tokens/s')
    print(f'Cociente cargador/paso GPU: {loader_rate / train_rate:,.0f}')
    print(f'Memoria GPU asignada máxima: {torch.cuda.max_memory_allocated() / 2**30:.2f} GiB')
finally:
    del optimizer, model, x, y
    torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The verification run used P06_BENCH_MICROBATCH=1 to stay under 2 GiB. Peak usage was 1.96 GiB, the step took 76 ms, or 13510 tokens per second, and the loader with pinned-memory copying delivered 10.75 million tokens per second, a ratio of 796. Microbatch 4 takes longer per step but processes more tokens. The short p06-l06 check measured 9853 to 11301 tokens per second in complete updates. The margin over the threshold of 10 is almost two orders of magnitude, so one reading process will not limit long pretraining. This measurement does not cover cold reads. With 3.6 GB of shards fitting in the operating system’s page cache on a machine with at least 16 GB, that will not be a problem in practice, but a corpus of hundreds of gigabytes would require measuring disk performance.

Exercises

NumericStream size
3000000000 tokens are stored as uint16 without headers. How many decimal gigabytes do they occupy, with 1 GB = 1000000000 bytes?
NumericChanging the type
For the same 3000000000 tokens, how many decimal GB does int32 occupy without headers?
QuizBefore converting
You switch to a vocabulary of 100000 IDs and convert an int64 array containing ID 70000 with ids.astype(np.uint16). What happens, and what should you do?
QuizNearly identical copies
Which procedure best reduces leakage of near-identical pages between training and validation?
QuizDocument boundaries
An end token is inserted between two documents, but the causal mask is unchanged. What is guaranteed?
NumericThe cost of not crossing
The training corpus is written into 18 shards of exactly 100000000 tokens each, and the loader forms aligned windows of context T = 1024 without crossing shards. How many target positions in the concatenated stream does it never use?
QuizWhat loader state should be saved
The lab's TokenLoader regenerates each epoch's permutation from (seed, epoch). A checkpoint saves weights, optimizer, and seed, but not loader state. What happens when resuming halfway through epoch 3?
CodeSave the next batch
Implement TokenLoader for a fixed token list. A window starts at 0, T, 2T, and so on and is valid only if T+1 tokens are available. Each epoch shuffle its starts using random.Random(seed); next_batch() returns an (x, y) pair of lists of length T and generates a new permutation when the previous one is exhausted. state_dict() and load_state_dict(state) must also restore random state to reproduce batches across epoch changes. The returned state must not change when the loader advances.
import random

class TokenLoader:
  def __init__(self, tokens, T, seed):
      pass

  def next_batch(self):
      pass

  def state_dict(self):
      pass

  def load_state_dict(self, state):
      pass
Shift+Enter to run
Key idea

A token stream is reproducible when its selection, format, and next-batch state are reproducible too. Exact deduplication, separators, and resumption are verified with independent tests.