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

Upload moe/kd_moe_train_v3.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. moe/kd_moe_train_v3.py +337 -0
moe/kd_moe_train_v3.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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" for i in range(_nl)]
167
+ + ["lm_head"])
168
+ kw["quantization_config"] = BitsAndBytesConfig(
169
+ load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True,
170
+ bnb_4bit_compute_dtype=torch.bfloat16,
171
+ llm_int8_skip_modules=_skip)
172
+ model = AutoModelForCausalLM.from_pretrained(base, **kw)
173
+ model.gradient_checkpointing_enable()
174
+ model.enable_input_require_grads()
175
+ model.config.use_cache = False
176
+ # MoE targeting. The routed experts are exact slices of the parent FFN: the knowledge
177
+ # in them is already correct, so they are left frozen. What did NOT exist in the parent
178
+ # is the router — nothing yet knows which slice holds what, and misrouting is
179
+ # indistinguishable from knowledge loss at the output. So the routers are trained FULLY
180
+ # (all 64 gates together are only ~21M parameters; a rank-128 adapter on a 5120x64
181
+ # matrix would be a straitjacket, not a compression) while attention and the shared
182
+ # expert get LoRA to smooth the seams. Routers move WITH the experts' consumers, never
183
+ # alone: the routers-only run doubled Unknown facts precisely because gates drifted
184
+ # away from everything else.
185
+ #
186
+ # LoRA on the 12288 routed-expert projections was the alternative and it is a trap:
187
+ # each is only 5120x192, so r=128 adapters would add ~8.4B trainable parameters.
188
+ import re
189
+ TARGET_RE = re.compile(r"(linear_attn\.(in_proj_qkv|in_proj_z|in_proj_a|in_proj_b|out_proj)"
190
+ r"|self_attn\.(q_proj|k_proj|v_proj|o_proj)"
191
+ r")$") # shared experts train FULL this round, not LoRA
192
+ targets = sorted({n for n, _ in model.named_modules() if TARGET_RE.search(n)})
193
+ gates = sorted({n for n, _ in model.named_modules()
194
+ if n.endswith("mlp.gate") or n.endswith("mlp.shared_expert_gate")
195
+ or n.endswith("mlp.shared_expert")}) # whole shared expert, full rank
196
+ assert targets and gates, (len(targets), len(gates))
197
+ assert not any(".experts." in t for t in targets), "routed experts must stay frozen"
198
+ print(f"LoRA on {len(targets)} modules | fully-trained gates: {len(gates)}", flush=True)
199
+ model = get_peft_model(model, LoraConfig(
200
+ r=A.rank, lora_alpha=2*A.rank, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
201
+ target_modules=targets,
202
+ modules_to_save=gates + ["input_layernorm", "post_attention_layernorm", "norm"]))
203
+ model.print_trainable_parameters()
204
+
205
+
206
+ class KD(Trainer):
207
+ """KL against the teacher's recorded top-k, with a CE anchor. Assistant tokens only."""
208
+ t0 = time.time()
209
+ seen = 0
210
+
211
+ def compute_loss(self, model, inputs, return_outputs=False, **kw):
212
+ t_idx = inputs.pop("t_idx")
213
+ t_val = inputs.pop("t_val")
214
+ labels = inputs.pop("labels")
215
+ KD.seen += int(inputs["input_ids"].numel())
216
+ out = model(**inputs)
217
+ logits = out.logits[:, :-1] # predict token t+1
218
+ tgt_i = t_idx[:, :-1]
219
+ tgt_v = t_val[:, :-1]
220
+ keep = labels[:, 1:] != -100 # supervise assistant turns only
221
+ if keep.any():
222
+ # only the teacher's top-k student log-probs are needed, so never build the
223
+ # full 248320-wide fp32 log_softmax: log_softmax(x)_i = x_i - logsumexp(x).
224
+ # The naive version costs ~8GB per batch to keep 128 numbers per token.
225
+ kept = logits[keep] # bf16 [N, V]
226
+ ti, tv, lb = tgt_i[keep], tgt_v[keep], labels[:, 1:][keep]
227
+
228
+ # At 8k positions the fp32 ops on [N, 248320] cost ~16GB stored for
229
+ # backward. Chunk over positions under torch.utils.checkpoint: fp32
230
+ # intermediates are recomputed per-chunk in backward, never stored.
231
+ import torch.utils.checkpoint as ckpt
232
+
233
+ def _loss_chunk(kc, tic, tvc, lbc):
234
+ lse = torch.logsumexp(kc.float(), dim=-1, keepdim=True)
235
+ s_top = torch.gather(kc, -1, tic).float() - lse
236
+ t_in = torch.logsumexp(tvc.float(), -1, keepdim=True).clamp(max=-1e-6)
237
+ s_in = torch.logsumexp(s_top, -1, keepdim=True).clamp(max=-1e-6)
238
+ t_out = torch.log1p(-torch.exp(t_in).clamp(max=1 - 1e-6))
239
+ s_out = torch.log1p(-torch.exp(s_in).clamp(max=1 - 1e-6))
240
+ kdb = (torch.exp(t_in)*(t_in-s_in) + torch.exp(t_out)*(t_out-s_out)).sum(-1).sum()
241
+ t_c = torch.softmax(tvc.float()/A.temperature, -1)
242
+ s_c = s_top/A.temperature
243
+ s_c = s_c - torch.logsumexp(s_c, -1, keepdim=True)
244
+ kdc = (t_c*(torch.log(t_c+1e-9)-s_c)).sum(-1).sum()
245
+ cec = F.cross_entropy(kc.float(), lbc, reduction="sum")
246
+ return kdc, kdb, cec
247
+
248
+ CH, N = 1024, kept.shape[0]
249
+ kdc_s = kdb_s = ce_s = 0.0
250
+ for c0 in range(0, N, CH):
251
+ kdc_c, kdb_c, ce_c = ckpt.checkpoint(
252
+ _loss_chunk, kept[c0:c0+CH], ti[c0:c0+CH], tv[c0:c0+CH],
253
+ lb[c0:c0+CH], use_reentrant=False)
254
+ kdc_s = kdc_s + kdc_c; kdb_s = kdb_s + kdb_c; ce_s = ce_s + ce_c
255
+ kd_cond, kd_bin, ce = kdc_s/N, kdb_s/N, ce_s/N
256
+ kd = kd_cond + A.binary_weight * kd_bin
257
+ else:
258
+ kd = ce = logits.sum() * 0.0
259
+ loss = A.kd_weight * kd + (1.0 - A.kd_weight) * ce
260
+ if self.state.global_step % 5 == 0:
261
+ self.log({"kd": float(kd), "kdb": float(kd_bin), "ce": float(ce)})
262
+ return (loss, out) if return_outputs else loss
263
+
264
+ def training_step(self, *a, **k):
265
+ if time.time() - self.t0 > A.minutes * 60:
266
+ self.control.should_training_stop = True
267
+ return super().training_step(*a, **k)
268
+
269
+
270
+ class DriveLog(TrainerCallback):
271
+ def __init__(self, path):
272
+ self.path = path
273
+ with open(path, "w") as f:
274
+ f.write("step,epoch,loss,kd,ce,lr\n")
275
+ self.last = {}
276
+
277
+ def on_log(self, args, state, control, logs=None, **kw):
278
+ if not logs:
279
+ return
280
+ self.last.update(logs)
281
+ if "loss" in logs:
282
+ with open(self.path, "a") as f:
283
+ f.write("%d,%.4f,%.5f,%.5f,%.5f,%.3e\n" % (
284
+ state.global_step, logs.get("epoch", 0), logs["loss"],
285
+ self.last.get("kd", 0), self.last.get("ce", 0),
286
+ logs.get("learning_rate", 0)))
287
+
288
+
289
+ import inspect
290
+ _want = dict(output_dir=A.out, per_device_train_batch_size=1,
291
+ gradient_accumulation_steps=A.accum, num_train_epochs=4,
292
+ learning_rate=A.lr, lr_scheduler_type="cosine", warmup_steps=20,
293
+ bf16=True, logging_steps=5, save_steps=25, save_total_limit=2,
294
+ save_strategy="steps", optim="adamw_torch", report_to="none",
295
+ gradient_checkpointing=True, dataloader_num_workers=2,
296
+ remove_unused_columns=False, label_names=["labels"])
297
+ _ok = set(inspect.signature(TrainingArguments.__init__).parameters)
298
+ _drop = [k for k in _want if k not in _ok]
299
+ if _drop:
300
+ print("dropping unsupported TrainingArguments:", _drop, flush=True)
301
+ args = TrainingArguments(**{k: v for k, v in _want.items() if k in _ok})
302
+
303
+ CSV = os.path.join(os.path.dirname(A.out) or ".",
304
+ "kd_loss_%s.csv" % os.path.basename(A.out.rstrip("/")))
305
+ trainer = KD(model=model, args=args, train_dataset=Chats(), data_collator=collate,
306
+ callbacks=[DriveLog(CSV)])
307
+ trainer.train()
308
+ el = time.time() - KD.t0
309
+ print(f"\ntrained {KD.seen/1e6:.2f}M tokens in {el/60:.1f} min ({KD.seen/el:.0f} tok/s)",
310
+ flush=True)
311
+
312
+ try:
313
+ import matplotlib
314
+ matplotlib.use("Agg")
315
+ import matplotlib.pyplot as plt
316
+ h = [x for x in trainer.state.log_history if "loss" in x]
317
+ if h:
318
+ fig, ax = plt.subplots(figsize=(9, 4.5))
319
+ ax.plot([x["step"] for x in h], [x["loss"] for x in h], lw=1.2, color="#3b6ea5")
320
+ ax.set_xlabel("step"); ax.set_ylabel("KD loss"); ax.grid(alpha=.25)
321
+ ax.set_title("Whittle 14.7B: logit distillation from the FP8 parent")
322
+ fig.tight_layout()
323
+ fig.savefig(os.path.join(os.path.dirname(A.out) or ".", "kd_loss_curve.png"), dpi=120)
324
+ print("curve saved | first %.3f last %.3f" % (h[0]["loss"], h[-1]["loss"]), flush=True)
325
+ except Exception as e:
326
+ print("plot skipped:", type(e).__name__, flush=True)
327
+
328
+ model.save_pretrained(A.out)
329
+ tok.save_pretrained(A.out)
330
+ if A.push:
331
+ from huggingface_hub import HfApi
332
+ api = HfApi()
333
+ api.create_repo(A.push, repo_type="model", private=False, exist_ok=True)
334
+ api.upload_folder(folder_path=A.out, repo_id=A.push,
335
+ ignore_patterns=["checkpoint-*", "*.log"])
336
+ print("pushed ->", A.push, flush=True)
337
+ print(f"total {(time.time()-t0)/60:.1f} min", flush=True)