Skip to content

Commit f95e244

Browse files
committed
tp-review2 changes
1 parent 794f837 commit f95e244

26 files changed

Lines changed: 421 additions & 329 deletions

‎ACCELERATORS.md‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,65 @@ You do not need a training-capable GPU to follow along. Every chapter's trained
4545
| Subfolder | Chapter | Artifact | Base |
4646
| --- | --- | --- | --- |
4747
| `ch5-lora` | 5 | LoRA adapter | Qwen3-4B-Instruct-2507 |
48+
| `ch5-qlora` | 5 | QLoRA adapter (r=8; `--quantized_4bit` needs a CUDA card, or load it on the bf16 base) | Qwen3-4B-Instruct-2507 |
4849
| `ch6-sft` | 6 | full SFT model (standalone) | (full fine-tune) |
4950
| `ch7-distilled` | 7 | distilled student (LoRA) | Qwen3-4B-Instruct-2507 |
5051
| `ch8-dpo` | 8 | full DPO model (standalone) | (full fine-tune) |
5152
| `ch8-dpo-lora` | 8 | LoRA-DPO adapter (fits one 24 GB card) | `ch6-sft` |
5253

53-
Load a full model with `AutoModelForCausalLM.from_pretrained("bahree/ModelAdaptationBook", subfolder="ch6-sft")`, or an adapter with `PeftModel.from_pretrained(base, "bahree/ModelAdaptationBook", subfolder="ch5-lora")`. This is why the "What runs where" table marks chapters 6 to 8 as not running on Apple Silicon: that is about *training* them. You can still *use* their results on a Mac by pulling the trained model.
54+
Load a full model with `AutoModelForCausalLM.from_pretrained("bahree/ModelAdaptationBook", subfolder="ch6-sft")`, or an adapter with `PeftModel.from_pretrained(base, "bahree/ModelAdaptationBook", subfolder="ch5-lora")`.
55+
56+
**The exact commands.** Every model or adapter path argument in the book's scripts also accepts a Hub reference of the form `repo#subfolder` (resolved by `common/hub.py`), so each chapter's evaluation and inference steps run from the published artifact with no local training run. Run from `code/` with the virtual environment active; the first run downloads the base model (about 8 GB) and the artifact, both cached afterwards, no token required. Quote the reference on shells where `#` starts a comment.
57+
58+
```bash
59+
# Chapter 5: evaluate and run the published LoRA adapter (step 3 and step 5 of the chapter)
60+
python -m chapter05.scripts.listing_5_3_evaluate \
61+
--base Qwen/Qwen3-4B-Instruct-2507 \
62+
--adapter "bahree/ModelAdaptationBook#ch5-lora" \
63+
--test data/it_support/test.jsonl
64+
python -m chapter05.generate \
65+
--base Qwen/Qwen3-4B-Instruct-2507 \
66+
--adapter "bahree/ModelAdaptationBook#ch5-lora" \
67+
--prompt "Explain how photosynthesis works in simple terms."
68+
# Chapter 5, step 6: the QLoRA adapter (4-bit base, CUDA only)
69+
python -m chapter05.generate \
70+
--base Qwen/Qwen3-4B-Instruct-2507 \
71+
--adapter "bahree/ModelAdaptationBook#ch5-qlora" --quantized_4bit \
72+
--prompt "Explain how photosynthesis works in simple terms."
73+
74+
# Chapter 6: the full SFT model
75+
python -m chapter06.eval_sft --data_dir data/it_support --split test \
76+
--model_dir "bahree/ModelAdaptationBook#ch6-sft" \
77+
--output chapter06/runs/sft_hub/eval_report.json
78+
python -m chapter06.generate --model_dir "bahree/ModelAdaptationBook#ch6-sft" \
79+
--prompt "How do I troubleshoot a VPN connection failure?"
80+
81+
# Chapter 7: teacher (the chapter 6 model) and the distilled student
82+
python -m chapter07.eval_distillation --data_dir chapter07/data/distill_ready \
83+
--teacher_dir "bahree/ModelAdaptationBook#ch6-sft" \
84+
--student_dir "bahree/ModelAdaptationBook#ch7-distilled" \
85+
--source_dir data/it_support_fmt
86+
python -m chapter07.generate --adapter_dir "bahree/ModelAdaptationBook#ch7-distilled" \
87+
--prompt "How do I troubleshoot a VPN connection failure?"
88+
89+
# Chapter 8: the DPO model against the SFT model
90+
python -m chapter08.eval_dpo --data_dir data/it_support --split test \
91+
--sft_dir "bahree/ModelAdaptationBook#ch6-sft" \
92+
--dpo_dir "bahree/ModelAdaptationBook#ch8-dpo" \
93+
--output chapter08/eval/dpo_report_hub.json
94+
python -m chapter08.generate --model_dir "bahree/ModelAdaptationBook#ch8-dpo" \
95+
--prompt "How do I troubleshoot a VPN connection failure?"
96+
97+
# Chapter 9: canary prompts and the safety monitor on the published models
98+
python -m chapter09.scripts.run_canary_prompts \
99+
--model_dir "bahree/ModelAdaptationBook#ch6-sft" \
100+
--output chapter09/eval/canary_baseline.jsonl
101+
python -m chapter09.safety_monitor \
102+
--model_dir "bahree/ModelAdaptationBook#ch6-sft" \
103+
--output chapter09/eval/safety_report.json
104+
```
105+
106+
On Windows, replace the trailing `\` with `^` and keep the quotes around the Hub references. This is why the "What runs where" table marks chapters 6 to 8 as not running on Apple Silicon: that is about *training* them. You can still *use* their results on a Mac by pulling the trained model.
54107

55108
## GPU requirements at a glance
56109

@@ -63,7 +116,7 @@ AMD (ROCm) was validated end-to-end on a datacenter card (Instinct MI300X); VRAM
63116
| 3 (data-quality experiment) | same profile as chapter 5 LoRA | 8 GB | 12 GB+ | Yes | Synthetic-data pipeline yes; manifest module yes; full experiment slow | Yes, verified (bf16 LoRA on MPS); synthetic-data pipeline and manifest module also yes |
64117
| 4 (ICL/RAG) | inference only (~8 GB for the optional HF backend) | None for mock backends; ~8 GB for the optional Qwen3-4B HF backend | 12 GB+ | Yes | Yes (mock backend / hash embedder) | Yes (mock backends are CPU; HF backend uses MPS, slow on 8 GB) |
65118
| 5 (LoRA, r=16) | **9.0 GB** allocated (10.2 GB reserved), one card | 8 GB (RTX 3060/4060+) | 12 GB+ | Yes | Yes, but ~20× slower | Yes (trains on MPS) |
66-
| 5 (QLoRA, r=8) | **5.1 GB** allocated (5.4 GB reserved), one card | 6 GB | 8 GB+ | Yes (4-bit works; benign `rocminfo` warning) | Not recommended | **No** (`bitsandbytes` is CUDA-only) |
119+
| 5 (QLoRA, r=8) | **5.1 GB** allocated (5.4 GB reserved), one card | 6 GB | 8 GB+ | Yes (4-bit works; benign `rocminfo` warning) | Not recommended | **No** (`bitsandbytes` is CUDA-only; the published `ch5-qlora` adapter loads on the bf16 base for inference) |
67120
| 6 (Full SFT) | **32.5 GB** total (17.2 + 15.3 GB across two A30s); **OOM on one A30** at 23.2 GB during AdamW state init | Two 24 GB cards (A30 / RTX 4090), or one 40 GB card | A100 40 GB+ | Yes | No | No |
68121
| 7 (Distillation, LoRA student r=16) | **10.5 GB** allocated (15.8 GB reserved, batch 2), one card | 12 GB for the student; the teacher-generation stage loads the chapter 6 model for inference (~10 GB) | 24 GB+ | Yes | Not recommended | Student: yes in principle (LoRA on MPS); teacher generation is slow |
69122
| 8 (DPO, full-parameter) | **54.3 GB** total (18.4 + 18.6 + 17.3 GB across three A30s); **OOM on two A30s** (23.2 + 22.7 GB) | Three 24 GB cards, or one 80 GB card | A100 80 GB / H100 | Yes | No | No |

‎code/chapter01/run_sidebar_example.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def main():
172172
f"Full SFT model ({args.sft_dir.name})")
173173

174174
args.output.parent.mkdir(parents=True, exist_ok=True)
175-
with open(args.output, "w") as f:
175+
with open(args.output, "w", encoding="utf-8") as f:
176176
json.dump(results, f, indent=2)
177177
print(f"\n[saved] {args.output}")
178178

‎code/chapter03/ch03_data_quality_helpers.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,7 @@ def save_results_json(results: dict[str, dict], output_dir: str) -> str:
513513
for k, v in results.items()
514514
}
515515
path = os.path.join(output_dir, "results.json")
516-
with open(path, "w") as f:
516+
with open(path, "w", encoding="utf-8") as f:
517517
json.dump(save, f, indent=2)
518518
return path
519519

‎code/chapter03/ch03_datasetmanifest.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,13 @@ def set_retention(self, years: int = 2) -> "DatasetManifest":
136136
def save(self, path: str) -> None:
137137
"""Write the manifest to a JSON file."""
138138
Path(path).parent.mkdir(parents=True, exist_ok=True)
139-
with open(path, "w") as f:
139+
with open(path, "w", encoding="utf-8") as f:
140140
json.dump(vars(self), f, indent=2)
141141

142142
@classmethod
143143
def load(cls, path: str) -> "DatasetManifest":
144144
"""Load a manifest from a JSON file."""
145-
with open(path) as f:
145+
with open(path, encoding="utf-8") as f:
146146
data = json.load(f)
147147
return cls(**data)
148148

‎code/chapter03/ch03_synthetic_data_generation.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -659,7 +659,7 @@ def to_chatml(ex: dict) -> dict:
659659
"trained_models": [], # populated after training with checkpoint info
660660
}
661661

662-
with open(f"{output_dir}/manifest.json", "w") as f:
662+
with open(f"{output_dir}/manifest.json", "w", encoding="utf-8") as f:
663663
json.dump(manifest, f, indent=2)
664664

665665
print(f"\nStep 6: Mixed dataset saved to {output_dir}/")

‎code/chapter05/README.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,23 @@ python -m chapter05.train_lora ^
214214
Saved LoRA adapter to: **chapter05/runs/it_lora**
215215
```
216216

