logic65 commited on
Commit
d962cf1
·
verified ·
1 Parent(s): 59d874e

Upload moe/kd_moe_train_v4.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. moe/kd_moe_train_v4.py +348 -0
moe/kd_moe_train_v4.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Teach the 14.7B what the parent believes, not just what the answer was.
3
+
4
+ Note on the targets: the teacher pass ran the parent at nf4, because bf16
5
+ weights left too little of an 80GB card for the gated-delta-rule activations.
6
+ That perturbs the deep tail of the recorded distribution, which is why the
7
+ head is kept at top-128 rather than pushed further: past that point we would
8
+ be recording quantisation noise rather than the parent's beliefs.
9
+
10
+ Cross-entropy on hard labels gives one bit per token, and this corpus is spent:
11
+ the student already sits near 0.14 there. The parent's distribution says how much
12
+ probability belongs on every plausible continuation, which is the signal that decides
13
+ whether a model obeys "answer in one word" or wanders. That is the failure we measured.
14
+
15
+ Loss = KL(teacher || student) over the teacher's recorded top-k, plus a small
16
+ cross-entropy anchor so the argmax stays pinned to the real answer. Both are taken
17
+ on assistant turns only, and only where the turn's terminator was visible, so nothing
18
+ here teaches the model to run on.
19
+
20
+ python kd_student_train.py --teacher-logits teacher_top128.npz --minutes 180
21
+ """
22
+ import argparse, json, os, time
23
+
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--base", default="logic65/Qwen3.8-Whittle-tri-14.7B")
26
+ ap.add_argument("--subfolder", default="bf16")
27
+ ap.add_argument("--teacher-logits", required=True)
28
+ ap.add_argument("--data-repo", default="logic65/Qwen3.8-Whittle-dev")
29
+ ap.add_argument("--data-file", default="data/heal60_mix.jsonl")
30
+ ap.add_argument("--out", default="tri-kd-lora")
31
+ ap.add_argument("--seq", type=int, default=4096)
32
+ ap.add_argument("--tok-budget", type=int, default=8192)
33
+ ap.add_argument("--accum", type=int, default=4)
34
+ ap.add_argument("--lr", type=float, default=1e-4)
35
+ ap.add_argument("--kd-weight", type=float, default=0.9, help="rest goes to the CE anchor")
36
+ ap.add_argument("--temperature", type=float, default=1.0)
37
+ ap.add_argument("--use-topk", type=int, default=0, help="trim teacher head to this k")
38
+ ap.add_argument("--minutes", type=float, default=180.0)
39
+ ap.add_argument("--rank", type=int, default=32)
40
+ ap.add_argument("--binary-weight", type=float, default=0.5,
41
+ help="weight on the set-mass (binary) KL term")
42
+ ap.add_argument("--quant", default="bf16", choices=("bf16", "nf4"))
43
+ ap.add_argument("--push", default="")
44
+ A = ap.parse_args()
45
+
46
+ import numpy as np
47
+ import torch
48
+ import torch.nn.functional as F
49
+ from huggingface_hub import hf_hub_download, snapshot_download
50
+ from transformers import (AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,
51
+ Trainer, TrainingArguments, TrainerCallback)
52
+ from peft import LoraConfig, get_peft_model
53
+
54
+ t0 = time.time()
55
+ # accept a local checkpoint directory (the merged SFT model) as well as a hub repo
56
+ if os.path.isdir(A.base):
57
+ base = os.path.join(A.base, A.subfolder) if os.path.isdir(os.path.join(A.base, A.subfolder)) else A.base
58
+ else:
59
+ local = snapshot_download(A.base, allow_patterns=[f"{A.subfolder}/*", "*.json"])
60
+ base = os.path.join(local, A.subfolder)
61
+ mix = (A.data_file if os.path.exists(A.data_file)
62
+ else hf_hub_download(A.data_repo, A.data_file, repo_type="model"))
63
+ tok = AutoTokenizer.from_pretrained(base)
64
+ IM_START = tok.convert_tokens_to_ids("<|im_start|>")
65
+ IM_END = tok.convert_tokens_to_ids("<|im_end|>")
66
+ ASSIST = tok("assistant", add_special_tokens=False)["input_ids"]
67
+
68
+ Z = np.load(A.teacher_logits)
69
+ TOPK = int(Z["topk"][0])
70
+ USE_K = min(A.use_topk, TOPK) if A.use_topk else TOPK
71
+ row_ids, lengths = Z["row_ids"], Z["lengths"]
72
+ offs = np.concatenate([[0], np.cumsum(lengths)])
73
+ T_IDX, T_VAL = Z["idx"], Z["val"]
74
+ print(f"teacher targets: {len(row_ids)} rows, {lengths.sum()/1e6:.2f}M tokens, top-{TOPK}",
75
+ flush=True)
76
+
77
+ raw = [json.loads(l)["input_ids"][:A.seq] for l in open(mix)]
78
+ pos = {int(r): k for k, r in enumerate(row_ids)}
79
+
80
+
81
+ def mask_for(ids):
82
+ """Assistant turns only, and only those whose <|im_end|> is inside the window."""
83
+ lab = [-100]*len(ids)
84
+ if IM_START not in ids:
85
+ return list(ids)
86
+ i, n = 0, len(ids)
87
+ while i < n:
88
+ if ids[i] == IM_START and ids[i+1:i+1+len(ASSIST)] == ASSIST:
89
+ j = i + 1 + len(ASSIST)
90
+ while j < n and ids[j] != IM_END:
91
+ j += 1
92
+ if j < n and ids[j] == IM_END:
93
+ for k in range(i+1+len(ASSIST), j+1):
94
+ lab[k] = ids[k]
95
+ i = j
96
+ i += 1
97
+ return lab if any(v != -100 for v in lab) else list(ids)
98
+
99
+
100
+ data = []
101
+ for r_i, ids in enumerate(raw):
102
+ if r_i not in pos:
103
+ continue # teacher never reached this row
104
+ k = pos[r_i]
105
+ n = min(len(ids), int(lengths[k]))
106
+ data.append({"input_ids": ids[:n], "labels": mask_for(ids)[:n],
107
+ "t_idx": T_IDX[offs[k]:offs[k]+n, :USE_K],
108
+ "t_val": T_VAL[offs[k]:offs[k]+n, :USE_K]})
109
+ data.sort(key=lambda d: len(d["input_ids"]))
110
+ sup = sum(sum(1 for v in d["labels"] if v != -100) for d in data)
111
+ print(f"{len(data)} conversations | {sum(len(d['input_ids']) for d in data)/1e6:.2f}M tokens "
112
+ f"| {sup/1e6:.2f}M supervised", flush=True)
113
+
114
+ GROUPS, cur = [], []
115
+ for d in data:
116
+ L = len(d["input_ids"])
117
+ if cur and max(L, max(len(x["input_ids"]) for x in cur)) * (len(cur)+1) > A.tok_budget:
118
+ GROUPS.append(cur); cur = []
119
+ cur.append(d)
120
+ if cur:
121
+ GROUPS.append(cur)
122
+ print(f"{len(GROUPS)} batches, budget {A.tok_budget} tok", flush=True)
123
+
124
+
125
+ class Chats(torch.utils.data.Dataset):
126
+ def __len__(self):
127
+ return len(GROUPS)
128
+
129
+ def __getitem__(self, i):
130
+ return GROUPS[i]
131
+
132
+
133
+ PAD = tok.pad_token_id if tok.pad_token_id is not None else IM_END
134
+
135
+
136
+ def collate(batch):
137
+ b = batch[0] if (len(batch) == 1 and isinstance(batch[0], list)) else batch
138
+ m = max(len(x["input_ids"]) for x in b)
139
+ ids = torch.full((len(b), m), PAD, dtype=torch.long)
140
+ lab = torch.full((len(b), m), -100, dtype=torch.long)
141
+ att = torch.zeros((len(b), m), dtype=torch.long)
142
+ ti = torch.zeros((len(b), m, USE_K), dtype=torch.long)
143
+ tv = torch.full((len(b), m, USE_K), -1e4, dtype=torch.float)
144
+ for k, x in enumerate(b):
145
+ n = len(x["input_ids"])
146
+ ids[k, :n] = torch.tensor(x["input_ids"])
147
+ lab[k, :n] = torch.tensor(x["labels"])
148
+ att[k, :n] = 1
149
+ ti[k, :n] = torch.tensor(x["t_idx"].astype(np.int64))
150
+ tv[k, :n] = torch.tensor(x["t_val"].astype(np.float32))
151
+ return {"input_ids": ids, "labels": lab, "attention_mask": att,
152
+ "t_idx": ti, "t_val": tv}
153
+
154
+
155
+ kw = dict(dtype=torch.bfloat16, attn_implementation="sdpa", device_map={"": 0})
156
+ if A.quant == "nf4":
157
+ # Keep the routers OUT of nf4. They are the parameters this run exists to train,
158
+ # and a 4-bit tensor cannot carry gradients. Naming them in full matters: a bare
159
+ # "gate" would substring-match every expert's gate_proj and drag 12B of weights
160
+ # back into bf16. All 64 routers together are ~21M parameters.
161
+ import json as _json
162
+ _cfg = _json.load(open(os.path.join(base, "config.json")))
163
+ _nl = _cfg.get("num_hidden_layers") or _cfg["text_config"]["num_hidden_layers"]
164
+ _skip = ([f"model.layers.{i}.mlp.gate" for i in range(_nl)]
165
+ + [f"model.layers.{i}.mlp.shared_expert_gate" for i in range(_nl)]
166
+ + [f"model.layers.{i}.mlp.shared_expert"
167
+ for i in range(int(os.environ.get("SHARED_FROM", "40")), _nl)]
168
+ + ["lm_head"])
169
+ kw["quantization_config"] = BitsAndBytesConfig(
170
+ load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True,
171
+ bnb_4bit_compute_dtype=torch.bfloat16,
172
+ llm_int8_skip_modules=_skip)
173
+ model = AutoModelForCausalLM.from_pretrained(base, **kw)
174
+ model.gradient_checkpointing_enable()
175
+ model.enable_input_require_grads()
176
+ model.config.use_cache = False
177
+ # MoE targeting. The routed experts are exact slices of the parent FFN: the knowledge
178
+ # in them is already correct, so they are left frozen. What did NOT exist in the parent
179
+ # is the router — nothing yet knows which slice holds what, and misrouting is
180
+ # indistinguishable from knowledge loss at the output. So the routers are trained FULLY
181
+ # (all 64 gates together are only ~21M parameters; a rank-128 adapter on a 5120x64
182
+ # matrix would be a straitjacket, not a compression) while attention and the shared
183
+ # expert get LoRA to smooth the seams. Routers move WITH the experts' consumers, never
184
+ # alone: the routers-only run doubled Unknown facts precisely because gates drifted
185
+ # away from everything else.
186
+ #
187
+ # LoRA on the 12288 routed-expert projections was the alternative and it is a trap:
188
+ # each is only 5120x192, so r=128 adapters would add ~8.4B trainable parameters.
189
+ import re
190
+ TARGET_RE = re.compile(r"(linear_attn\.(in_proj_qkv|in_proj_z|in_proj_a|in_proj_b|out_proj)"
191
+ r"|self_attn\.(q_proj|k_proj|v_proj|o_proj)"
192
+ r")$") # shared experts train FULL this round, not LoRA
193
+ targets = sorted({n for n, _ in model.named_modules() if TARGET_RE.search(n)})
194
+ # All 64 shared experts full-rank is 5B trainable = 10GB weights + 10GB grads +
195
+ # 10GB optimiser states on top of the nf4 base: OOM at 79GB. The planner showed
196
+ # shared-expert activation mass is 80-90% in the DEEP layers and ~36% mid-stack,
197
+ # and stopping behaviour is late-layer, so train the deep half only (~1.9B).
198
+ SHARED_FROM = int(os.environ.get("SHARED_FROM", "40"))
199
+ import re as _re
200
+ def _deep_shared(n):
201
+ m = _re.search(r"layers\.(\d+)\.mlp\.shared_expert$", n)
202
+ return m is not None and int(m.group(1)) >= SHARED_FROM
203
+ gates = sorted({n for n, _ in model.named_modules()
204
+ if n.endswith("mlp.gate") or n.endswith("mlp.shared_expert_gate")
205
+ or _deep_shared(n)})
206
+ print(f"full-rank modules: {len(gates)} (routers + shared experts from L{SHARED_FROM})", flush=True)
207
+ assert targets and gates, (len(targets), len(gates))
208
+ assert not any(".experts." in t for t in targets), "routed experts must stay frozen"
209
+ print(f"LoRA on {len(targets)} modules | fully-trained gates: {len(gates)}", flush=True)
210
+ model = get_peft_model(model, LoraConfig(
211
+ r=A.rank, lora_alpha=2*A.rank, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
212
+ target_modules=targets,
213
+ modules_to_save=gates + ["input_layernorm", "post_attention_layernorm", "norm"]))
214
+ model.print_trainable_parameters()
215
+
216
+
217
+ class KD(Trainer):
218
+ """KL against the teacher's recorded top-k, with a CE anchor. Assistant tokens only."""
219
+ t0 = time.time()
220
+ seen = 0
221
+
222
+ def compute_loss(self, model, inputs, return_outputs=False, **kw):
223
+ t_idx = inputs.pop("t_idx")
224
+ t_val = inputs.pop("t_val")
225
+ labels = inputs.pop("labels")
226
+ KD.seen += int(inputs["input_ids"].numel())
227
+ out = model(**inputs)
228
+ logits = out.logits[:, :-1] # predict token t+1
229
+ tgt_i = t_idx[:, :-1]
230
+ tgt_v = t_val[:, :-1]
231
+ keep = labels[:, 1:] != -100 # supervise assistant turns only
232
+ if keep.any():
233
+ # only the teacher's top-k student log-probs are needed, so never build the
234
+ # full 248320-wide fp32 log_softmax: log_softmax(x)_i = x_i - logsumexp(x).
235
+ # The naive version costs ~8GB per batch to keep 128 numbers per token.
236
+ kept = logits[keep] # bf16 [N, V]
237
+ ti, tv, lb = tgt_i[keep], tgt_v[keep], labels[:, 1:][keep]
238
+
239
+ # At 8k positions the fp32 ops on [N, 248320] cost ~16GB stored for
240
+ # backward. Chunk over positions under torch.utils.checkpoint: fp32
241
+ # intermediates are recomputed per-chunk in backward, never stored.
242
+ import torch.utils.checkpoint as ckpt
243
+
244
+ def _loss_chunk(kc, tic, tvc, lbc):
245
+ lse = torch.logsumexp(kc.float(), dim=-1, keepdim=True)
246
+ s_top = torch.gather(kc, -1, tic).float() - lse
247
+ t_in = torch.logsumexp(tvc.float(), -1, keepdim=True).clamp(max=-1e-6)
248
+ s_in = torch.logsumexp(s_top, -1, keepdim=True).clamp(max=-1e-6)
249
+ t_out = torch.log1p(-torch.exp(t_in).clamp(max=1 - 1e-6))
250
+ s_out = torch.log1p(-torch.exp(s_in).clamp(max=1 - 1e-6))
251
+ kdb = (torch.exp(t_in)*(t_in-s_in) + torch.exp(t_out)*(t_out-s_out)).sum(-1).sum()
252
+ t_c = torch.softmax(tvc.float()/A.temperature, -1)
253
+ s_c = s_top/A.temperature
254
+ s_c = s_c - torch.logsumexp(s_c, -1, keepdim=True)
255
+ kdc = (t_c*(torch.log(t_c+1e-9)-s_c)).sum(-1).sum()
256
+ cec = F.cross_entropy(kc.float(), lbc, reduction="sum")
257
+ return kdc, kdb, cec
258
+
259
+ CH, N = 1024, kept.shape[0]
260
+ kdc_s = kdb_s = ce_s = 0.0
261
+ for c0 in range(0, N, CH):
262
+ kdc_c, kdb_c, ce_c = ckpt.checkpoint(
263
+ _loss_chunk, kept[c0:c0+CH], ti[c0:c0+CH], tv[c0:c0+CH],
264
+ lb[c0:c0+CH], use_reentrant=False)
265
+ kdc_s = kdc_s + kdc_c; kdb_s = kdb_s + kdb_c; ce_s = ce_s + ce_c
266
+ kd_cond, kd_bin, ce = kdc_s/N, kdb_s/N, ce_s/N
267
+ kd = kd_cond + A.binary_weight * kd_bin
268
+ else:
269
+ kd = ce = logits.sum() * 0.0
270
+ loss = A.kd_weight * kd + (1.0 - A.kd_weight) * ce
271
+ if self.state.global_step % 5 == 0:
272
+ self.log({"kd": float(kd), "kdb": float(kd_bin), "ce": float(ce)})
273
+ return (loss, out) if return_outputs else loss
274
+
275
+ def training_step(self, *a, **k):
276
+ if time.time() - self.t0 > A.minutes * 60:
277
+ self.control.should_training_stop = True
278
+ return super().training_step(*a, **k)
279
+
280
+
281
+ class DriveLog(TrainerCallback):
282
+ def __init__(self, path):
283
+ self.path = path
284
+ with open(path, "w") as f:
285
+ f.write("step,epoch,loss,kd,ce,lr\n")
286
+ self.last = {}
287
+
288
+ def on_log(self, args, state, control, logs=None, **kw):
289
+ if not logs:
290
+ return
291
+ self.last.update(logs)
292
+ if "loss" in logs:
293
+ with open(self.path, "a") as f:
294
+ f.write("%d,%.4f,%.5f,%.5f,%.5f,%.3e\n" % (
295
+ state.global_step, logs.get("epoch", 0), logs["loss"],
296
+ self.last.get("kd", 0), self.last.get("ce", 0),
297
+ logs.get("learning_rate", 0)))
298
+
299
+
300
+ import inspect
301
+ _want = dict(output_dir=A.out, per_device_train_batch_size=1,
302
+ gradient_accumulation_steps=A.accum, num_train_epochs=4,
303
+ learning_rate=A.lr, lr_scheduler_type="cosine", warmup_steps=20,
304
+ bf16=True, logging_steps=5, save_steps=25, save_total_limit=2,
305
+ save_strategy="steps", optim="adamw_torch", report_to="none",
306
+ gradient_checkpointing=True, dataloader_num_workers=2,
307
+ remove_unused_columns=False, label_names=["labels"])
308
+ _ok = set(inspect.signature(TrainingArguments.__init__).parameters)
309
+ _drop = [k for k in _want if k not in _ok]
310
+ if _drop:
311
+ print("dropping unsupported TrainingArguments:", _drop, flush=True)
312
+ args = TrainingArguments(**{k: v for k, v in _want.items() if k in _ok})
313
+
314
+ CSV = os.path.join(os.path.dirname(A.out) or ".",
315
+ "kd_loss_%s.csv" % os.path.basename(A.out.rstrip("/")))
316
+ trainer = KD(model=model, args=args, train_dataset=Chats(), data_collator=collate,
317
+ callbacks=[DriveLog(CSV)])
318
+ trainer.train()
319
+ el = time.time() - KD.t0
320
+ print(f"\ntrained {KD.seen/1e6:.2f}M tokens in {el/60:.1f} min ({KD.seen/el:.0f} tok/s)",
321
+ flush=True)
322
+
323
+ try:
324
+ import matplotlib
325
+ matplotlib.use("Agg")
326
+ import matplotlib.pyplot as plt
327
+ h = [x for x in trainer.state.log_history if "loss" in x]
328
+ if h:
329
+ fig, ax = plt.subplots(figsize=(9, 4.5))
330
+ ax.plot([x["step"] for x in h], [x["loss"] for x in h], lw=1.2, color="#3b6ea5")
331
+ ax.set_xlabel("step"); ax.set_ylabel("KD loss"); ax.grid(alpha=.25)
332
+ ax.set_title("Whittle 14.7B: logit distillation from the FP8 parent")
333
+ fig.tight_layout()
334
+ fig.savefig(os.path.join(os.path.dirname(A.out) or ".", "kd_loss_curve.png"), dpi=120)
335
+ print("curve saved | first %.3f last %.3f" % (h[0]["loss"], h[-1]["loss"]), flush=True)
336
+ except Exception as e:
337
+ print("plot skipped:", type(e).__name__, flush=True)
338
+
339
+ model.save_pretrained(A.out)
340
+ tok.save_pretrained(A.out)
341
+ if A.push:
342
+ from huggingface_hub import HfApi
343
+ api = HfApi()
344
+ api.create_repo(A.push, repo_type="model", private=False, exist_ok=True)
345
+ api.upload_folder(folder_path=A.out, repo_id=A.push,
346
+ ignore_patterns=["checkpoint-*", "*.log"])
347
+ print("pushed ->", A.push, flush=True)
348
+ print(f"total {(time.time()-t0)/60:.1f} min", flush=True)