From-scratch pretraining Completed 31 July 2026

GPT-2 124M,
rebuilt from first principles.

A decoder-only Transformer trained from random initialization on nearly 10 billion FineWeb-Edu tokens—documented from architecture and data preparation through failure recovery, evaluation, and public release.

Parameters
124.48M
Training tokens
10.00B
Validation loss
3.0308
HellaSwag
30.03%

What does it take to reproduce a foundational language model—not by fine-tuning an existing checkpoint, but by constructing the network, preparing the corpus, and carrying a random initialization through a complete pretraining run?

This project implements GPT-2 small as a compact, readable PyTorch system. It includes causal multi-head self-attention, pre-normalized residual blocks, tied token and output weights, distributed-aware data loading, bfloat16 training, deterministic evaluation, and exact checkpoint resume. The final model processed 9,999,745,024 tokens over 19,073 optimizer steps.

The result is intentionally modest in scale and unusually complete in documentation. The model, training record, public demo, metrics, checkpoint verification, recovery chronology, and source code can all be inspected independently.

Run signature Terminal checkpoint · independently verified
Compute1× H100single GPU
Duration9.40 hcumulative training
Throughput295ktokens per second
Compute cost$25.39time × rate estimate
Checkpoint1.39 GiBSHA-256 verified
StatusCompletepublicly released

02 · Architecture

A small Transformer, shown all the way through.

GPT-2 is a decoder-only Transformer: every token can attend only to itself and earlier tokens. The implementation uses learned token and position embeddings, twelve identical pre-LN Transformer blocks, a final layer norm, and a vocabulary projection whose weights are shared with the input embedding table.

Model dataflow Select a block to inspect it
Input Token IDs ≤ 1,024 positions
Embedding Token + position 50,304 × 768

12× Transformer blocks

Output LN + tied head next-token logits
Block 01 Identical topology · independent weights
NormalizeLayerNorm768 features
→
Mix contextCausal attention12 heads × 64
+
NormalizeLayerNorm768 features
→
TransformGELU MLP768 → 3,072 → 768
+

Both sublayers use pre-normalization and residual addition. Attention calls PyTorch’s scaled dot-product kernel with is_causal=True; the MLP expands the channel width by 4× before projecting back.

Context1,024tokens
Width768embedding dimensions
Depth12Transformer blocks
Heads1264 dimensions each
MLP3,072hidden dimensions
Vocabulary50,304padded for efficiency
Where 124,475,904 parameters live The language-model head is weight-tied

Weight tying reuses the 38.6M-token embedding matrix for output logits, avoiding a second vocabulary projection with the same shape.

03 · Data

Ten billion educational tokens, verified shard by shard.

Training used the FineWeb-Edu sample-10BT configuration. Documents were encoded with the GPT-2 tiktoken vocabulary, prefixed with the end-of-text token, stored as compact uint16 arrays, and divided into 100 verified shards.

Dataset preparation Network work remains separate from paid training
  1. 01FineWeb-Edusample-10BT documents
  2. 02GPT-2 tokenizerEOT + ordinary tokens
  3. 03NumPy shardsup to 100M uint16 tokens
  4. 04Verify & hashreadability, size, SHA-256
  5. 05Manifest complete100 shards · ~19.9 GB

Ordered loading

Shard names are validated and numerically ordered before training. A malformed, duplicated, or missing shard causes a preflight failure rather than an expensive partial run.

Deterministic position

DataLoaderLite records the rank-zero data position plus batch, sequence, and world-size metadata, allowing every distributed rank to reconstruct its exact position after resume.

04 · Training

A production recipe small enough to audit.

Each optimizer step aggregates 32 micro-batches of 16 sequences × 1,024 tokens, producing an effective batch of 524,288 tokens. The run uses AdamW, bfloat16 autocasting, gradient clipping, linear warmup, and cosine learning-rate decay.

16sequences
×
1,024tokens each
×
32accumulation steps
=
524,288tokens / optimizer step
Maximum learning rate
6 × 10−4
Minimum learning rate
6 × 10−5
Warmup
715 steps
Weight decay
0.1
Gradient clipping
1.0
Precision
bfloat16
Initialization seed
42
Compilation
Disabled
Learning-rate schedule Observed continuation · steps 13,140–19,070

The complete schedule is defined by the run configuration; the committed scalar history contains the final continuation segment.

