Train, save, and reload a small causal language model on a controlled corpus.
Section 1.1 1 of 7
Overview
Focus
Train, save, and reload a small causal language model on a controlled corpus.
Your route through the lesson
1.2 Text datasets, document splits, and training batches
1.3 Optimization, checkpoints, and resume state
1.4 Held-out loss and generated samples
1.5 Put it into practice
1.6 Guided comparison
1.7 Resuming interrupted miniature training
All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.
Section 1.2 2 of 7
Text datasets, document splits, and training batches
Focus
Turn a controlled text corpus into source-separated next-token training examples.
Pretraining learns a predictive objective from a corpus before task-specific instruction tuning. For a character language model, each character is a token and the objective predicts the next character. The architecture from Week 3 can learn this objective without downloading a pretrained model.
Keep document identities before creating overlapping windows. If two windows from the same document overlap heavily and land on opposite sides of a random window split, evaluation can reward memorized passages. Split source documents first, then make training, validation, and test windows within their assigned sources. A training-only vocabulary needs an explicit unknown-character policy for later text.
The lab uses a deliberately small generated device-message corpus. Its templates are familiar patterns, so held-out results describe this controlled toy distribution, not open-ended language understanding. Construct input windows of length T and targets shifted one character forward. Both arrays are shaped (batch,T). Randomly choose training windows with a recorded seed, while validation uses fixed held-out windows for checkpoint selection.
// Quick review
Check your understanding.
Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.
Section 1.3 3 of 7
Optimization, checkpoints, and resume state
Focus
Train the checked decoder and save enough state to reproduce a checkpoint.
Reuse the TinyDecoder architecture, its vocabulary mapping, and its maximum context length. Training makes a forward pass, calculates next-token cross-entropy, backpropagates, and updates model parameters. Unlike a prompt, this changes stored weights. Start by measuring loss on a fixed training batch before any updates so later changes have a reference.
A checkpoint should include the model state dictionary, architecture settings, tokenizer mapping, training step, and any state required for the intended resume behavior. Resuming the same optimizer trajectory also requires optimizer state and relevant random-generator state. Loading only model weights is suitable for inference but does not promise bit-for-bit continuation of training.
Use validation loss to preserve a candidate checkpoint. Record data construction and package versions. Reload into a fresh compatible model and compare evaluation outputs on a known input. A filename alone is not evidence of compatibility: a different vocabulary order can silently associate learned rows with the wrong characters even when tensor shapes match.
// Quick review
Check your understanding.
Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.
Section 1.4 4 of 7
Held-out loss and generated samples
Focus
Evaluate a fixed checkpoint without turning the final test into training feedback.
Training loss measures fitting; validation selects a checkpoint; the final test estimates the selected procedure on held-out records. Compute evaluation loss in evaluation mode without gradient recording. Average with a clear denominator: if windows contain different numbers of valid tokens, a simple mean of batch means can weight them incorrectly.
For equal-length windows, averaging all per-token losses gives a straightforward token-weighted measure. Perplexity is exp(mean cross-entropy) when loss uses the natural logarithm. A loss of ln(2) gives perplexity two. This expresses predictive uncertainty under the token objective; it is not a percentage of true factual answers.
Generate samples from more than one fixed prefix and note the decoding settings. Compare untrained and trained output alongside measured loss. A readable sample can be lucky and an unattractive sample can coexist with improved average prediction. Report both aggregate evidence and examples instead of selecting a single flattering continuation as proof of competence.
// Quick review
Check your understanding.
Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.
Section 1.5 5 of 7
Put it into practice
Focus
Train and reload a miniature character model using a complete local script.
Save week03.py and week04.py beside each other in your exercise folder. The second file imports the checked TinyDecoder class from the first. Run python week04.py --lesson 1 --output week04-checkpoint.pt with the PyTorch environment.
The lab creates source documents, builds source-separated windows, trains a small processor-capable model, selects a checkpoint by validation loss, and saves weights plus reconstruction metadata. It prints initial and final fixed-batch training loss, selected validation loss, final test loss, and a generated sample. The checkpoint path is an exercise artifact you control; do not overwrite an unrelated model file.
A Python import executes definitions from another module, so file location matters. If week03 cannot be imported, verify that both downloaded files are in the same folder before changing the model. The lab reconstructs a fresh model from the saved metadata and asserts that its evaluation outputs match the original selected model. Inspect the actual measured results; the controlled corpus is intentionally small.
Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.
Section 1.6 6 of 7
Guided comparison
Focus
Separate fitted weights, checkpoint selection, and reconstruction evidence.
A completed run has several independent pieces of evidence. Parameter snapshots before and after training show that learning changed the model. Loss on the same fixed batch shows whether it fit that sample better. Validation measurements determine which saved state is selected. Test loss then describes that selected state on the held-out test windows.
For reconstruction, instantiate the stored vocabulary size and hidden dimensions, load the state dictionary, switch to evaluation mode, and run the same known prefix. Matching outputs within a declared tolerance checks this reload path. If the vocabulary's character order changes, equal tensor shapes alone will not protect meaning.
Preserve the selected model, not merely the last state in memory. The lab saves inference reconstruction metadata and explicitly does not promise an exact optimizer resume. That distinction matters when an interrupted run should continue: an inference checkpoint restores useful model computation, while exact training continuation needs the additional optimizer and random-state contract.
// Quick review
Check your understanding.
Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.
Section 1.7 7 of 7
Resuming interrupted miniature training
Focus
Plan an interrupted training restart without confusing it with inference reload.
Suppose training stops at step 100. An inference checkpoint contains learned weights and tokenizer metadata; loading it restores the predictor. If a new optimizer starts with fresh moving averages, step 101 may differ from an uninterrupted run even with the same visible learning rate.
For reproducible training continuation, save step count, optimizer state, scheduler state if used, and random-generator states. Also preserve data-order or sampler position so the next batch matches. The underlying dataset and preprocessing versions must still agree. A changed input corpus makes the restarted experiment a new data version rather than a transparent continuation.
Use a small restart fixture before a long run: train several steps, save complete state, continue a reference path, then restore into fresh objects and compare the next checked step under controlled execution. If the hardware or framework does not provide exact determinism, declare the numerical comparison policy rather than claiming identity from a shared filename.
// Quick review
Check your understanding.
Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.
Your personal notes
Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.