60 / 90

Day 60: Post-Mortem Evaluation, Billing Audit, Safetensors & Teardown

Audit final model perplexity and sample quality, reconcile cloud invoices down to the dollar, export Safetensors, and destroy instances.

Models and Pretraining 480 active minutes (8 hours)
01 120 min

Final Checkpoint Validation, Perplexity and Coherence Evaluation

Agent-Assisted Engineering Check

Prerequisites

Day 59 Cloud Pretraining execution and Day 53 Validation metrics.

Learning Objective

Evaluate the final trained checkpoint on held-out validation tokens, compute validation loss and perplexity, and run autoregressive sampling to audit text coherence.

Instructions

1. Load the final checkpoint with map_location='cpu' (or your GPU), load its 'model' state into a freshly built model, and call model.eval().
2. Build a fixed list of held-out validation batches, so that two checkpoints are always compared on identical tokens.
3. Compute L_val as the mean cross-entropy over those batches inside torch.no_grad(), then PPL = exp(L_val).
4. Compare with the uniform baseline ln(V): for character-level Shakespeare, V = 65 and ln(65) = 4.1744, which is why L_val below 4.0 means the model beats guessing.
5. Generate five samples with temperature=0.8 and top_k=40 from the same prompt, and test each for degenerate loops (a long run of one token, or too few distinct tokens).
6. Read the samples yourself and record the checkpoint step, L_val, PPL, the samples, the decoding settings and the seed.

Time plan (120 min): reading 20 + exercise 70 + check 30. Reading: the estimate_loss and sampling code in nanoGPT and the CS336 notes on evaluation. Exercise: steps 1-6 on your final checkpoint. Check: explain the L_val and PPL thresholds from ln(V) without notes.

Practice & Prediction Log

Run an evaluation script on the final checkpoint. Assert that validation loss is lower than initial random initialization (L_val < 4.0 for Shakespeare, or PPL < 50) and that generated completions contain no repetitive single-token loops.

Independent Mastery Criterion

Validate final checkpoint performance with mathematical perplexity and coherence verification.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: estimate_loss() averages eval_iters batches per split; run every eval_interval; best_val_loss decides when a checkpoint is saved

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Python, PyTorch, and Day 46-48 Transformer model architecture.

Safe Fallback (Offline Resilience):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Fluent Python, PyTorch, and linear algebra

Safe Fallback (Offline Resilience):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

02 120 min

Comprehensive Cloud Spending Reconciliation and Cost Audit

Independent Mastery Check (no AI assistance).

Prerequisites

Day 60 Activity 1 and Day 58 Budget ceilings.

Learning Objective

Conduct an exact accounting audit: reconcile actual GPU billed hours, persistent disk volume fees, and egress bandwidth charges, calculating the final cost-per-billion-tokens metric.

Instructions

1. Export the provider's usage breakdown for the run, not only the summary total.
2. Itemize the costs: compute (hours * $/hr), storage (GB * $/GB-month * days / 30.4), and network egress (GB * $/GB). Write each line with its unit.
3. Add the lines and round only the final total to cents.
4. Reconcile with the Day 58 preflight budget, whose ceiling must lie in (0, 20.0]: state PASS or FAIL, and if it fails, give the overrun and the largest compute time that would have stayed under the ceiling.
5. Compute the efficiency metrics: cost per billion tokens = total / tokens * 1e9, and the implied throughput tokens / (hours * 3600).
6. Write one sentence on the cause of any overrun and one change that would prevent it next time.

Time plan (120 min): reading 20 + exercise 65 + check 35. Reading: the EleutherAI Transformer Math compute-cost section and your Day 58 preflight report. Exercise: the itemized bill and the reconciliation. Check: redo the reconciliation for a variant (12 hours of compute) unaided.

Practice & Prediction Log

You trained on 10B tokens using 16.7 hours of an A100 ($1.50/hr), with 50GB storage for 1 day ($0.10/GB/month = $0.16) and 2GB checkpoint download ($0.08/GB = $0.16). Calculate total bill and cost-per-billion-tokens. Then reconcile against the Day 58 $20 ceiling: does the run pass? If not, give the overrun and the maximum compute hours that would have stayed within the ceiling.

Independent Mastery Criterion

Itemize and reconcile full cloud spending down to the exact penny.

Authoritative Source Resources & Provenance

linking CC-BY 4.0

Transformer Math 101

Author: Quentin Anthony, Stella Biderman, Hailey Schoelkopf | Original Source Link ↗

Relevant Section / Range: Engineering Takeaways for Compute Costs

Verified Version & Date: EleutherAI Research Blog (Verified: 2026-10-30)

Selection Rationale:

Widely cited, practical industry guide deriving 6ND compute FLOPs, activation memory, KV cache size, and VRAM estimation.

Source Prerequisites:

Transformer matrix dimensions and matrix multiplication FLOP counting.

Safe Fallback (Offline Resilience):

The 6ND derivation (2ND forward, 4ND backward) and peak VRAM estimation models are fully worked out in the curriculum.

Compared Candidate Sources & Selection Analysis (2)

Rigorous academic formulation; Transformer Math 101 provides accessible step-by-step arithmetic equations.

Kaplan et al. Section 2.1 Compute Budgeting ↗ compared_alternative [Open Access]

Original 6ND approximation; EleutherAI expands on activation memory and KV cache.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Fluent Python, PyTorch, and linear algebra

Safe Fallback (Offline Resilience):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

03 120 min

Safetensors Format Export and Destructive Cloud Resource Teardown

Agent-Assisted Engineering Check

Prerequisites