217+
### Run without training: the published adapters
218+
219+
The chapter's LoRA adapter is published as `bahree/ModelAdaptationBook#ch5-lora` (and the QLoRA adapter as `#ch5-qlora`); every `--adapter` argument below accepts that `repo#subfolder` form, so steps 3 to 5 run on any machine, including Apple Silicon, without a training run:
220+
221+
```bash
222+
python -m chapter05.scripts.listing_5_3_evaluate \
223+
--base Qwen/Qwen3-4B-Instruct-2507 \
224+
--adapter "bahree/ModelAdaptationBook#ch5-lora" \
225+
--test data/it_support/test.jsonl
226+
python -m chapter05.generate \
227+
--base Qwen/Qwen3-4B-Instruct-2507 \
228+
--adapter "bahree/ModelAdaptationBook#ch5-lora" \
229+
--prompt "Explain how photosynthesis works in simple terms."
230+
```
231+
232+
The QLoRA adapter needs `--quantized_4bit` (CUDA only) to match training. See [ACCELERATORS.md](../../ACCELERATORS.md#running-without-training-pull-the-model-from-hugging-face) for every chapter's commands.
233+
217234
### Step 3: Evaluate LoRA vs Base Model
218235

219236
Compare the fine-tuned model to the base model:

‎code/chapter06/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ Training time: ~10 min (2x A30, sharded), ~45-60 min (A100). A single 24 GB card
103103

104104
### Step 3: Generate a response (Listing 6.3)
105105

106+
> **No training GPU?** The chapter's SFT model is published as `bahree/ModelAdaptationBook#ch6-sft`; `--model_dir` accepts that `repo#subfolder` form, so `eval_sft` and `generate` run from the published model (for example `--model_dir "bahree/ModelAdaptationBook#ch6-sft"`). Commands for every chapter: [ACCELERATORS.md](../../ACCELERATORS.md#running-without-training-pull-the-model-from-hugging-face).
107+
106108
```bash
107109
python -m chapter06.generate \
108110
--model_dir chapter06/runs/sft_run1 \

‎code/chapter06/scripts/safety_regression.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ def main():
280280
"regression_detected": regression_detected,
281281
}
282282
report_path = output_path / "safety_report.json"
283-
with open(report_path, "w") as f:
283+
with open(report_path, "w", encoding="utf-8") as f:
284284
json.dump(report, f, indent=2)
285285

286286
write_jsonl(output_path / "safety_details.jsonl", base_results + ft_results)

‎code/chapter07/README.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,8 @@ WARNING: Safety regression detected in student model.
413413
Generate text with the trained student adapter:
414414

415415
**Linux/macOS:**
416+
> **No training GPU?** The distilled student is published as `bahree/ModelAdaptationBook#ch7-distilled` and the teacher as `#ch6-sft`; `--teacher_dir`, `--student_dir`, and `--adapter_dir` accept that `repo#subfolder` form (for example `--adapter_dir "bahree/ModelAdaptationBook#ch7-distilled"`). Commands for every chapter: [ACCELERATORS.md](../../ACCELERATORS.md#running-without-training-pull-the-model-from-hugging-face).
417+
416418
```bash
417419
python -m chapter07.generate \
418420
--adapter_dir chapter07/runs/student_run1 \
@@ -497,12 +499,12 @@ The script writes a single JSON to `chapter07/runs/frontier_comparison.json` (or
497499

498500
### Reading the output
499501

500-
The chapter quotes the Ch6 SFT response (terse, generic) alongside Claude Sonnet 5.5's response (structured by category, with command examples and a follow-up question). The same gap will show up on most domain-specific prompts where you have an SFT model trained on a few hundred examples and the frontier model has been trained on the entire internet:
502+
The chapter quotes the Ch6 SFT response (terse, generic) alongside Claude Sonnet 4.5's response (structured by category, with command examples and a follow-up question). The same gap will show up on most domain-specific prompts where you have an SFT model trained on a few hundred examples and the frontier model has been trained on the entire internet:
501503

502504
- If the frontier response is dramatically more thorough and specific, distillation has a clear quality target. The cost model in §7.3 then tells you whether the per-request economics justify it.
503505
- If the responses are roughly comparable, your SFT model is already close to the ceiling for this task type and distillation may not move the needle. Save the budget for a different intervention (a better prompt, more training data, a different metric).
504506

505-
The Gemini 3.1 Pro response includes a `reasoning` field with the model's internal scratchpad; the `content` field is the user-facing answer. The chapter quotes only `content`; the JSON keeps both for audit.
507+
The Gemini 2.5 Pro response includes a `reasoning` field with the model's internal scratchpad; the `content` field is the user-facing answer. The chapter quotes only `content`; the JSON keeps both for audit.
506508

507509
## Understanding the results
508510

‎code/chapter07/eval/compute_format_adherence.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"""
1717
from __future__ import annotations
1818

19+
import argparse
1920
import gc
2021
import json
2122
import sys
@@ -38,12 +39,14 @@
3839
VALID = "data/it_support/valid.jsonl"
3940
OUT = "chapter07/eval/format_report.json"
4041
# --eval_file / --out override these (the book reports on data/it_support/test.jsonl, 2026-09-19)
41-
import argparse
4242
_ap = argparse.ArgumentParser(add_help=False)
43-
_ap.add_argument("--eval_file", default=None); _ap.add_argument("--out", default=None)
43+
_ap.add_argument("--eval_file", default=None)
44+
_ap.add_argument("--out", default=None)
4445
_args, _ = _ap.parse_known_args()
45-
if _args.eval_file: VALID = _args.eval_file
46-
if _args.out: OUT = _args.out
46+
if _args.eval_file:
47+
VALID = _args.eval_file
48+
if _args.out:
49+
OUT = _args.out
4750

4851

4952
def is_adapter(path: str) -> bool:

0 commit comments

Comments
 (0)