05 · Results

The terminal checkpoint improved cleanly to the end.

The final checkpoint records a training loss of 3.1033, validation loss of 3.0308, and validation perplexity of 20.71. The graphs below are generated directly from the committed CSV and clearly mark the observed continuation window.

Optimization trajectory Raw training loss + rolling mean
Validation loss 25 deterministic evaluations
Training throughput Final continuation · single H100
Zero-shot HellaSwag accuracy Normalized completion likelihood

3,016 / 10,042 correct. The 29.4% reference is Karpathy’s evaluation of the released checkpoint, not a number from OpenAI’s original paper. The datasets differ and the reference is rounded, so this is a descriptive—not controlled—comparison.

06 · Reliability

The run survived because state was treated as a product.

The most consequential engineering work was not another model layer. It was making a multi-hour paid run recoverable: atomic local checkpoints, complete optimizer and RNG state, verified uploads, bounded retries, resumable downloads, and a latest pointer that advances only after integrity checks pass.

Failure and recovery chronology One continuous optimization identity
  1. 01
    Artifact channel overflow

    The tokenized dataset exceeded the 5 GiB batch artifact path.

    Moved to progressive, verified object-storage uploads.
  2. 02
    Preparation retries

    Runtime image, tokenizer resources, and workspace constraints surfaced.

    Restored the ordered original loader and retained completed shards.
  3. 03
    Checkpoint response loss

    A synchronizer lost a response while rereading a large object.

    Switched to local SHA-256 plus remote size and sidecar checks.
  4. 04
    Interrupted transfers

    Transient upload and download failures threatened continuation.

    Added bounded retries, range resume, and atomic finalization.
  5. 05
    Verified continuation

    Model, optimizer, loader, RNG, token count, and W&B identity restored.

    Resumed at completed step + 1 and finished step 19,073.
Anatomy of the final checkpoint 1,493,919,114 bytes · CPU load passed
final_step_
019073.pt
format v1
  • Model149 tensors · 124.48M parameters
  • OptimizerAdamW momentum and variance state
  • Data loaderShard, position, batch, and rank state
  • RandomnessCPU, CUDA, Python, and NumPy RNG
  • ProvenanceConfig, Git SHA, W&B ID, elapsed time
  • IntegritySize, SHA-256, sidecar, and latest pointer

SHA-256e519d993d20c98c841ef061f76a1dec3e6ee24d5e55162bdea2a3e2da280fd40

07 · Samples

What the base model continues.

These fixed-seed samples use top-50 sampling and a 72-token total sequence limit. They are qualitative examples, not benchmark scores. Their unevenness is representative of a small, unaligned completion model.

The future of artificial intelligence is

The future of artificial intelligence is also expanding. As artificial intelligence and its algorithms have increasingly grown, the field continues to rely heavily on human experts and computer vision researchers to guide its operations and its algorithms remain largely untrained…
Seed 19073Top-k 50GPT-2 tiktoken

08 · Intended use and limitations

Useful as a learning artifact. Limited as a language system.

Appropriate use

Research and education

  • Studying a readable GPT-2 implementation.
  • Reproducing training and checkpoint mechanics.
  • Exploring base-model text continuation.
  • Benchmarking small-model infrastructure.
Out of scope

Autonomous or high-stakes use

  • Conversational instruction following.
  • Medical, legal, financial, or safety decisions.
  • Unsafeguarded public content generation.
  • Claims requiring factual reliability.
01

Scale

124M parameters and one approximately 10B-token pass are not competitive with modern frontier systems.

02

Alignment

No instruction tuning, preference optimization, refusal training, or dedicated safety tuning was performed.

03

Content risks

Outputs may be incorrect, incoherent, biased, unsafe, or stylistically derivative of pretraining data.

04

Evaluation coverage

HellaSwag is the only full downstream benchmark; no broad safety, bias, memorization, or toxicity suite was run.

05

Evidence window

The committed scalar history covers the final continuation segment, while terminal metrics come from the verified final checkpoint.

09 · Reproducibility and resources

Follow every important claim back to evidence.

The public release separates narrative from evidence. Human-readable reports explain the run; JSON, CSV, configuration, source, and checkpoint records make its central claims inspectable.

Local smoke test
python train_gpt2.py --smoke-test --benchmark-steps 1