Day 60 Activities 1-2, Safetensors library, cloud CLI/console teardown.

Learning Objective

Export PyTorch checkpoint weights into secure zero-copy Safetensors format, download artifacts locally, and execute irreversible cloud teardown to stop all ongoing charges.

Instructions

1. Load checkpoint.pt on the CPU and keep only the 'model' weights; drop the optimizer state and other training metadata.
2. Strip the '_orig_mod.' prefix that torch.compile adds to every key.
3. Handle tied weights: safetensors refuses tensors that share storage (lm_head.weight is transformer.wte.weight in GPT). Save an independent contiguous copy of each tensor and re-tie after loading.
4. Save model.safetensors with metadata, reload it with load_file, and assert a bit-exact round trip (same keys, torch.equal on every tensor).
5. Record the file size and SHA-256, copy the file home with rsync, and compare the local digest before touching the cloud.
6. Tear down in order: terminate the instance (terminated, not stopped), delete every volume, snapshot and bucket from this run, and list again later to confirm active instances = 0 and active volumes = 0.

Time plan (120 min): reading 20 + exercise 70 + check 30. Reading: the safetensors documentation (format and torch API) and the checkpoint layout in nanoGPT train.py. Exercise: the export script and the teardown checklist. Check: explain without notes why safetensors removes the pickle risk and why tied weights need a copy.

Practice & Prediction Log

Write a Python conversion script export_to_safetensors.py that reads 'checkpoint.pt', extracts 'model', strips optimizer states, saves 'model.safetensors', and verifies it loads cleanly with safetensors.torch.load_file.

Independent Mastery Criterion

Successfully convert model to Safetensors and execute teardown verification.

Authoritative Source Resources & Provenance

linking Apache-2.0

Safetensors: Simple, Safe and Fast Tensor Storage

Author: Nicolas Patry, Hugging Face Team | Original Source Link ↗

Relevant Section / Range: README 'Format' (8-byte header size, JSON header, tensor byte buffer)

Verified Version & Date: Safetensors 0.4.x / GitHub (Verified: 2026-10-30)

Selection Rationale:

Widely adopted format for secure model checkpoint export, preventing arbitrary code execution vulnerability inherent to Python pickle.

Source Prerequisites:

Binary serialization, memory mapping (mmap), and tensor state dictionaries.

Safe Fallback (Offline Resilience):

Zero-copy tensor slicing and header dictionary parsing are demonstrated in pure Python.

Compared Candidate Sources & Selection Analysis (2)
Python pickle module documentation ↗ compared_alternative [PSF License]

Default PyTorch serialization; Safetensors replaces pickle to eliminate arbitrary code execution security hazards.

ONNX Model Format Specification ↗ compared_alternative [Apache 2.0]

Full computational graph interchange format; Safetensors focuses strictly on zero-overhead raw weight storage.

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Python, PyTorch, and Day 46-48 Transformer model architecture.

Safe Fallback (Offline Resilience):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

04 120 min

Assessment: Four-Language Experimental Reproduction Report

Independent Mastery Check (no AI assistance).

Prerequisites

Day 60 Activities 1-3.

Learning Objective

Assemble the entire cloud pretraining reproduction into a standardized technical experiment report across all four supported languages, documenting parameters, metrics, expenditure, and teardown verification.

Instructions

1. Collect the numbers from their sources: final step and losses from the run log, MFU from the Day 59 monitor, total cost from the Activity 2 reconciliation, and teardown evidence from the provider CLI output.
2. Store each number once and render every language section from that single record, so the editions cannot disagree.
3. Check internal consistency: PPL = exp(L_val), and MFU is a fraction between 0 and 1.
4. Scan the whole report for secrets and private addresses (IP addresses, access keys, tokens, private key blocks).
5. Report the budget result honestly: if Activity 2 failed the $20 ceiling, every edition says so and names the cause.
6. Sign off the teardown only with evidence: instances = 0 and volumes = 0, with the date.

Time plan (120 min): reading 15 + exercise 75 + check 30. Reading: the CS336 reporting notes and your Activities 1-3 records. Exercise: fill the report and run the checks. Check: the mastery run with all assertions passing, then a reread of each edition.

Practice & Prediction Log

Complete the four-language reproduction report template. Verify that all numerical metrics match the actual experiment log and that the teardown checklist is signed off.

Independent Mastery Criterion

Deliver a complete, certified four-language cloud pretraining reproduction report.

Authoritative Source Resources & Provenance

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Fluent Python, PyTorch, and linear algebra

Safe Fallback (Offline Resilience):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

linking Apache-2.0

Safetensors: Simple, Safe and Fast Tensor Storage

Author: Nicolas Patry, Hugging Face Team | Original Source Link ↗

Relevant Section / Range: README 'Format' (8-byte header size, JSON header, tensor byte buffer)

Verified Version & Date: Safetensors 0.4.x / GitHub (Verified: 2026-10-30)

Selection Rationale:

Widely adopted format for secure model checkpoint export, preventing arbitrary code execution vulnerability inherent to Python pickle.

Source Prerequisites:

Binary serialization, memory mapping (mmap), and tensor state dictionaries.

Safe Fallback (Offline Resilience):

Zero-copy tensor slicing and header dictionary parsing are demonstrated in pure Python.

Compared Candidate Sources & Selection Analysis (2)
Python pickle module documentation ↗ compared_alternative [PSF License]

Default PyTorch serialization; Safetensors replaces pickle to eliminate arbitrary code execution security hazards.

ONNX Model Format Specification ↗ compared_alternative [Apache 2.0]

Full computational graph interchange format; Safetensors focuses strictly on zero-overhead raw weight storage.