zziang commited on
Commit
f2ab218
·
verified ·
1 Parent(s): 73bb815

Upload kaggle/director_lora_train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. kaggle/director_lora_train.py +195 -0
kaggle/director_lora_train.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Director LoRA, conservative configuration.
2
+
3
+ Qwen3.5-0.8B is a hybrid model: 24 layers, 18 Gated DeltaNet `linear_attn`
4
+ blocks and 6 ordinary `self_attn` blocks (every fourth layer), plus a vision
5
+ tower and an MTP head. LoRA goes on the MLP of all 24 layers and the q/k/v/o
6
+ projections of the 6 full-attention layers. Nothing in `linear_attn` is
7
+ touched: its projections feed a recurrent scan, and its conv1d/A_log/dt_bias
8
+ parameters are not plain Linears.
9
+
10
+ Targets are discovered by name rather than by a short module-name list, so the
11
+ vision tower and the MTP head cannot be matched by accident.
12
+
13
+ Runs in a fresh interpreter with transformers 5.x (Ming's 4.46.3 cannot load
14
+ Qwen3.5). The browser never loads this adapter: merge_and_unload() writes a
15
+ plain fp16 checkpoint for the ONNX export step.
16
+ """
17
+ import json
18
+ import os
19
+ import random
20
+ import re
21
+ import time
22
+ from pathlib import Path
23
+
24
+ ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
25
+ BUNDLE = Path(os.environ.get("BUNDLE", str(ROOT / "webfm-eval")))
26
+ # Deliberately NOT director/sft.jsonl: that path holds the old six-line radio
27
+ # scripts, which use a different output protocol.
28
+ DATA = Path(os.environ.get("DATA", str(ROOT / "director_lora" / "sft.jsonl")))
29
+ OUT = Path(os.environ.get("LORA_OUT", str(ROOT / "director_lora")))
30
+ MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
31
+ R = int(os.environ.get("R", "16"))
32
+ ALPHA = int(os.environ.get("ALPHA", "32"))
33
+ DROPOUT = float(os.environ.get("DROPOUT", "0.05"))
34
+ LR = float(os.environ.get("LR", "1e-4"))
35
+ EPOCHS = int(os.environ.get("EPOCHS", "2"))
36
+ ACCUM = int(os.environ.get("ACCUM", "4"))
37
+ MAX_LEN = int(os.environ.get("MAX_LEN", "2048"))
38
+ SEED = int(os.environ.get("SEED", "20261107"))
39
+ GRAD_CKPT = os.environ.get("GRAD_CKPT", "0") == "1"
40
+
41
+ TARGET_RE = re.compile(
42
+ r"(^|\.)layers\.\d+\.("
43
+ r"mlp\.(gate_proj|up_proj|down_proj)"
44
+ r"|self_attn\.(q_proj|k_proj|v_proj|o_proj))$"
45
+ )
46
+ EXCLUDE = ("mtp", "vision", "visual", "multi_modal")
47
+
48
+
49
+ def log(msg: str) -> None:
50
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
51
+
52
+
53
+ def load_rows() -> list[dict]:
54
+ path = DATA if DATA.exists() else BUNDLE / "director_lora" / "sft.jsonl"
55
+ if not path.exists():
56
+ raise SystemExit(f"no training data at {DATA} or {path}")
57
+ rows = [json.loads(l) for l in path.read_text(encoding="utf-8").splitlines() if l.strip()]
58
+ log(f"{len(rows)} rows from {path}")
59
+ if not rows:
60
+ raise SystemExit("empty training set")
61
+ return rows
62
+
63
+
64
+ def encode(tok, row: dict):
65
+ import torch
66
+
67
+ messages = row["messages"]
68
+ if not messages or messages[-1]["role"] != "user":
69
+ raise SystemExit("bad messages field in training row")
70
+ prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
71
+ p_ids = tok(prompt, add_special_tokens=False)["input_ids"]
72
+ t_ids = tok(row["response"], add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
73
+ ids = (p_ids + t_ids)[:MAX_LEN]
74
+ labels = ([-100] * len(p_ids) + t_ids)[:MAX_LEN]
75
+ if all(v == -100 for v in labels):
76
+ return None
77
+ return {"input_ids": torch.tensor([ids]), "labels": torch.tensor([labels])}
78
+
79
+
80
+ def build_targets(model) -> list[str]:
81
+ import torch
82
+
83
+ names = [n for n, m in model.named_modules()
84
+ if isinstance(m, torch.nn.Linear)
85
+ and TARGET_RE.search(n)
86
+ and not any(x in n for x in EXCLUDE)]
87
+ mlp = sum(1 for n in names if ".mlp." in n)
88
+ attn = len(names) - mlp
89
+ log(f"targets: {len(names)} Linears ({mlp} MLP, {attn} self_attn)")
90
+ if mlp != 72 or attn != 24:
91
+ raise SystemExit(f"unexpected layer count ({mlp}/{attn}); check transformers version")
92
+ return names
93
+
94
+
95
+ def main() -> None:
96
+ import torch
97
+ from peft import LoraConfig, get_peft_model
98
+ from transformers import AutoModelForCausalLM, AutoTokenizer
99
+
100
+ import transformers
101
+ log(f"transformers {transformers.__version__}, torch {torch.__version__}")
102
+ if int(transformers.__version__.split(".")[0]) < 5:
103
+ raise SystemExit("Qwen3.5 needs transformers >= 5; run in a fresh process")
104
+
105
+ random.seed(SEED)
106
+ torch.manual_seed(SEED)
107
+ rows = load_rows()
108
+
109
+ tok = AutoTokenizer.from_pretrained(MODEL_ID)
110
+ if not getattr(tok, "chat_template", None):
111
+ raise SystemExit("tokenizer has no chat template; the browser applies one")
112
+ log(f"eos={tok.eos_token_id} ({tok.decode([tok.eos_token_id])!r})")
113
+
114
+ model = AutoModelForCausalLM.from_pretrained(
115
+ MODEL_ID, dtype=torch.bfloat16, device_map="cuda:0")
116
+ model.config.use_cache = False
117
+ if GRAD_CKPT:
118
+ model.gradient_checkpointing_enable()
119
+ model.enable_input_require_grads()
120
+
121
+ targets = build_targets(model)
122
+ cfg = LoraConfig(r=R, lora_alpha=ALPHA, lora_dropout=DROPOUT, bias="none",
123
+ task_type="CAUSAL_LM", target_modules=targets)
124
+ model = get_peft_model(model, cfg)
125
+ trainable = [p for p in model.parameters() if p.requires_grad]
126
+ n_train = sum(p.numel() for p in trainable)
127
+ n_all = sum(p.numel() for p in model.parameters())
128
+ log(f"trainable {n_train/1e6:.2f}M / {n_all/1e6:.0f}M ({n_train/n_all:.2%})")
129
+
130
+ encoded = [x for x in (encode(tok, row) for row in rows) if x is not None]
131
+ log(f"encoded {len(encoded)} examples, max {max(x['input_ids'].shape[1] for x in encoded)} tokens")
132
+ opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01)
133
+ model.train()
134
+ step, running, t0 = 0, 0.0, time.time()
135
+ for epoch in range(EPOCHS):
136
+ order = list(range(len(encoded)))
137
+ random.shuffle(order)
138
+ total = 0.0
139
+ for i, idx in enumerate(order):
140
+ batch = {k: v.cuda() for k, v in encoded[idx].items()}
141
+ loss = model(**batch).loss / ACCUM
142
+ loss.backward()
143
+ total += loss.item()
144
+ if (i + 1) % ACCUM == 0 or i + 1 == len(order):
145
+ torch.nn.utils.clip_grad_norm_(trainable, 1.0)
146
+ opt.step()
147
+ opt.zero_grad(set_to_none=True)
148
+ step += 1
149
+ running += loss.item() * ACCUM
150
+ if step % 25 == 0:
151
+ log(f"epoch {epoch} step {step} loss {running/25:.4f} ({time.time()-t0:.0f}s)")
152
+ running = 0.0
153
+ log(f"epoch {epoch} mean loss {total/max(1,len(order))*ACCUM:.4f}")
154
+ opt.zero_grad(set_to_none=True)
155
+
156
+ adapter = OUT / "adapter"
157
+ adapter.mkdir(parents=True, exist_ok=True)
158
+ model.save_pretrained(adapter)
159
+ tok.save_pretrained(adapter)
160
+ log(f"saved adapter -> {adapter}")
161
+
162
+ merged = OUT / "model_fp16"
163
+ merged.mkdir(parents=True, exist_ok=True)
164
+ model = model.merge_and_unload()
165
+ # The ONNX export strips the vision tower and the MTP head; only the text
166
+ # decoder is shipped to the browser.
167
+ if GRAD_CKPT:
168
+ model.gradient_checkpointing_disable()
169
+ model.config.use_cache = True
170
+ model.save_pretrained(merged, safe_serialization=True)
171
+ tok.save_pretrained(merged)
172
+ log(f"saved merged fp16 -> {merged}")
173
+
174
+ # Cheap sanity check: the merged model must still produce the protocol.
175
+ model.eval()
176
+ probe = rows[0]["messages"]
177
+ text = tok.apply_chat_template(probe, tokenize=False, add_generation_prompt=True)
178
+ ids = tok([text], return_tensors="pt").to("cuda")
179
+ with torch.no_grad():
180
+ gen = model.generate(**ids, max_new_tokens=160, do_sample=False,
181
+ eos_token_id=tok.eos_token_id,
182
+ pad_token_id=tok.eos_token_id)
183
+ out = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
184
+ log("merged model sample:\n" + out[:400])
185
+ (OUT / "sample.txt").write_text(out, encoding="utf-8")
186
+ (OUT / "train_meta.json").write_text(json.dumps({
187
+ "model": MODEL_ID, "rows": len(encoded), "epochs": EPOCHS, "lr": LR,
188
+ "r": R, "alpha": ALPHA, "targets": len(targets), "trainable": n_train,
189
+ "steps": step, "seconds": round(time.time() - t0),
190
+ }, indent=1), encoding="utf-8")
191
+ log("done")
192
+
193
+
194
+ if __name__ == "__main__":
195
+ main()