67 / 90

Day 67: Fine-Tuning Recipe Preflight, Zero-Shot Baselines & Spending Caps

Lock in LoRA hyperparameters, benchmark pre-finetuning zero-shot baselines, and enforce hard spending caps.

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

Fine-Tuning Recipe Configuration and Hyperparameter Audit

Agent-Assisted Engineering Check

Prerequisites

Day 64-66 LoRA mathematics and Day 49-51 pretraining loops.

Learning Objective

Audit learning rate schedules (cosine decay with warmup to 2e-4), rank r=16, alpha=32, batch size, and target linear projections against standard LoRA recipes.

Instructions

Study source: within this activity's existing reading/practice time, use Hugging Face LLM Course: Fine-tuning LLMs, Chapter 11.3: Training Configuration, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. 1. Review the published recipes (Alpaca, the LoRA paper, PEFT) and write down the value each uses:
- Learning rate: 1e-4 to 3e-4 for LoRA, about 10x the usual full fine-tuning rate (1e-5 to 2e-5), because only the small adapter is updated.
- Rank and scale: r=16, alpha=32, so the adapter output is scaled by alpha/r = 2.0.
- Target modules: all attention projections (q_proj, k_proj, v_proj, o_proj), or all linear layers.
- Schedule: linear warmup over 3% to 5% of the steps, then cosine decay to 10% of the peak.
2. Write config.json with these values plus max_steps=1000, seq_len=1024 and min_lr_ratio=0.1.
3. Implement lr_at(step) and check three points by hand: the end of warmup (step 29 of 30 warmup steps) is 2e-4, the last step is 2e-5, and the rate rises during warmup.
4. Check the sequence format: every pair is packed into a fixed length (512 or 1024 tokens) and ends with the EOS token.
5. Check loss masking on one example: prompt tokens get label -100, and only the answer tokens and EOS count in the loss.

Time plan (120 min): reading 30 + exercise 60 + check 30. Reading: the Alpaca training recipe and Hu et al. (LoRA) Section 7 on which weight matrices to adapt and which rank to use. Exercise: steps 2-5. Check: recompute alpha/r and the warmup step count, and explain from memory why the LoRA rate is 10x higher.

Practice & Prediction Log

Construct a configuration dictionary config.json for training a 7B model on Alpaca-format data. Assert that rank=16, alpha=32, lr=2e-4, warmup_ratio=0.03, and loss_masking=True.

Independent Mastery Criterion

Formulate a complete, mathematically sound instruction fine-tuning configuration.

Authoritative Source Resources & Provenance

linking Apache-2.0

Hugging Face LLM Course: Fine-tuning LLMs

Author: Hugging Face course contributors | Original Source Link ↗

Relevant Section / Range: Chapter 11.3: Training Configuration

Verified Version & Date: Public edition checked 2026-11-01; moving pages may change

Selection Rationale:

Sequenced templates, supervised fine-tuning and evaluation teaching with exercises/quizzes. LoRA method and memory claims are checked against the original paper, PEFT and the local parameter ledger, not accepted wholesale from Chapter 11.4.

Source Prerequisites:

Python, PyTorch, language-model training and the preceding chat-format lessons.

Safe Fallback (Offline Resilience):

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

Compared Candidate Sources & Selection Analysis (2)
LoRA original paper ↗ compared_alternative [arXiv.org perpetual non-exclusive license / Open Access]

Retained for initialization and the low-rank method, not a beginner teaching sequence.

Hugging Face PEFT ↗ compared_alternative [Apache-2.0]

Retained for actual API and implementation defaults; reference documentation is not a complete teaching course.

linking Copyright Stanford CRFM (blog post; no open license stated)

Stanford Alpaca: An Instruction-following LLaMA Model

Author: Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, Tatsunori B. Hashimoto | Original Source Link ↗

Relevant Section / Range: Training recipe

Verified Version & Date: Stanford CRFM Release (Verified: 2026-10-30)

Selection Rationale:

Original open recipe demonstrating lightweight instruction fine-tuning of open models, establishing prompt/response templates, batch scheduling, and learning rate ranges.

Source Prerequisites:

