zziang commited on
Commit
3ef3c32
·
verified ·
1 Parent(s): 97e2893

director: six prefixed lines instead of JSON

Browse files
Files changed (1) hide show
  1. kaggle/director_sft.py +123 -0
kaggle/director_sft.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Teach the 0.8B director the output contract, then score it.
2
+
3
+ Zero-shot (and few-shot) the model gets the words right and the shape wrong:
4
+ three of six samples stop after one line, and it writes the array as a single
5
+ object with repeated keys. That is a formatting job, so it is worth a small
6
+ fine-tune rather than more prompt engineering.
7
+
8
+ Only the last few blocks and the head are trained. The base model already knows
9
+ how to write Chinese; what it lacks is six lines of 8-40 characters in a fixed
10
+ style order. Freezing the rest also keeps a 0.8B model training inside 15 GB.
11
+ """
12
+ import json
13
+ import os
14
+ import time
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
18
+ OUT = ROOT / "director"
19
+ MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
20
+ TRAIN_LAYERS = int(os.environ.get("TRAIN_LAYERS", "6"))
21
+ EPOCHS = int(os.environ.get("EPOCHS", "4"))
22
+ LR = float(os.environ.get("LR", "1e-4"))
23
+ ACCUM = int(os.environ.get("ACCUM", "4"))
24
+ MAX_LEN = int(os.environ.get("MAX_LEN", "1024"))
25
+
26
+
27
+ def log(msg: str) -> None:
28
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
29
+
30
+
31
+ def find_blocks(model):
32
+ """Longest ModuleList of decoder blocks, whatever it is nested under."""
33
+ import torch.nn as nn
34
+
35
+ best = (0, None)
36
+ for name, mod in model.named_modules():
37
+ if isinstance(mod, nn.ModuleList) and len(mod) > best[0]:
38
+ best = (len(mod), (name, mod))
39
+ return best[1]
40
+
41
+
42
+ def build_example(tok, topic: str, lines: list[dict]) -> dict:
43
+ import torch
44
+
45
+ from director_probe import SYSTEM, build_prompt
46
+
47
+ msgs = [{"role": "system", "content": SYSTEM},
48
+ {"role": "user", "content": build_prompt(topic)}]
49
+ prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
50
+ target = "\n".join(f"{l['style']}:{l['text']}" for l in lines)
51
+ p_ids = tok(prompt, add_special_tokens=False)["input_ids"]
52
+ t_ids = tok(target, add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
53
+ ids = (p_ids + t_ids)[:MAX_LEN]
54
+ labels = ([-100] * len(p_ids) + t_ids)[:MAX_LEN]
55
+ return {"input_ids": torch.tensor([ids]), "labels": torch.tensor([labels])}
56
+
57
+
58
+ def train(rows: list[dict]) -> str:
59
+ import torch
60
+ from transformers import AutoModelForCausalLM, AutoTokenizer
61
+
62
+ from director_probe import build_prompt # noqa: F401 (import check)
63
+
64
+ tok = AutoTokenizer.from_pretrained(MODEL_ID)
65
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.float32,
66
+ device_map="cuda:0")
67
+ n_layers, (lname, blocks) = find_blocks(model)
68
+ log(f"blocks: {lname} x{n_layers}; training the last {TRAIN_LAYERS}")
69
+
70
+ for p in model.parameters():
71
+ p.requires_grad_(False)
72
+ for blk in list(blocks)[-TRAIN_LAYERS:]:
73
+ for p in blk.parameters():
74
+ p.requires_grad_(True)
75
+ for name, p in model.named_parameters():
76
+ if name.endswith(("lm_head.weight", "norm.weight", "final_norm.weight")):
77
+ p.requires_grad_(True)
78
+ trainable = [p for p in model.parameters() if p.requires_grad]
79
+ n_train = sum(p.numel() for p in trainable)
80
+ log(f"trainable {n_train/1e6:.0f}M of {sum(p.numel() for p in model.parameters())/1e6:.0f}M")
81
+
82
+ opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01)
83
+ model.train()
84
+ step = 0
85
+ t0 = time.time()
86
+ for epoch in range(EPOCHS):
87
+ total = 0.0
88
+ for i, row in enumerate(rows):
89
+ ex = build_example(tok, row["topic"], row["lines"])
90
+ loss = model(**{k: v.cuda() for k, v in ex.items()}).loss / ACCUM
91
+ loss.backward()
92
+ total += loss.item()
93
+ if (i + 1) % ACCUM == 0:
94
+ torch.nn.utils.clip_grad_norm_(trainable, 1.0)
95
+ opt.step()
96
+ opt.zero_grad(set_to_none=True)
97
+ step += 1
98
+ if step % 10 == 0:
99
+ log(f"epoch {epoch} step {step} loss {total/(i+1)*ACCUM:.4f} "
100
+ f"({time.time()-t0:.0f}s)")
101
+ log(f"epoch {epoch} done, mean loss {total/max(1,len(rows))*ACCUM:.4f}")
102
+ opt.zero_grad(set_to_none=True)
103
+
104
+ out = OUT / "model"
105
+ out.mkdir(parents=True, exist_ok=True)
106
+ model.half().save_pretrained(out)
107
+ tok.save_pretrained(out)
108
+ log(f"saved {out} ({sum(f.stat().st_size for f in out.glob('*'))/1e6:.0f} MB)")
109
+ return str(out)
110
+
111
+
112
+ def main() -> None:
113
+ OUT.mkdir(parents=True, exist_ok=True)
114
+ path = OUT / "sft.jsonl"
115
+ rows = [json.loads(l) for l in path.read_text().splitlines() if l.strip()]
116
+ log(f"{len(rows)} training scripts from {path}")
117
+ if not rows:
118
+ raise SystemExit("no training data")
119
+ train(rows)
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()