Skip to content

Commit 60d25e9

Browse files
committed
Refactor Chapter 5 Scripts and Update Dataset Preparation and cleaned up unnecessary code and improved documentation for clarity.
1 parent 9aa0a4d commit 60d25e9

19 files changed

Lines changed: 1400 additions & 1400 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ Every chapter ships with runnable code. The hands-on chapters (4 through 9) repr
2727
| **[Chapter 1: Why Model Adaptation?](code/chapter01/README.md)** | A reproducibility script for the §1.6 sidebar. Runs the same prompt through base Qwen3-4B, the Chapter 5 LoRA adapter, and the Chapter 6 SFT model side by side; degrades gracefully if the later-chapter artifacts are not yet built. |
2828
| **[Chapter 2: How Do I Do Model Adaptation?](code/chapter02/README.md)** | A five-step LoRA fine-tuning quickstart on Qwen3-4B-Instruct-2507 using a 40-example Dolly subset (TRL's `SFTTrainer` plus PEFT): dataset prep, LoRA training, generation, and adapter save. Runs in under 10 minutes on a 12 GB GPU, and on Apple Silicon via MPS. |
2929
| **[Chapter 3: What Data Do I Need?](code/chapter03/README.md)** | Data-quality experiment that trains the same model on four versions of Financial PhraseBank and compares results on a held-out test set; a six-step synthetic data generation pipeline (load → prompt → generate → quality-gate → distribution-check → mix-and-save) using a frontier teacher; and a standalone `DatasetManifest` module for content hashing, lineage tracking, and retention scheduling. |
30-
| **[Chapter 4: In-Context Learning and Few-Shot Adaptation](code/chapter04/README.md)** | Few-shot ticket classifier, prompt validator with run-to-run variability measurement, minimal RAG pipeline (50 lines), and a Precision@k / Recall@k / Hit@1 retrieval evaluator. CPU-friendly; GPU optional. |
30+
| **[Chapter 4: In-Context Learning, Few-Shot, and RAG](code/chapter04/README.md)** | Few-shot ticket classifier, prompt validator with run-to-run variability measurement, minimal RAG pipeline (50 lines), and a Precision@k / Recall@k / Hit@1 retrieval evaluator. CPU-friendly; GPU optional. |
3131
| **[Chapter 5: Parameter-Efficient Fine-Tuning (LoRA and QLoRA)](code/chapter05/README.md)** | LoRA and QLoRA adapters trained on a 400-example Dolly subset of Qwen3-4B-Instruct-2507, evaluated against the base model with per-category Token-F1 and a safety regression suite. |
3232
| **[Chapter 6: Supervised Fine-Tuning (SFT)](code/chapter06/README.md)** | A full-parameter SFT of Qwen3-4B-Instruct-2507 on a technical-support Dolly subset, with overfit monitoring, three-way base-vs-LoRA-vs-SFT comparison, behavioral tests, and a separate safety regression suite. |
3333
| **[Chapter 7: Knowledge Distillation](code/chapter07/README.md)** | Black-box distillation from the chapter 6 SFT teacher into a chapter 5-style LoRA student, with quality filtering, three-way base-vs-teacher-vs-student evaluation, safety robustness check, and an optional OpenRouter-backed SFT-vs-frontier-API comparison. |

‎code/chapter02/quickstart.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@
7070
def step1_prepare_dataset() -> tuple[HFDataset, HFDataset, List[Dict[str, Any]]]:
7171
"""Step 1: download Dolly 15K and keep 40 train + 5 valid + 3 demo examples.
7272
73-
Same filter and seed as chapter 5's listing_5_2_prepare_dataset.py, just a
73+
Same filter and seed as chapter 5's listing_5_1_prepare_dataset.py, just a
7474
smaller slice so the run finishes in minutes.
7575
"""
7676
print("Step 1: prepare dataset")

‎code/chapter02/run_chapter5_adapter.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def print_no_adapter_instructions(args: argparse.Namespace) -> None:
111111
print("Two ways to fix this:")
112112
print()
113113
print("Option A. Train the chapter 5 adapter locally:")
114-
print(" python -m chapter05.scripts.listing_5_2_prepare_dataset \\")
114+
print(" python -m chapter05.scripts.listing_5_1_prepare_dataset \\")
115115
print(" --out chapter05/data/dolly_subset --seed 42")
116116
print(" python -m chapter05.train_lora \\")
117117
print(" --train chapter05/data/dolly_subset/train.jsonl \\")

‎code/chapter04/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Chapter 4 -- In-Context Learning and Few-Shot Adaptation
1+
# Chapter 4 -- In-Context Learning, Few-Shot, and RAG
22

33
This chapter covers how to get useful work out of a model without training it: few-shot prompting, many-shot prompting on long-context models, prompt validation against held-out test sets, and a minimal retrieval-augmented generation (RAG) pipeline. The code in this folder backs the four numbered listings in the chapter.
44

‎code/chapter05/README.md‎

Lines changed: 566 additions & 566 deletions
Large diffs are not rendered by default.

‎code/chapter05/eval.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
3. **Toy golden set** - Simple Q&A pairs to sanity-check model behavior.
77
88
Also includes loss/perplexity computation on held-out JSONL data, and report
9-
generation (JSON + Markdown). Used by ``scripts/listing_5_4_evaluate.py``
10-
(Listing 5.4) to compare base model vs. adapter variants.
9+
generation (JSON + Markdown). Used by ``scripts/listing_5_3_evaluate.py``
10+
(Listing 5.3) to compare base model vs. adapter variants.
1111
"""
1212
from __future__ import annotations
1313

@@ -473,7 +473,7 @@ def write_report(path: str | Path, obj: Dict[str, Any]) -> None:
473473
"""Write an evaluation results dict as a JSON file.
474474
475475
The JSON report is the machine-readable counterpart to the human-readable
476-
Markdown summary generated by ``listing_5_4_evaluate.py``. Both are saved
476+
Markdown summary generated by ``listing_5_3_evaluate.py``. Both are saved
477477
to the same output directory (e.g., ``chapter05/runs/eval_report/``).
478478
479479
Args:

‎code/chapter05/examples/README_INTERPRETING_RESULTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Understanding Your Evaluation Results
22

3-
This guide helps you interpret the evaluation report from `listing_5_4_evaluate.py`.
3+
This guide helps you interpret the evaluation report from `listing_5_3_evaluate.py`.
44

55
---
66

‎code/chapter05/examples/example_data_prep_outcome_types.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
These illustrate the response types discussed in the chapter's "Data quality
44
iterations" section, using the Contoso IT-support assistant. Each is a single
55
training row in the same `messages` format produced by
6-
`scripts/listing_5_2_prepare_dataset.py` (see `dolly_to_messages`).
6+
`scripts/listing_5_1_prepare_dataset.py` (see `dolly_to_messages`).
77

88
> **These rows are illustrative.** The Dolly 15K subset used in this chapter
99
> contains no refusals and no tone tags, so these are examples of what you would

‎code/chapter05/examples/example_qlora_evaluation_output.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ This file captures a typical run of the evaluation script when comparing the **b
55
## Command
66

77
```bash
8-
python chapter05/scripts/listing_5_4_evaluate.py \
8+
python chapter05/scripts/listing_5_3_evaluate.py \
99
--base Qwen/Qwen3-4B-Instruct-2507 \
1010
--adapter chapter05/runs/dolly_lora \
1111
--adapter_alt chapter05/runs/dolly_qlora \

‎code/chapter05/generate.py‎

Lines changed: 110 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -1,110 +1,110 @@
1-
"""Inference script: generate text with the base model and an optional LoRA/QLoRA adapter (Listing 5.5).
2-
3-
Loads the base model, optionally attaches a LoRA or QLoRA adapter, and generates
4-
a response for a single user prompt. Supports adapter merging for deployment.
5-
6-
Usage (base model only):
7-
python -m chapter05.generate --base Qwen/Qwen3-4B-Instruct-2507 \\
8-
--prompt "Explain how photosynthesis works in simple terms."
9-
10-
Usage (with LoRA adapter):
11-
python -m chapter05.generate --base Qwen/Qwen3-4B-Instruct-2507 \\
12-
--adapter chapter05/runs/dolly_lora \\
13-
--prompt "Explain how photosynthesis works in simple terms."
14-
15-
Usage (with QLoRA adapter -- must use --quantized_4bit):
16-
python -m chapter05.generate --base Qwen/Qwen3-4B-Instruct-2507 \\
17-
--adapter chapter05/runs/dolly_qlora --quantized_4bit \\
18-
--prompt "Explain how photosynthesis works in simple terms."
19-
20-
See Chapter 5, Section 5.1 (Step 4) and the README for full details.
21-
"""
22-
from __future__ import annotations
23-
24-
import argparse
25-
from pathlib import Path
26-
27-
import torch
28-
from peft import PeftModel
29-
from transformers import AutoModelForCausalLM
30-
31-
from chapter05 import DEFAULT_MODEL_NAME
32-
from chapter05.chat_template import DEFAULT_SYSTEM_PROMPT, build_prompt_text
33-
from chapter05.modeling import load_base_model_lora, load_base_model_qlora, load_tokenizer
34-
35-
36-
def parse_args() -> argparse.Namespace:
37-
"""Parse command-line arguments for inference.
38-
39-
Returns:
40-
Namespace with base model, adapter path, prompt, generation settings,
41-
and optional merge/quantization flags.
42-
"""
43-
ap = argparse.ArgumentParser()
44-
ap.add_argument("--base", default=DEFAULT_MODEL_NAME)
45-
ap.add_argument("--adapter", default=None, help="Path to LoRA/QLoRA adapter folder")
46-
ap.add_argument("--prompt", required=True, help="User prompt")
47-
ap.add_argument("--system_prompt", default=DEFAULT_SYSTEM_PROMPT)
48-
ap.add_argument("--max_new_tokens", type=int, default=128)
49-
ap.add_argument("--do_sample", action="store_true")
50-
ap.add_argument("--temperature", type=float, default=0.7)
51-
ap.add_argument("--quantized_4bit", action="store_true", help="Load base in 4-bit (requires bitsandbytes)")
52-
ap.add_argument("--merge_adapter", action="store_true", help="Merge adapter into base before generation")
53-
ap.add_argument("--save_merged", default=None, help="If set, save merged model to this folder")
54-
return ap.parse_args()
55-
56-
57-
def main() -> None:
58-
"""Load model, optionally attach adapter, and generate a response."""
59-
args = parse_args()
60-
tokenizer = load_tokenizer(args.base)
61-
62-
# Use --quantized_4bit when running a QLoRA-trained adapter so the base
63-
# model is loaded in 4-bit (matching the precision used during training).
64-
if args.quantized_4bit:
65-
model = load_base_model_qlora(args.base, gradient_checkpointing=False)
66-
else:
67-
model = load_base_model_lora(args.base, gradient_checkpointing=False)
68-
69-
if args.adapter:
70-
model = PeftModel.from_pretrained(model, args.adapter)
71-
if args.merge_adapter:
72-
# merge_and_unload() permanently folds LoRA weights into the base.
73-
# This loses modularity (can't swap adapters) but can be faster
74-
# for high-throughput serving. See Section 5.11 deployment options.
75-
model = model.merge_and_unload()
76-
if args.save_merged:
77-
Path(args.save_merged).mkdir(parents=True, exist_ok=True)
78-
model.save_pretrained(args.save_merged)
79-
tokenizer.save_pretrained(args.save_merged)
80-
81-
model.eval()
82-
83-
messages = [
84-
{"role": "system", "content": args.system_prompt},
85-
{"role": "user", "content": args.prompt},
86-
]
87-
text = build_prompt_text(tokenizer, messages)
88-
inputs = tokenizer(text, return_tensors="pt", add_special_tokens=False).to(model.device)
89-
90-
with torch.no_grad():
91-
out = model.generate(
92-
**inputs,
93-
max_new_tokens=args.max_new_tokens,
94-
do_sample=args.do_sample,
95-
# Pass temperature=None when not sampling to avoid HF warnings
96-
# about unused generation parameters.
97-
temperature=args.temperature if args.do_sample else None,
98-
pad_token_id=tokenizer.pad_token_id,
99-
eos_token_id=tokenizer.eos_token_id,
100-
)
101-
102-
# skip_special_tokens=False to show the full chat template (system/user/assistant
103-
# markers). This is useful for debugging and demonstrating the template structure.
104-
decoded = tokenizer.decode(out[0], skip_special_tokens=False)
105-
print(decoded)
106-
107-
108-
if __name__ == "__main__":
109-
main()
110-
1+
"""Inference script: generate text with the base model and an optional LoRA/QLoRA adapter (Listing 5.4).
2+
3+
Loads the base model, optionally attaches a LoRA or QLoRA adapter, and generates
4+
a response for a single user prompt. Supports adapter merging for deployment.
5+
6+
Usage (base model only):
7+
python -m chapter05.generate --base Qwen/Qwen3-4B-Instruct-2507 \\
8+
--prompt "Explain how photosynthesis works in simple terms."
9+
10+
Usage (with LoRA adapter):
11+
python -m chapter05.generate --base Qwen/Qwen3-4B-Instruct-2507 \\
12+
--adapter chapter05/runs/dolly_lora \\
13+
--prompt "Explain how photosynthesis works in simple terms."
14+
15+
Usage (with QLoRA adapter -- must use --quantized_4bit):
16+
python -m chapter05.generate --base Qwen/Qwen3-4B-Instruct-2507 \\
17+
--adapter chapter05/runs/dolly_qlora --quantized_4bit \\
18+
--prompt "Explain how photosynthesis works in simple terms."
19+
20+
See Chapter 5, Section 5.1 (Step 4) and the README for full details.
21+
"""
22+
from __future__ import annotations
23+
24+
import argparse
25+
from pathlib import Path
26+
27+
import torch
28+
from peft import PeftModel
29+
from transformers import AutoModelForCausalLM
30+
31+
from chapter05 import DEFAULT_MODEL_NAME
32+
from chapter05.chat_template import DEFAULT_SYSTEM_PROMPT, build_prompt_text
33+
from chapter05.modeling import load_base_model_lora, load_base_model_qlora, load_tokenizer
34+
35+
36+
def parse_args() -> argparse.Namespace:
37+
"""Parse command-line arguments for inference.
38+
39+
Returns:
40+
Namespace with base model, adapter path, prompt, generation settings,
41+
and optional merge/quantization flags.
42+
"""
43+
ap = argparse.ArgumentParser()
44+
ap.add_argument("--base", default=DEFAULT_MODEL_NAME)
45+
ap.add_argument("--adapter", default=None, help="Path to LoRA/QLoRA adapter folder")
46+
ap.add_argument("--prompt", required=True, help="User prompt")
47+
ap.add_argument("--system_prompt", default=DEFAULT_SYSTEM_PROMPT)
48+
ap.add_argument("--max_new_tokens", type=int, default=128)
49+
ap.add_argument("--do_sample", action="store_true")
50+
ap.add_argument("--temperature", type=float, default=0.7)
51+
ap.add_argument("--quantized_4bit", action="store_true", help="Load base in 4-bit (requires bitsandbytes)")
52+
ap.add_argument("--merge_adapter", action="store_true", help="Merge adapter into base before generation")
53+
ap.add_argument("--save_merged", default=None, help="If set, save merged model to this folder")
54+
return ap.parse_args()
55+
56+
57+
def main() -> None:
58+
"""Load model, optionally attach adapter, and generate a response."""
59+
args = parse_args()
60+
tokenizer = load_tokenizer(args.base)
61+
62+
# Use --quantized_4bit when running a QLoRA-trained adapter so the base
63+
# model is loaded in 4-bit (matching the precision used during training).
64+
if args.quantized_4bit:
65+
model = load_base_model_qlora(args.base, gradient_checkpointing=False)
66+
else:
67+
model = load_base_model_lora(args.base, gradient_checkpointing=False)
68+
69+
if args.adapter:
70+
model = PeftModel.from_pretrained(model, args.adapter)
71+
if args.merge_adapter:
72+
# merge_and_unload() permanently folds LoRA weights into the base.
73+
# This loses modularity (can't swap adapters) but can be faster
74+
# for high-throughput serving. See Section 5.11 deployment options.
75+
model = model.merge_and_unload()
76+
if args.save_merged:
77+
Path(args.save_merged).mkdir(parents=True, exist_ok=True)
78+
model.save_pretrained(args.save_merged)
79+
tokenizer.save_pretrained(args.save_merged)
80+
81+
model.eval()
82+
83+
messages = [
84+
{"role": "system", "content": args.system_prompt},
85+
{"role": "user", "content": args.prompt},
86+
]
87+
text = build_prompt_text(tokenizer, messages)
88+
inputs = tokenizer(text, return_tensors="pt", add_special_tokens=False).to(model.device)
89+
90+
with torch.no_grad():
91+
out = model.generate(
92+
**inputs,
93+
max_new_tokens=args.max_new_tokens,
94+
do_sample=args.do_sample,
95+
# Pass temperature=None when not sampling to avoid HF warnings
96+
# about unused generation parameters.
97+
temperature=args.temperature if args.do_sample else None,
98+
pad_token_id=tokenizer.pad_token_id,
99+
eos_token_id=tokenizer.eos_token_id,
100+
)
101+
102+
# skip_special_tokens=False to show the full chat template (system/user/assistant
103+
# markers). This is useful for debugging and demonstrating the template structure.
104+
decoded = tokenizer.decode(out[0], skip_special_tokens=False)
105+
print(decoded)
106+
107+
108+
if __name__ == "__main__":
109+
main()
110+

0 commit comments

Comments
 (0)