Supervised fine-tuning, instruction formatting, and LoRA fundamentals.

Safe Fallback (Offline Resilience):

Complete instruction templates, JSONL formatting scripts, and learning rate schedules are self-contained in curriculum materials.

Compared Candidate Sources & Selection Analysis (2)

Multi-turn ShareGPT tuning recipe; Alpaca provides simpler, single-turn clarity ideal for foundational instruction tuning study.

Databricks Dolly 15k Dataset & Training Recipe ↗ compared_alternative [CC-BY-SA 3.0]

Commercially permissive crowdsourced dataset; Alpaca established the academic instruction tuning standard.

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

Author: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | Original Source Link ↗

Relevant Section / Range: Appendix D Hyperparameters Used in Experiments

Verified Version & Date: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

Selection Rationale:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

Source Prerequisites:

Matrix factorization, rank, linear layers, and transformer attention.

Safe Fallback (Offline Resilience):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

Compared Candidate Sources & Selection Analysis (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

02 120 min

Zero-Shot Baseline Evaluation on Target Evaluation Prompts

Independent Mastery Check (no AI assistance).

Prerequisites

Day 67 Activity 1 and model evaluation metrics.

Learning Objective

Run the un-finetuned base model against a fixed suite of evaluation prompts, recording baseline task accuracy, formatting compliance, and failure examples.

Instructions

1. Fix a held-out suite of domain prompts (for example 50 structured-extraction prompts). Each item has an id, the prompt and the JSON keys a correct answer must contain.
2. Load the base model with no adapter. Decode with temperature=0.1, max_new_tokens=256 and a fixed seed, and record these parameters exactly; Day 69 reuses them.
3. Score every output automatically: it must parse with json.loads, be a JSON object, and contain every expected key. Record why each failure failed.
4. Save the failure outputs verbatim. Typical base-model failures: a chatty prefix before the JSON, an object that stops in the middle, or a missing key.
5. Write baseline_results.json with the accuracy, the number of prompts, the decoding parameters and a SHA-256 hash of the prompt suite, so Day 69 can prove it used the same suite.
6. Note the resolution of your measurement: with 10 prompts each prompt moves accuracy by 10 points.

Time plan (120 min): reading 15 + exercise 75 + check 30. Reading: InstructGPT (Ouyang et al.) Section 1 on why base models do not follow instructions, and the Alpaca evaluation notes. Exercise: steps 1-6 on 10 prompts. Check: re-score one saved failure by hand and confirm the hash matches the suite.

Practice & Prediction Log

Run zero_shot_eval.py on 10 test prompts using the base model. Compute accuracy (e.g. 10% to 20%) and record exact failure outputs where the model produced conversational filler instead of the requested JSON.

Independent Mastery Criterion

Establish an immutable, empirical baseline performance record before initiating fine-tuning.

Authoritative Source Resources & Provenance

linking Open Access

Training language models to follow instructions with human feedback

Author: Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, et al. | Original Source Link ↗

Relevant Section / Range: Section 3.6 Evaluation and Section 4.1 Results on the API distribution

Verified Version & Date: arXiv:2203.02155v1 (Verified: 2026-10-30)

Selection Rationale:

Foundational InstructGPT paper defining the SFT objective: maximizing log-likelihood of demonstrator completions conditioned on prompts.

Source Prerequisites:

Supervised fine-tuning, conditional autoregressive generation.

Safe Fallback (Offline Resilience):

The conditional likelihood objective and prompt-conditioning derivations are completely formulated in the review.

Compared Candidate Sources & Selection Analysis (2)

Earlier RLHF formulation on summarization; InstructGPT standardizes the prompt-response SFT training phase.

Focuses on massive multi-task scaling; InstructGPT details the exact prompt-conditioned loss setup.

linking Copyright Stanford CRFM (blog post; no open license stated)

Stanford Alpaca: An Instruction-following LLaMA Model

Author: Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, Tatsunori B. Hashimoto | Original Source Link ↗

Relevant Section / Range: Preliminary evaluation

Verified Version & Date: Stanford CRFM Release (Verified: 2026-10-30)

Selection Rationale:

Original open recipe demonstrating lightweight instruction fine-tuning of open models, establishing prompt/response templates, batch scheduling, and learning rate ranges.

Source Prerequisites:

Supervised fine-tuning, instruction formatting, and LoRA fundamentals.

Safe Fallback (Offline Resilience):

Complete instruction templates, JSONL formatting scripts, and learning rate schedules are self-contained in curriculum materials.

Compared Candidate Sources & Selection Analysis (2)

Multi-turn ShareGPT tuning recipe; Alpaca provides simpler, single-turn clarity ideal for foundational instruction tuning study.

Databricks Dolly 15k Dataset & Training Recipe ↗ compared_alternative [CC-BY-SA 3.0]

Commercially permissive crowdsourced dataset; Alpaca established the academic instruction tuning standard.

03 120 min

Cloud Spending Caps, Time Ceilings & Preflight Stop Triggers

Agent-Assisted Engineering Check

Prerequisites

Day 67 Activity 1 and Day 58 Budget ceilings.

Learning Objective

Establish strict financial and temporal boundaries for the LoRA run: max budget <= $10.00, maximum duration < 2 hours, and define automated kill triggers.

Instructions

1. Estimate the run: LoRA trains about 0.5% of the parameters, the batch fits on one GPU, and an instruction-tuning run usually needs 1 to 2 GPU hours.
2. Set the ceilings: the spending cap is $10.00. Plan 2.0 hours: $1.20 at $0.60/hr on an A10G, or $3.00 at $1.50/hr on an A100.
3. Set the stop triggers:
- Step limit: stop at step 1000 or after 3 epochs.
- Plateau: stop early when validation loss has not improved for 3 evaluations in a row.
- Timeout guard: kill the process when wall-clock time passes 2.5 hours. Worst case on an A100: 2.5 * $1.50 = $3.75, still under the cap.
4. Write check_budget_limits(max_cost, max_hours). It rejects a cost above $10.00 or more than 3 hours (the hard validator bound, above the 2.5-hour guard).
5. Reject invalid inputs too: NaN, infinity, negative values and booleans. NaN > 10.0 is False, so a plain comparison lets NaN through.
6. Never start a background job without these caps.

Time plan (120 min): reading 20 + exercise 70 + check 30. Reading: Hu et al. (LoRA) on how few parameters are trained, the Alpaca cost notes, and your Day 58 budget rules. Exercise: steps 2-5 with a test for each bad input. Check: recompute the three costs ($1.20, $3.00, $3.75) without notes.

Practice & Prediction Log

Write a pre-flight budget assertion check_budget_limits(max_cost, max_hours). Confirm that it rejects configurations exceeding $10.00 or 3 hours.

Independent Mastery Criterion

Enforce strict financial guardrails ensuring LoRA fine-tuning never incurs unexpected cloud debt.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

Author: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | Original Source Link ↗

Relevant Section / Range: N/A

Verified Version & Date: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

Selection Rationale:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

Source Prerequisites:

Matrix factorization, rank, linear layers, and transformer attention.

Safe Fallback (Offline Resilience):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

Compared Candidate Sources & Selection Analysis (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.

linking Copyright Stanford CRFM (blog post; no open license stated)

Stanford Alpaca: An Instruction-following LLaMA Model

Author: Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, Tatsunori B. Hashimoto | Original Source Link ↗

Relevant Section / Range: N/A

Verified Version & Date: Stanford CRFM Release (Verified: 2026-10-30)

Selection Rationale:

Original open recipe demonstrating lightweight instruction fine-tuning of open models, establishing prompt/response templates, batch scheduling, and learning rate ranges.

Source Prerequisites:

Supervised fine-tuning, instruction formatting, and LoRA fundamentals.

Safe Fallback (Offline Resilience):

Complete instruction templates, JSONL formatting scripts, and learning rate schedules are self-contained in curriculum materials.

Compared Candidate Sources & Selection Analysis (2)

Multi-turn ShareGPT tuning recipe; Alpaca provides simpler, single-turn clarity ideal for foundational instruction tuning study.

Databricks Dolly 15k Dataset & Training Recipe ↗ compared_alternative [CC-BY-SA 3.0]

Commercially permissive crowdsourced dataset; Alpaca established the academic instruction tuning standard.

04 120 min

Assessment: Preflight Fine-Tuning Validator and Baseline Ledger Audit

Independent Mastery Check (no AI assistance).

Prerequisites

Day 67 Activities 1-3.

Learning Objective

Build and verify an automated FinetunePreflightValidator class that checks dataset formatting, loss masking, budget boundaries, and baseline evaluation records before training launches.

Instructions

1. Create FinetunePreflightValidator(dataset_path, baseline_path, budget_limit).
2. verify_data(): read the tokenized JSONL. Every row must have input_ids and labels of the same length, the first label must be -100 (the prompt is masked), and at least one label must not be -100 (something is trained). Report the row count and the first bad rows.
3. verify_baseline(): baseline_results.json from Activity 2 must exist, its accuracy must be a number between 0 and 1, n must be positive, and the decoding parameters must be recorded.
4. verify_budget(): the limit must be a finite positive number no greater than 10.0.
5. validate(): run all three checks and return verdict='GO' only when every check passes; otherwise 'NO-GO'. Include each check's details, baseline_score and data_samples_count in the report.
6. Test both outcomes: one valid fixture gives GO, and one broken input per check (a budget over 10, a missing baseline, a NaN budget) gives NO-GO. A validator that cannot say NO-GO certifies nothing.

Time plan (120 min): reading 10 + exercise 80 + check 30. Reading: your notes from Activities 1-3 and the Alpaca data format. Exercise: the class and its fixtures. Check: the mastery run with every GO and NO-GO assertion passing, without AI help.

Practice & Prediction Log

Run FinetunePreflightValidator on a valid fixture and confirm it returns 'GO' with baseline_score and data_samples_count in the report. Then break each check in turn (budget above $10.00, missing baseline file, NaN budget) and confirm every case returns 'NO-GO'.

Independent Mastery Criterion

Construct a production preflight validator certifying instruction tuning readiness.

Authoritative Source Resources & Provenance

linking Copyright Stanford CRFM (blog post; no open license stated)

Stanford Alpaca: An Instruction-following LLaMA Model

Author: Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, Tatsunori B. Hashimoto | Original Source Link ↗

Relevant Section / Range: N/A

Verified Version & Date: Stanford CRFM Release (Verified: 2026-10-30)

Selection Rationale:

Original open recipe demonstrating lightweight instruction fine-tuning of open models, establishing prompt/response templates, batch scheduling, and learning rate ranges.

Source Prerequisites:

Supervised fine-tuning, instruction formatting, and LoRA fundamentals.

Safe Fallback (Offline Resilience):

Complete instruction templates, JSONL formatting scripts, and learning rate schedules are self-contained in curriculum materials.

Compared Candidate Sources & Selection Analysis (2)

Multi-turn ShareGPT tuning recipe; Alpaca provides simpler, single-turn clarity ideal for foundational instruction tuning study.

Databricks Dolly 15k Dataset & Training Recipe ↗ compared_alternative [CC-BY-SA 3.0]

Commercially permissive crowdsourced dataset; Alpaca established the academic instruction tuning standard.

linking arXiv non-exclusive license / Open Access

LoRA: Low-Rank Adaptation of Large Language Models

Author: Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen | Original Source Link ↗

Relevant Section / Range: N/A

Verified Version & Date: ICLR 2022 / arXiv:2106.09685v2 (Verified: 2026-10-30)

Selection Rationale:

Primary literature introducing Low-Rank Adaptation, establishing parameter decomposition W = W0 + (alpha/r)*BA, initialization strategies, and zero inference latency merging.

Source Prerequisites:

Matrix factorization, rank, linear layers, and transformer attention.

Safe Fallback (Offline Resilience):

Complete matrix derivations, tensor dimensions, and pure PyTorch LoRALinear modules are implemented directly in lesson code.

Compared Candidate Sources & Selection Analysis (2)

Introduces bottleneck adapter layers in series, which introduces unavoidable inference latency overhead; LoRA's parallel formulation merges with zero latency.

Prepends virtual prompt tokens; reduces available context length, unlike LoRA which preserves full sequence capacity.