Skip to content

Commit eabe47f

Browse files
committed
Initial commit for chapters 6 thru 9 for MEAP
1 parent 4d5f18d commit eabe47f

77 files changed

Lines changed: 8359 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎code/chapter06/README.md‎

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
# Chapter 6: Supervised Fine-Tuning (SFT): Maximum Expressiveness
2+
3+
This chapter demonstrates full-parameter SFT on **Qwen/Qwen3-4B-Instruct-2507** using the same Dolly dataset from Chapter 5. Where Chapter 5 trained a lightweight LoRA adapter (0.07% of parameters), this chapter updates every parameter in the model, enabling a direct comparison between the two approaches.
4+
5+
The running example throughout the chapter is an **IT technical support assistant** that answers questions about software installation, network troubleshooting, and system configuration. The dataset is built by filtering Dolly 15K for technical support categories and keywords, then formatting the results as chat-message JSONL.
6+
7+
## Assumptions
8+
9+
This README assumes you have already completed the one-time setup from [`code/README.md`](../README.md) (Python 3.10+, virtual environment, PyTorch with CUDA, `pip install -e ".[dev]"`). If not, start there first.
10+
11+
**GPU requirements:** Full SFT trains all ~4B parameters and needs significantly more memory than LoRA:
12+
13+
| GPU | VRAM | SFT feasibility |
14+
|-----|------|-----------------|
15+
| NVIDIA A100 (40/80 GB) | 40-80 GB | Comfortable; single GPU |
16+
| NVIDIA A30 / RTX 4090 (24 GB) | 24 GB | Works well with gradient checkpointing |
17+
| RTX 4070/4080 (12-16 GB) | 12-16 GB | Tight; may OOM. Use LoRA (Chapter 5) instead |
18+
19+
**Disk space:** The final saved model is ~7-10 GB (vs. 15-30 MB for a LoRA adapter). Intermediate epoch checkpoints, however, also store optimizer state and run ~22-24 GB each. With the default `save_total_limit=3` the run directory peaks at roughly 70-80 GB during training before the final model is written. **Plan for ~80 GB free** if you keep the default save policy; reduce `save_total_limit` if you need to cap disk usage.
20+
21+
## Code layout
22+
23+
| Location | Contents |
24+
|----------|----------|
25+
| `scripts/` | Runnable scripts (prepare dataset, monitor, behavioral tests, safety regression) |
26+
| `*.py` (this folder) | Python package modules (training, eval, inference). Run as `python -m chapter06.<module>` |
27+
| `data/` | Generated datasets (created by Step 1 below) |
28+
| `tests/` | Unit tests for eval utilities |
29+
30+
Shared utilities (JSONL, env, seed) live in `code/common/`. Evaluation metrics (`token_f1`, `exact_match`, `is_refusal`) are reused from `code/chapter05/metrics.py`.
31+
32+
## Listing map
33+
34+
| Listing | Description | File |
35+
|---------|-------------|------|
36+
| 6.1 | Data preparation (three-stage filter pipeline) | `scripts/prepare_sft_dataset.py` |
37+
| 6.2 | Full SFT training script | `train_sft.py` |
38+
| 6.3 | Inference with fine-tuned model | `generate.py` |
39+
| 6.4 | Training monitor (overfitting and gradient checks) | `scripts/monitor.py` |
40+
| 6.5 | Evaluation (base vs. fine-tuned, per-category Token-F1) | `eval_sft.py` |
41+
| 6.6 | Behavioral tests (safety, knowledge, format) | `scripts/behavioral_tests.py` |
42+
| 6.7 | OpenAI / Azure OpenAI fine-tuning API (platform comparison) | N/A (API example in chapter text) |
43+
| 6.8 | Google Vertex AI fine-tuning setup (platform comparison) | N/A (API example in chapter text) |
44+
| 6.9 | Safety regression suite (pre-deployment sign-off) | `scripts/safety_regression.py` |
45+
46+
## Step-by-step instructions
47+
48+
Run all commands from the `code/` directory with your virtual environment activated.
49+
50+
```bash
51+
cd /path/to/repo/code
52+
source .venv/bin/activate # Linux/macOS
53+
# Windows: .venv\Scripts\activate
54+
```
55+
56+
### Step 1: Prepare dataset (Listing 6.1)
57+
58+
Filters Dolly 15K down to technical support categories, applies keyword filtering, and converts to chat-message JSONL.
59+
60+
```bash
61+
python -m chapter06.scripts.prepare_sft_dataset \
62+
--out chapter06/data/dolly_sft
63+
```
64+
65+
Output: 450 training + 50 validation examples in `chapter06/data/dolly_sft/`.
66+
67+
### Step 2: Train full SFT model (Listing 6.2)
68+
69+
Run a 2-step smoke test first to catch OOM or config errors:
70+
71+
```bash
72+
python -m chapter06.train_sft \
73+
--train chapter06/data/dolly_sft/train.jsonl \
74+
--valid chapter06/data/dolly_sft/valid.jsonl \
75+
--out chapter06/runs/sft_smoke \
76+
--max_steps 2 --report_to none
77+
```
78+
79+
If the smoke test passes, clean up and run the full training:
80+
81+
```bash
82+
rm -rf chapter06/runs/sft_smoke
83+
84+
python -m chapter06.train_sft \
85+
--train chapter06/data/dolly_sft/train.jsonl \
86+
--valid chapter06/data/dolly_sft/valid.jsonl \
87+
--out chapter06/runs/sft_run1 \
88+
--report_to none
89+
```
90+
91+
Training time: ~10 min (2x A30), ~45-60 min (A100), ~90-120 min (RTX 4090).
92+
93+
### Step 3: Generate a response (Listing 6.3)
94+
95+
```bash
96+
python -m chapter06.generate \
97+
--model_dir chapter06/runs/sft_run1 \
98+
--prompt "How do I troubleshoot a VPN connection failure?"
99+
```
100+
101+
Unlike Chapter 5 (base model + adapter), this loads the complete fine-tuned model from a single directory.
102+
103+
### Step 4: Monitor training (Listing 6.4)
104+
105+
After a successful run, the trainer state file lives inside each checkpoint subdirectory, not in the top-level output directory. Point the monitor at the latest checkpoint:
106+
107+
```bash
108+
python -m chapter06.scripts.monitor chapter06/runs/sft_run1/checkpoint-87
109+
```
110+
111+
(Replace `checkpoint-87` with whichever step the final epoch landed on; `ls chapter06/runs/sft_run1/` lists the available checkpoints.)
112+
113+
Shows training loss trajectory, validation loss trend, and gradient norm warnings. If you point at the top-level run directory you will see "No trainer_state.json found" — that is the cue to descend into a `checkpoint-N/` subdirectory.
114+
115+
### Step 5: Evaluate base vs. fine-tuned (Listing 6.5)
116+
117+
```bash
118+
python -m chapter06.eval_sft \
119+
--data_dir chapter06/data/dolly_sft \
120+
--model_dir chapter06/runs/sft_run1 \
121+
--output chapter06/runs/sft_run1/eval_report.json
122+
```
123+
124+
Evaluates the base model, frees GPU memory, then evaluates the fine-tuned model. Prints a per-category comparison and saves a JSON report.
125+
126+
### Step 6: Behavioral tests (Listing 6.6)
127+
128+
```bash
129+
python -m chapter06.scripts.behavioral_tests \
130+
--model_dir chapter06/runs/sft_run1 \
131+
--also_test_base
132+
```
133+
134+
Checks safety refusal, knowledge retention, and format compliance. Exit code 0 = all passed; exit code 1 = failures detected.
135+
136+
### Step 7: Safety regression suite (Listing 6.9)
137+
138+
```bash
139+
python -m chapter06.scripts.safety_regression \
140+
--model_dir chapter06/runs/sft_run1 \
141+
--output_dir chapter06/eval/safety
142+
```
143+
144+
Compares base vs. fine-tuned across four safety dimensions. Flags any category where the fine-tuned model's pass rate drops more than 10 percentage points below the base model.
145+
146+
## Results summary
147+
148+
Representative numbers from an NVIDIA A30 run with `seed=42`. Full details in `runs/sft_run1/eval_report.json`. Your run will vary within ±0.02 on F1 across hardware and library versions; the *pattern* (summarization and closed_qa gain the most, open_qa moves least, safety is preserved) is the reliable signal.
149+
150+
### Evaluation (Token-F1 on 50 held-out examples)
151+
152+
| Category | Base Model | Fine-Tuned | Delta |
153+
|----------|-----------|------------|-------|
154+
| Closed QA | 0.314 | 0.57-0.64 | +0.26 to +0.32 |
155+
| Information extraction | 0.367 | 0.47-0.48 | +0.11 |
156+
| Open QA | 0.219 | 0.26-0.26 | +0.04 |
157+
| Summarization | 0.242 | 0.66-0.86 | +0.42 to +0.62 |
158+
| **Overall** | **0.257** | **0.36-0.37** | **+0.10 to +0.11** |
159+
160+
The Base column reproduces byte-for-byte; the SFT column moves within a 0.05-0.20 band depending on the random initialization of optimizer state and the transformers/peft version. Use these ranges as the "expect this magnitude" guide, not as fixed targets.
161+
162+
### Safety regression
163+
164+
The safety regression suite reports a per-category pass rate for base and fine-tuned, and flags any category that drops more than 10 percentage points. Across the four categories (harmful-request refusal, uncertainty acknowledgment, bias check, general knowledge), expect both base and fine-tuned to land in the **70-80%** pass rate on this Dolly technical-support subset, **with no regression** — full SFT on a narrow, on-topic training set tends to preserve safety alignment far better than LoRA on a broader Dolly subset (the chapter 5 LoRA pass shows -40 to -80 pp on a different safety prompt set; see chapter 5's README).
165+
166+
Absolute pass rates below 100% reflect the limits of keyword-based heuristics, not actual model failures. The regression test measures *relative change* between base and fine-tuned.
167+
168+
## Key differences from Chapter 5
169+
170+
| Aspect | Chapter 5 (LoRA) | Chapter 6 (Full SFT) |
171+
|--------|------------------|----------------------|
172+
| Trainable parameters | ~3.4M (0.07%) | ~4B (100%) |
173+
| Learning rate | 2e-4 | 2e-5 (10× lower) |
174+
| GPU memory (training) | 12-16 GB | 18-28 GB (with gradient checkpointing) |
175+
| Final-model size | 15-30 MB (adapter only) | 7-10 GB (full model) |
176+
| Intermediate checkpoint size | same as final | 22-24 GB each (model + optimizer + scheduler) |
177+
| PEFT config | Yes (LoRA rank 16) | None (all parameters trainable) |
178+
| Loading for inference | Base model + adapter | Single directory (complete model) |
179+
180+
## W&B experiment tracking (optional)
181+
182+
W&B is not required. To enable it:
183+
184+
```bash
185+
pip install wandb
186+
echo 'WANDB_API_KEY=your_key_here' >> .env
187+
188+
python -m chapter06.train_sft \
189+
--train chapter06/data/dolly_sft/train.jsonl \
190+
--valid chapter06/data/dolly_sft/valid.jsonl \
191+
--out chapter06/runs/sft_run1 \
192+
--report_to wandb
193+
```
194+
195+
To disable: `export WANDB_DISABLED=true`
196+
197+
## Running tests
198+
199+
```bash
200+
pytest chapter06/tests/ -v
201+
```
202+
203+
## Troubleshooting
204+
205+
**"CUDA out of memory"**: Full SFT requires 18-28 GB VRAM with gradient checkpointing. If your GPU has less than 24 GB, use LoRA from Chapter 5. The batch size is already 1; there is nothing further to reduce.
206+
207+
**"No module named 'chapter06'" or "No module named 'chapter05'"**: Run from the `code/` directory with the venv activated. Chapter 6 imports metrics from `chapter05.metrics`, so the full package must be installed.
208+
209+
**"trainer_state.json not found"**: The monitor script needs the path to a checkpoint directory (e.g., `chapter06/runs/sft_run1/checkpoint-87`), not the top-level output directory. Use a glob: `chapter06/runs/sft_run1/checkpoint-*`.
210+
211+
**High gradient norms (>5.0)**: Early spikes (6-8) are normal for full SFT on 4B models. What matters is the trajectory: norms should settle to the 2-5 range within the first epoch. If norms stay above 10 and training loss is increasing, reduce the learning rate with `--lr 1e-5`.
212+
213+
## Preparing for Chapter 8
214+
215+
The SFT checkpoint from this chapter is the starting point for DPO training in Chapter 8. Before moving on, verify your output directory contains: (1) the full model checkpoint (`.safetensors` shards), (2) tokenizer files, (3) `training_args.bin`, and (4) the eval report JSON from Step 5. These four artifacts are all Chapter 8 needs.

‎code/chapter06/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
DEFAULT_MODEL_NAME = "Qwen/Qwen3-4B-Instruct-2507"
2+
DEFAULT_SYSTEM_PROMPT = "You are an IT support assistant. Provide clear, step-by-step answers."
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"dataset": "databricks/databricks-dolly-15k",
3+
"created_utc": "2026-05-09T04:07:22.847960Z",
4+
"seed": 42,
5+
"filters": {
6+
"categories": [
7+
"closed_qa",
8+
"open_qa",
9+
"information_extraction",
10+
"summarization"
11+
],
12+
"min_length": 40,
13+
"max_length": 2000
14+
},
15+
"counts": {
16+
"train": 450,
17+
"valid": 50
18+
},
19+
"category_distribution": {
20+
"open_qa": 282,
21+
"summarization": 53,
22+
"closed_qa": 79,
23+
"information_extraction": 36
24+
},
25+
"system_prompt": "You are an IT support assistant. Provide clear, step-by-step answers."
26+
}

0 commit comments

Comments
 (0)