snwy commited on
Commit
aee6a1a
·
verified ·
1 Parent(s): ecc0b2d

repro code

Browse files
Files changed (8) hide show
  1. activation_stats.py +398 -0
  2. finetune_qwen.py +1267 -0
  3. layer_influence.py +375 -0
  4. layer_surgery.py +279 -0
  5. moe_to_dense.py +1097 -0
  6. sample.txt +65 -0
  7. scales.json +8 -0
  8. visualize_activations.py +467 -0
activation_stats.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # fmt: off
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ from dataclasses import dataclass, asdict
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ import torch
12
+ from transformers import AutoModelForCausalLM, AutoTokenizer
13
+
14
+
15
+ @dataclass
16
+ class RunningStat:
17
+ count: int = 0
18
+ sum: float = 0.0
19
+ sumsq: float = 0.0
20
+ min: Optional[float] = None
21
+ max: Optional[float] = None
22
+ zero_count: int = 0
23
+ nan_count: int = 0
24
+ inf_count: int = 0
25
+
26
+ def update_from_tensor(self, t: torch.Tensor):
27
+ with torch.no_grad():
28
+ nan_mask = torch.isnan(t)
29
+ inf_mask = torch.isinf(t)
30
+ self.nan_count += int(nan_mask.sum().item())
31
+ self.inf_count += int(inf_mask.sum().item())
32
+ t = torch.nan_to_num(t, nan=0.0, posinf=0.0, neginf=0.0)
33
+
34
+ self.zero_count += int((t == 0).sum().item())
35
+
36
+ tf = t.float()
37
+ self.sum += float(tf.sum().item())
38
+ self.sumsq += float((tf * tf).sum().item())
39
+ self.count += t.numel()
40
+
41
+ t_min = float(t.min().item())
42
+ t_max = float(t.max().item())
43
+ if self.min is None or t_min < self.min:
44
+ self.min = t_min
45
+ if self.max is None or t_max > self.max:
46
+ self.max = t_max
47
+
48
+ @property
49
+ def mean(self) -> Optional[float]:
50
+ if self.count == 0:
51
+ return None
52
+ return self.sum / self.count
53
+
54
+ @property
55
+ def var(self) -> Optional[float]:
56
+ if self.count == 0:
57
+ return None
58
+ m = self.mean
59
+ return max(0.0, self.sumsq / self.count - (m * m))
60
+
61
+ @property
62
+ def std(self) -> Optional[float]:
63
+ v = self.var
64
+ if v is None:
65
+ return None
66
+ return math.sqrt(v)
67
+
68
+ def to_dict(self) -> Dict[str, Any]:
69
+ d = asdict(self)
70
+ d["mean"] = self.mean
71
+ d["std"] = self.std
72
+ return d
73
+
74
+
75
+ @dataclass
76
+ class TokenRMSStat:
77
+ count: int = 0
78
+ sum: float = 0.0
79
+ sumsq: float = 0.0
80
+
81
+ def update_from_tensor(self, t: torch.Tensor):
82
+ with torch.no_grad():
83
+ if t.ndim == 1:
84
+ feats = t.unsqueeze(0)
85
+ else:
86
+ feats = t.view(-1, t.shape[-1])
87
+ rms = feats.float().pow(2).mean(dim=-1).sqrt()
88
+ rms = torch.nan_to_num(rms, nan=0.0, posinf=0.0, neginf=0.0)
89
+ self.count += int(rms.numel())
90
+ self.sum += float(rms.sum().item())
91
+ self.sumsq += float((rms * rms).sum().item())
92
+
93
+ @property
94
+ def mean(self) -> Optional[float]:
95
+ if self.count == 0:
96
+ return None
97
+ return self.sum / self.count
98
+
99
+ @property
100
+ def var(self) -> Optional[float]:
101
+ if self.count == 0:
102
+ return None
103
+ m = self.mean
104
+ return max(0.0, self.sumsq / self.count - (m * m))
105
+
106
+ @property
107
+ def std(self) -> Optional[float]:
108
+ v = self.var
109
+ if v is None:
110
+ return None
111
+ return math.sqrt(v)
112
+
113
+ def to_dict(self) -> Dict[str, Any]:
114
+ return {
115
+ "count": self.count,
116
+ "mean": self.mean,
117
+ "std": self.std,
118
+ }
119
+
120
+
121
+ class ActivationMonitor:
122
+ def __init__(self, use_tensorboard: bool = False, tb_dir: Optional[str] = None):
123
+ self.stats: Dict[str, RunningStat] = {}
124
+ self.token_rms: Dict[str, TokenRMSStat] = {}
125
+ self.use_tensorboard = use_tensorboard
126
+ self.tb = None
127
+ self._global_step = 0
128
+ if self.use_tensorboard and tb_dir is not None:
129
+ try:
130
+ from torch.utils.tensorboard import SummaryWriter
131
+
132
+ self.tb = SummaryWriter(log_dir=tb_dir)
133
+ except Exception as e:
134
+ print(f"TensorBoard not available: {e}")
135
+
136
+ def _get_stat(self, name: str) -> RunningStat:
137
+ if name not in self.stats:
138
+ self.stats[name] = RunningStat()
139
+ return self.stats[name]
140
+
141
+ def _get_token_rms(self, name: str) -> TokenRMSStat:
142
+ if name not in self.token_rms:
143
+ self.token_rms[name] = TokenRMSStat()
144
+ return self.token_rms[name]
145
+
146
+ def hook(self, name: str):
147
+ def _hook(module, inputs, output):
148
+ with torch.no_grad():
149
+ t = output
150
+ if isinstance(t, tuple):
151
+ t = t[0]
152
+ if not isinstance(t, torch.Tensor):
153
+ return
154
+ self._get_stat(name).update_from_tensor(t)
155
+ self._get_token_rms(name).update_from_tensor(t)
156
+
157
+ if self.tb is not None and (self._global_step % 10 == 0):
158
+ rs = self.stats[name]
159
+ tr = self.token_rms[name]
160
+ if rs.count > 0:
161
+ self.tb.add_scalar(
162
+ f"{name}/mean", rs.mean, self._global_step
163
+ )
164
+ if rs.std is not None:
165
+ self.tb.add_scalar(
166
+ f"{name}/std", rs.std, self._global_step
167
+ )
168
+ self.tb.add_scalar(
169
+ f"{name}/zero_frac",
170
+ rs.zero_count / max(1, rs.count),
171
+ self._global_step,
172
+ )
173
+ if tr.count > 0 and tr.mean is not None:
174
+ self.tb.add_scalar(
175
+ f"{name}/token_rms_mean",
176
+ tr.mean,
177
+ self._global_step,
178
+ )
179
+ return
180
+
181
+ return _hook
182
+
183
+ def step(self):
184
+ self._global_step += 1
185
+
186
+ def close(self):
187
+ if self.tb is not None:
188
+ self.tb.flush()
189
+ self.tb.close()
190
+
191
+ def to_dict(self) -> Dict[str, Any]:
192
+ out: Dict[str, Any] = {}
193
+ for k in sorted(self.stats.keys()):
194
+ out[k] = {
195
+ "global": self.stats[k].to_dict(),
196
+ "token_rms": self.token_rms[k].to_dict(),
197
+ }
198
+ return out
199
+
200
+
201
+ def find_modules_to_hook(
202
+ model: torch.nn.Module, patterns: List[str]
203
+ ) -> List[str]:
204
+ names: List[str] = []
205
+ for name, _ in model.named_modules():
206
+ lname = name.lower()
207
+ if not lname.startswith("model.layers."):
208
+ continue
209
+ for p in patterns:
210
+ if p in lname:
211
+ names.append(name)
212
+ break
213
+ return sorted(list(set(names)))
214
+
215
+
216
+ def compute_attention_entropy(
217
+ model: AutoModelForCausalLM,
218
+ tok: AutoTokenizer,
219
+ prompts: List[str],
220
+ max_length: int,
221
+ input_device: torch.device,
222
+ ) -> Dict[int, float]:
223
+ prev = getattr(model.config, "output_attentions", False)
224
+ model.config.output_attentions = True
225
+
226
+ with torch.inference_mode():
227
+ enc = tok(
228
+ prompts,
229
+ return_tensors="pt",
230
+ padding=True,
231
+ truncation=True,
232
+ max_length=max_length,
233
+ )
234
+ for k in enc:
235
+ enc[k] = enc[k].to(input_device)
236
+ out = model(**enc, output_attentions=True, use_cache=False)
237
+ atts = out.attentions
238
+ entropies: Dict[int, float] = {}
239
+ for i, att in enumerate(atts):
240
+ probs = att.float().clamp_min(1e-12)
241
+ ent = -(probs * probs.log()).sum(dim=-1)
242
+ ent_mean = float(ent.mean().item())
243
+ entropies[i] = ent_mean
244
+
245
+ model.config.output_attentions = prev
246
+ return entropies
247
+
248
+
249
+ def load_prompts(
250
+ prompts: Optional[str], prompts_file: Optional[str]
251
+ ) -> List[str]:
252
+ lines: List[str] = []
253
+ if prompts_file:
254
+ with open(prompts_file, "r", encoding="utf-8") as f:
255
+ for line in f:
256
+ s = line.strip("\n")
257
+ if s:
258
+ lines.append(s)
259
+ if prompts:
260
+ for s in prompts.split("\n"):
261
+ s = s.strip()
262
+ if s:
263
+ lines.append(s)
264
+ if not lines:
265
+ lines = [
266
+ "Hello! Briefly introduce yourself.",
267
+ "Explain the concept of attention in transformers.",
268
+ "List three use cases for large language models.",
269
+ ]
270
+ return lines
271
+
272
+
273
+ def main():
274
+ ap = argparse.ArgumentParser(
275
+ description="Activation statistics monitor for HF CausalLM models."
276
+ )
277
+ ap.add_argument("--model", type=str, required=True, help="Model path or HF ID.")
278
+ ap.add_argument("--prompts", type=str)
279
+ ap.add_argument("--prompts_file", type=str)
280
+ ap.add_argument("--max_length", type=int, default=256)
281
+ ap.add_argument("--batch_size", type=int, default=4)
282
+ ap.add_argument(
283
+ "--dtype",
284
+ type=str,
285
+ default="bfloat16",
286
+ choices=["bfloat16", "float16", "float32"],
287
+ )
288
+ ap.add_argument("--device_map", type=str, default="auto")
289
+ ap.add_argument(
290
+ "--patterns",
291
+ type=str,
292
+ default=(
293
+ "q_proj,k_proj,v_proj,o_proj,mlp.up_proj,mlp.gate_proj,"
294
+ "mlp.down_proj,layernorm,norm"
295
+ ),
296
+ )
297
+ ap.add_argument("--save_json", type=str)
298
+ ap.add_argument("--tensorboard_dir", type=str)
299
+ ap.add_argument("--attention_entropy", action="store_true")
300
+ args = ap.parse_args()
301
+
302
+ dtype_map = {
303
+ "bfloat16": torch.bfloat16,
304
+ "float16": torch.float16,
305
+ "float32": torch.float32,
306
+ }
307
+ torch_dtype = dtype_map[args.dtype]
308
+
309
+ print(f"Loading tokenizer/model: {args.model}")
310
+ tok = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
311
+ model = AutoModelForCausalLM.from_pretrained(
312
+ args.model,
313
+ torch_dtype=torch_dtype,
314
+ trust_remote_code=True,
315
+ device_map=args.device_map,
316
+ )
317
+ model.eval()
318
+
319
+ embed_device = model.get_input_embeddings().weight.device
320
+ print(f"Sending inputs to: {embed_device}")
321
+
322
+ patterns = [p.strip().lower() for p in args.patterns.split(",") if p.strip()]
323
+ to_hook = find_modules_to_hook(model, patterns)
324
+
325
+ mon = ActivationMonitor(
326
+ use_tensorboard=args.tensorboard_dir is not None,
327
+ tb_dir=args.tensorboard_dir,
328
+ )
329
+ handles = []
330
+ for name, module in model.named_modules():
331
+ if name in to_hook:
332
+ handles.append(module.register_forward_hook(mon.hook(name)))
333
+ print(f"Registered hooks on {len(handles)} modules.")
334
+
335
+ prompts = load_prompts(args.prompts, args.prompts_file)
336
+
337
+ with torch.inference_mode():
338
+ i = 0
339
+ while i < len(prompts):
340
+ batch_prompts = prompts[i : i + args.batch_size]
341
+ i += args.batch_size
342
+ enc = tok(
343
+ batch_prompts,
344
+ return_tensors="pt",
345
+ padding=True,
346
+ truncation=True,
347
+ max_length=args.max_length,
348
+ )
349
+ for k in enc:
350
+ enc[k] = enc[k].to(embed_device)
351
+ _ = model(**enc, use_cache=False)
352
+ mon.step()
353
+
354
+ attn_entropy: Dict[int, float] = {}
355
+ if args.attention_entropy:
356
+ subset = prompts[: min(len(prompts), args.batch_size)]
357
+ attn_entropy = compute_attention_entropy(
358
+ model, tok, subset, args.max_length, embed_device
359
+ )
360
+
361
+ for h in handles:
362
+ h.remove()
363
+ mon.close()
364
+
365
+ stats = mon.to_dict()
366
+ if args.attention_entropy:
367
+ stats["_attention_entropy"] = attn_entropy
368
+
369
+ print("\nActivation summary (top 10 by token_rms mean):")
370
+ ranked = sorted(
371
+ [
372
+ (name, d["token_rms"]["mean"] or 0.0)
373
+ for name, d in stats.items()
374
+ if name != "_attention_entropy"
375
+ ],
376
+ key=lambda x: x[1],
377
+ reverse=True,
378
+ )[:10]
379
+ for name, rms_mean in ranked:
380
+ g = stats[name]["global"]
381
+ zero_frac = g.get("zero_count", 0) / max(1, g.get("count", 1))
382
+ print(
383
+ f"- {name}: token_rms_mean={rms_mean:.4f}, "
384
+ f"mean={g.get('mean'):.4f} std={g.get('std'):.4f} "
385
+ f"min={g.get('min'):.4f} max={g.get('max'):.4f} "
386
+ f"zero_frac={zero_frac:.4f}"
387
+ )
388
+
389
+ if args.save_json:
390
+ out_path = Path(args.save_json)
391
+ out_path.parent.mkdir(parents=True, exist_ok=True)
392
+ with open(out_path, "w") as f:
393
+ json.dump(stats, f, indent=2)
394
+ print(f"\nSaved stats JSON to: {out_path}")
395
+
396
+
397
+ if __name__ == "__main__":
398
+ main()
finetune_qwen.py ADDED
@@ -0,0 +1,1267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from datasets import load_from_disk, concatenate_datasets, Dataset
4
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, TrainingArguments, BitsAndBytesConfig
5
+ from peft import LoraConfig, prepare_model_for_kbit_training, PeftModel
6
+ from peft.tuners.lora import LoraLayer
7
+ from trl import SFTTrainer, SFTConfig
8
+ import logging
9
+ import torch.distributed as dist
10
+ from datetime import timedelta, datetime
11
+ import time
12
+ from transformers.trainer import TrainerCallback
13
+ import gc
14
+ import sys
15
+ import shutil # For handling file operations
16
+ import glob # For file pattern matching
17
+ import threading # For background cleanup
18
+ import multiprocessing
19
+ import subprocess
20
+ import tempfile
21
+ import json
22
+ import random
23
+ import math
24
+ import queue
25
+ import numpy as np
26
+
27
+ # Import the specific layer class for FSDP wrapping
28
+ try:
29
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer
30
+ except ImportError:
31
+ logging.warning("Could not import Qwen2DecoderLayer. FSDP wrapping might fail.")
32
+ Qwen2DecoderLayer = None
33
+
34
+ # Configure more detailed logging with timestamps
35
+ logging.basicConfig(
36
+ level=logging.INFO,
37
+ format='%(asctime)s - %(levelname)s - %(message)s',
38
+ datefmt='%Y-%m-%d %H:%M:%S',
39
+ stream=sys.stdout, # Ensure logs go to stdout for immediate visibility
40
+ force=True
41
+ )
42
+
43
+ # Set up temporary directory for cache files
44
+ temp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp")
45
+ os.makedirs(temp_dir, exist_ok=True)
46
+ logging.info(f"Using temporary directory: {temp_dir}")
47
+
48
+ # Set environment variables to control temporary file creation
49
+ os.environ["TMPDIR"] = temp_dir # Unix
50
+ os.environ["TEMP"] = temp_dir # Windows
51
+ os.environ["TMP"] = temp_dir # Windows alternative
52
+
53
+ # Set default cache locations
54
+ hf_datasets_cache_path = os.path.join(temp_dir, "hf_datasets_cache")
55
+ transformers_cache_path = os.path.join(temp_dir, "transformers_cache")
56
+ hf_home_path = os.path.join(temp_dir, "hf_home")
57
+ os.makedirs(hf_datasets_cache_path, exist_ok=True)
58
+ os.makedirs(transformers_cache_path, exist_ok=True)
59
+ os.makedirs(hf_home_path, exist_ok=True)
60
+
61
+ os.environ["HF_DATASETS_CACHE"] = hf_datasets_cache_path
62
+ os.environ["TRANSFORMERS_CACHE"] = transformers_cache_path
63
+ os.environ["HF_HOME"] = hf_home_path
64
+ logging.info(f"Hugging Face Datasets cache directed to: {hf_datasets_cache_path}")
65
+ logging.info(f"Hugging Face Transformers cache directed to: {transformers_cache_path}")
66
+
67
+ # Keep forcing Arrow to use system memory pool if possible
68
+ os.environ["ARROW_DEFAULT_MEMORY_POOL"] = "system"
69
+ logging.info("Configured temporary directory and cache locations.")
70
+
71
+ # Set environment variable to control PyTorch's memory allocator
72
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True,max_split_size_mb:512"
73
+ # Disable PYTORCH_NO_CUDA_MEMORY_CACHING for better performance
74
+ if "PYTORCH_NO_CUDA_MEMORY_CACHING" in os.environ:
75
+ del os.environ["PYTORCH_NO_CUDA_MEMORY_CACHING"]
76
+ # Set a longer timeout for NCCL operations
77
+ os.environ["NCCL_BLOCKING_WAIT"] = "1"
78
+ os.environ["NCCL_ASYNC_ERROR_HANDLING"] = "1"
79
+ os.environ["NCCL_TIMEOUT"] = "3600" # 1 hour timeout for NCCL operations
80
+
81
+ # Initialize distributed environment with better error handling
82
+ def init_distributed():
83
+ try:
84
+ # Check if we're in a distributed training environment
85
+ if "WORLD_SIZE" in os.environ and int(os.environ["WORLD_SIZE"]) > 1:
86
+ # Set memory optimization environment variables
87
+ if int(os.environ.get("LOCAL_RANK", 0)) == 0:
88
+ logging.info("Setting PyTorch memory optimizations for H200 GPUs")
89
+ # Empty CUDA cache before initializing process group
90
+ if torch.cuda.is_available():
91
+ torch.cuda.empty_cache()
92
+ logging.info("CUDA cache cleared")
93
+
94
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
95
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
96
+ rank = int(os.environ.get("RANK", 0))
97
+
98
+ logging.info(f"Initializing distributed training for 8x H200s. Rank: {rank}, Local Rank: {local_rank}, World Size: {world_size}")
99
+
100
+ # Set the device for this process explicitly before initializing
101
+ torch.cuda.set_device(local_rank)
102
+ logging.info(f"Setting device {local_rank} for process rank {rank}")
103
+
104
+ # Set a longer timeout to handle long operations (3 hours)
105
+ timeout = timedelta(hours=3)
106
+
107
+ # Initialize the distributed process group
108
+ dist.init_process_group(
109
+ backend='nccl',
110
+ init_method='env://',
111
+ timeout=timeout,
112
+ rank=rank,
113
+ world_size=world_size
114
+ )
115
+
116
+ # Verify initialization was successful
117
+ if dist.is_initialized():
118
+ logging.info(f"Successfully initialized distributed process group. Rank: {rank}, Device: {torch.cuda.current_device()}")
119
+ # Log NCCL environment
120
+ logging.info(f"NCCL Version: {torch.cuda.nccl.version() if hasattr(torch.cuda, 'nccl') else 'unknown'}")
121
+ logging.info(f"CUDA Device Count: {torch.cuda.device_count()}")
122
+ logging.info(f"CUDA Device Name: {torch.cuda.get_device_name(local_rank)}")
123
+ else:
124
+ logging.error(f"Failed to initialize distributed process group. Rank: {rank}")
125
+
126
+ # Ensure all processes can communicate with specified device
127
+ try:
128
+ device_ids = [local_rank]
129
+ dist.barrier(device_ids=device_ids)
130
+ logging.info(f"Communication test successful. Process {rank} on device {local_rank} can communicate.")
131
+ except Exception as e:
132
+ logging.error(f"Communication test failed. Processes cannot communicate: {str(e)}. Rank: {rank}")
133
+ raise
134
+
135
+ return True
136
+ else:
137
+ logging.info("Not running in distributed mode.")
138
+ return False
139
+ except Exception as e:
140
+ logging.error(f"Error initializing distributed environment: {str(e)}")
141
+ raise
142
+
143
+ # Initialize distributed environment
144
+ distributed_mode = init_distributed()
145
+
146
+ # --- Configuration ---
147
+
148
+ # Model ID updated based on user input
149
+ MODEL_ID = "Qwen/QwQ-32B"
150
+
151
+ # Path to the processed dataset created by preprocess_data.py
152
+ DATASET_PATH = "./processed_datasets/combined_code_finetune_data"
153
+
154
+ # Number of examples to use (set to -1 for all)
155
+ MAX_EXAMPLES = -1 # Use all examples by default
156
+
157
+ # LoRA configuration (Optimized for 8x H200 GPUs)
158
+ LORA_R = 64 # Doubled to increase parameter count significantly
159
+ LORA_ALPHA = 128 # Increased alpha to match r
160
+ LORA_DROPOUT = 0.05 # Dropout probability for LoRA layers
161
+ # Target modules might need verification for QwQ-32B specifically.
162
+ # Common targets for Qwen models:
163
+ LORA_TARGET_MODULES = [
164
+ "q_proj",
165
+ "k_proj",
166
+ "v_proj",
167
+ "o_proj",
168
+ "gate_proj",
169
+ "up_proj",
170
+ "down_proj",
171
+ # "embed_tokens", # Removed to reduce overhead/complexity
172
+ # "lm_head", # Removed to reduce overhead/complexity
173
+ ]
174
+
175
+ # Training arguments optimized for 8x H200 GPUs with memory constraints
176
+ OUTPUT_DIR = "./qwq-32b-finetuned-adapters"
177
+ PER_DEVICE_TRAIN_BATCH_SIZE = 8 # Increase BS after halving seq length again
178
+ GRADIENT_ACCUMULATION_STEPS = 6 # Decrease accumulation (8*8*6 = 384)
179
+ # Global batch size = PER_DEVICE_TRAIN_BATCH_SIZE * GRADIENT_ACCUMULATION_STEPS * NumGPUs
180
+ # Example: 8 * 6 * 8 = 384
181
+ LEARNING_RATE = 3e-5 # Slightly higher LR for larger batch size
182
+ EPOCHS = 1 # Start with 1 epoch, increase cautiously
183
+ MAX_SEQ_LENGTH = 4096 # Halved sequence length again
184
+ LOGGING_STEPS = 50 # Increased logging frequency
185
+ SAVE_STEPS = 500 # Increased save frequency
186
+ OPTIMIZER = "adamw_bnb_8bit" # Use 8-bit optimizer to save significant memory
187
+ WARMUP_RATIO = 0.03
188
+ LR_SCHEDULER_TYPE = "cosine"
189
+
190
+ # H200-specific optimizations (8x setup)
191
+ USE_FLASH_ATTN = True # Enable Flash Attention 2 for H200s
192
+ USE_SEQUENCE_PARALLEL = False # Disable when using FSDP
193
+ USE_BETTER_TRANSFORMERS = True # Use better transformers for optimized kernels
194
+ DATALOADER_NUM_WORKERS = 8 # Reduced workers to avoid CPU contention
195
+ TOKENIZATION_NUM_WORKERS = 224 # Maximum worker count for tokenization
196
+ USE_ACTIVATION_CHECKPOINTING = True # Enable activation checkpointing to save memory with long sequences
197
+
198
+ # Advanced distributed training options for 8x GPUs
199
+ USE_FSDP = True # Enable FSDP
200
+ FSDP_CONFIG = {
201
+ "fsdp_offload_params": False, # Disable CPU Offload
202
+ "fsdp_sharding_strategy": 1, # 1 = FULL_SHARD
203
+ "fsdp_auto_wrap_policy": "TRANSFORMER_BASED_WRAP",
204
+ "fsdp_transformer_layer_cls_to_wrap": [Qwen2DecoderLayer.__name__] if Qwen2DecoderLayer else [],
205
+ "fsdp_state_dict_type": "SHARDED_STATE_DICT",
206
+ "fsdp_backward_prefetch": "backward_post", # Changed from backward_pre
207
+ "fsdp_forward_prefetch": False, # Disabled forward prefetch
208
+ "fsdp_activation_checkpointing": [Qwen2DecoderLayer.__name__] if Qwen2DecoderLayer else [], # Use FSDP activation checkpointing
209
+ }
210
+
211
+ # WandB Integration
212
+ REPORT_TO_WANDB = True # Set to False to disable WandB reporting
213
+ WANDB_PROJECT_NAME = "QwQ-32B-Finetune-8xH200" # Updated for 8x GPUs
214
+ WANDB_ENTITY = None # Set to your username or team name if needed
215
+
216
+ # Determine report_to destination
217
+ report_to = "none"
218
+ if REPORT_TO_WANDB:
219
+ # Disable WandB in all processes except rank 0 in distributed mode
220
+ if distributed_mode and int(os.environ.get("LOCAL_RANK", 0)) != 0:
221
+ logging.info(f"Rank {os.environ.get('RANK', '?')}: Disabling WandB")
222
+ os.environ["WANDB_DISABLED"] = "true"
223
+ report_to = "none" # Explicitly set to none for non-main processes
224
+ else:
225
+ # Main process or non-distributed mode, attempt WandB initialization
226
+ try:
227
+ import wandb
228
+ logging.info("Initializing WandB directly...")
229
+ run_name = f"qwq-32b-finetune-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
230
+ if wandb.run is None:
231
+ try:
232
+ wandb.init(
233
+ project=WANDB_PROJECT_NAME,
234
+ entity=WANDB_ENTITY,
235
+ name=run_name,
236
+ config={
237
+ "model_name": MODEL_ID,
238
+ "batch_size": PER_DEVICE_TRAIN_BATCH_SIZE,
239
+ "gradient_accumulation_steps": GRADIENT_ACCUMULATION_STEPS,
240
+ "learning_rate": LEARNING_RATE,
241
+ "epochs": EPOCHS,
242
+ "sequence_length": MAX_SEQ_LENGTH,
243
+ "lora_r": LORA_R,
244
+ "lora_alpha": LORA_ALPHA,
245
+ }
246
+ )
247
+ logging.info(f"WandB initialized: {wandb.run.name} (ID: {wandb.run.id})")
248
+ report_to = "wandb"
249
+ except Exception as e:
250
+ logging.error(f"WandB initialization error: {str(e)}")
251
+ report_to = "tensorboard"
252
+ else:
253
+ logging.info(f"Using existing WandB run: {wandb.run.name} (ID: {wandb.run.id})")
254
+ report_to = "wandb"
255
+ except ImportError:
256
+ logging.warning("WandB package not installed. Reporting to TensorBoard.")
257
+ report_to = "tensorboard"
258
+ except Exception as wandb_init_e:
259
+ logging.error(f"General WandB setup error: {wandb_init_e}")
260
+ report_to = "tensorboard"
261
+ # If WandB reporting is disabled, set report_to accordingly
262
+ elif not distributed_mode:
263
+ report_to = "tensorboard"
264
+ logging.info("WandB reporting disabled. Reporting to TensorBoard.")
265
+ else: # If WandB is disabled and it IS distributed
266
+ report_to = "none"
267
+ logging.info("WandB reporting disabled for this distributed rank.")
268
+
269
+ # Quantization (QLoRA)
270
+ USE_4BIT_QUANTIZATION = False # Disable QLoRA due to FSDP incompatibility
271
+ BNB_4BIT_COMPUTE_DTYPE = "bfloat16" # Use bfloat16 if supported, else float16
272
+ BNB_4BIT_QUANT_TYPE = "nf4"
273
+
274
+ # --- Check Optional Dependencies (Define flags globally) ---
275
+ FLASH_ATTN_AVAILABLE = False
276
+ BETTER_TRANSFORMERS_AVAILABLE = False
277
+ try:
278
+ import flash_attn
279
+ FLASH_ATTN_AVAILABLE = True
280
+ logging.info("Flash Attention available - will be used if enabled.")
281
+ except ImportError:
282
+ logging.warning("Flash Attention not available. Install with 'pip install flash-attn'")
283
+
284
+ try:
285
+ from optimum.bettertransformer import BetterTransformer
286
+ BETTER_TRANSFORMERS_AVAILABLE = True
287
+ logging.info("Better Transformers available - will be used if enabled.")
288
+ except ImportError:
289
+ logging.warning("Better Transformers not available. Install with 'pip install optimum'")
290
+
291
+ # --- Check Dataset ---
292
+ if not os.path.exists(DATASET_PATH):
293
+ logging.error(f"Dataset not found at {DATASET_PATH}. Run preprocess_data.py first.")
294
+ exit(1)
295
+
296
+ logging.info(f"Loading dataset from {DATASET_PATH}...")
297
+
298
+ # Load dataset normally
299
+ dataset = load_from_disk(DATASET_PATH)
300
+
301
+ # Apply truncation if needed
302
+ if MAX_EXAMPLES > 0 and len(dataset) > MAX_EXAMPLES:
303
+ logging.info(f"Truncating dataset to {MAX_EXAMPLES} examples")
304
+ indices = list(range(min(MAX_EXAMPLES, len(dataset))))
305
+ dataset = dataset.select(indices)
306
+
307
+ logging.info(f"Dataset loaded: {dataset} with {len(dataset)} examples")
308
+
309
+ # --- Tokenizer ---
310
+ logging.info(f"Loading tokenizer for {MODEL_ID}...")
311
+
312
+ # Enable fast tokenizer and optimizations
313
+ tokenizer = AutoTokenizer.from_pretrained(
314
+ MODEL_ID,
315
+ use_fast=True, # Explicitly request the fast Rust-based tokenizer
316
+ trust_remote_code=True,
317
+ # model_max_length=MAX_SEQ_LENGTH,
318
+ padding_side="right",
319
+ )
320
+
321
+ # Log tokenizer type for verification
322
+ if hasattr(tokenizer, 'is_fast') and tokenizer.is_fast:
323
+ logging.info(f"Successfully loaded fast tokenizer (Rust implementation): {type(tokenizer).__name__}")
324
+ # Fast tokenizers are automatically parallel in dataset.map() when num_proc > 1
325
+ logging.info(f"Fast tokenizer will use parallel processing during dataset.map() with {TOKENIZATION_NUM_WORKERS} workers")
326
+ else:
327
+ logging.warning(f"Using Python tokenizer: {type(tokenizer).__name__}")
328
+ logging.warning("Python tokenizers are slower than Rust-based fast tokenizers")
329
+
330
+ # Check and set pad token based on Qwen documentation (<|endoftext|>)
331
+ # Qwen models might have this set correctly, but we verify.
332
+ EXPECTED_PAD_TOKEN = "<|endoftext|>"
333
+ if tokenizer.pad_token is None or tokenizer.pad_token != EXPECTED_PAD_TOKEN:
334
+ logging.warning(f"Tokenizer pad_token is missing or not '{EXPECTED_PAD_TOKEN}'. Setting pad_token='{EXPECTED_PAD_TOKEN}'.")
335
+ tokenizer.pad_token = EXPECTED_PAD_TOKEN
336
+
337
+ # Enable padding and truncation defaults for batch processing
338
+ tokenizer.pad_token = tokenizer.eos_token if tokenizer.pad_token is None else tokenizer.pad_token
339
+ tokenizer.padding_side = "right" # Typically "right" for decoder-only models like Qwen
340
+
341
+ # Log tokenizer configuration
342
+ logging.info(f"Tokenizer configuration:")
343
+ logging.info(f" - Type: {'Fast' if hasattr(tokenizer, 'is_fast') and tokenizer.is_fast else 'Python'}")
344
+ logging.info(f" - Pad token: {tokenizer.pad_token}")
345
+ logging.info(f" - EOS token: {tokenizer.eos_token}") # Should be <|im_end|>
346
+ logging.info(f" - Vocab size: {tokenizer.vocab_size}")
347
+ logging.info(f" - Model max length: {tokenizer.model_max_length}")
348
+ logging.info(f" - Padding side: {tokenizer.padding_side}")
349
+
350
+ # Define parallel preprocessing function for the dataset
351
+ def preprocess_function(examples):
352
+ return tokenizer(
353
+ examples["text"],
354
+ padding="max_length",
355
+ truncation=True,
356
+ max_length=MAX_SEQ_LENGTH,
357
+ return_tensors=None, # Return Python lists for dataset
358
+ )
359
+
360
+ # Create a cache directory for tokenized datasets
361
+ TOKENIZED_DATASET_CACHE_DIR = os.path.join(os.path.dirname(DATASET_PATH), "tokenized_cache")
362
+ os.makedirs(TOKENIZED_DATASET_CACHE_DIR, exist_ok=True)
363
+ tokenized_dataset_path = os.path.join(TOKENIZED_DATASET_CACHE_DIR, "tokenized_dataset")
364
+
365
+ # Create a file to signal tokenization completion
366
+ tokenization_done_file = os.path.join(TOKENIZED_DATASET_CACHE_DIR, "tokenization_complete")
367
+
368
+ # Function to clean up temporary files in dataset directory
369
+ def delete_existing_tmp_files():
370
+ """Find and delete any existing tmp files in dataset directory"""
371
+ # Look for tmp files in dataset directory
372
+ tmp_files = glob.glob(os.path.join(DATASET_PATH, "tmp*"))
373
+
374
+ if tmp_files:
375
+ logging.info(f"Found {len(tmp_files)} existing tmp files, removing...")
376
+ for tmp_file in tmp_files:
377
+ try:
378
+ if os.path.isdir(tmp_file):
379
+ shutil.rmtree(tmp_file)
380
+ else:
381
+ os.remove(tmp_file)
382
+ logging.info(f"Removed: {tmp_file}")
383
+ except Exception as e:
384
+ logging.warning(f"Could not remove {tmp_file}: {str(e)}")
385
+ else:
386
+ logging.info("No existing tmp files found")
387
+
388
+ # Check if we're in distributed mode and get rank
389
+ if distributed_mode:
390
+ rank = int(os.environ.get("RANK", "0"))
391
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
392
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
393
+ is_main_process = rank == 0
394
+ logging.info(f"Rank {rank}/{world_size}: Preparing for dataset processing")
395
+ else:
396
+ is_main_process = True
397
+ rank = 0
398
+ world_size = 1
399
+ local_rank = 0
400
+
401
+ # Clean up temp files - only on main process to avoid conflicts
402
+ if is_main_process:
403
+ delete_existing_tmp_files()
404
+ # Also remove the tokenization_done_file if it exists
405
+ if os.path.exists(tokenization_done_file):
406
+ os.remove(tokenization_done_file)
407
+ logging.info(f"Rank {rank}: Removed old tokenization completion marker")
408
+
409
+ # Only tokenize on main process (rank 0) to avoid redundant work
410
+ need_tokenization = False
411
+
412
+ # Check if tokenized dataset already exists
413
+ if os.path.exists(tokenized_dataset_path) and os.path.isdir(tokenized_dataset_path):
414
+ # --- Dataset Exists ---
415
+ logging.info(f"Rank {rank}: Found existing tokenized dataset at {tokenized_dataset_path}")
416
+ path_to_load = tokenized_dataset_path # All ranks will load from the persistent path
417
+ need_tokenization = False
418
+
419
+ # Rank 0 ensures completion marker exists
420
+ if is_main_process and not os.path.exists(tokenization_done_file):
421
+ total_original_examples = "unknown"
422
+ try:
423
+ from datasets import load_dataset_builder # Local import
424
+ original_dataset_info = load_dataset_builder(DATASET_PATH).info
425
+ total_original_examples = original_dataset_info.splits['train'].num_examples
426
+ except Exception as info_e:
427
+ logging.warning(f"Rank {rank}: Could not get original dataset info: {info_e}")
428
+ try:
429
+ # Get size of existing loaded dataset (approximate if needed)
430
+ # This requires loading a small part or metadata, might be slow
431
+ # For now, let's just mark it as existing
432
+ # loaded_size = len(load_from_disk(tokenized_dataset_path, keep_in_memory=False))
433
+ loaded_size = "unknown (loaded existing)"
434
+ with open(tokenization_done_file, "w") as f:
435
+ f.write(f"Tokenization assumed complete (loaded existing) at {datetime.now().isoformat()}\n")
436
+ f.write(f"Processed {loaded_size} examples out of {total_original_examples}\n")
437
+ logging.info(f"Rank {rank}: Created tokenization completion marker as it was missing.")
438
+ except Exception as file_e:
439
+ logging.error(f"Rank {rank}: Failed to create missing completion marker: {file_e}")
440
+ # Proceeding anyway, but other ranks might hang if they rely solely on the file
441
+
442
+ # Non-main ranks still need to wait for the marker to be sure Rank 0 checked/created it
443
+ elif not is_main_process:
444
+ logging.info(f"Rank {rank}: Waiting for main process confirmation via marker file...")
445
+ max_wait_time = 300 # Shorter wait, just confirming file exists
446
+ wait_start = time.time()
447
+ while not os.path.exists(tokenization_done_file):
448
+ if time.time() - wait_start > max_wait_time:
449
+ logging.error(f"Rank {rank}: Timed out waiting for marker file from Rank 0.")
450
+ raise TimeoutError("Marker file wait timeout")
451
+ time.sleep(5)
452
+ logging.info(f"Rank {rank}: Marker file found.")
453
+
454
+ elif is_main_process: # Tokenized doesn't exist, Rank 0 needs to create it
455
+ logging.info(f"Rank {rank}: Tokenization required. Proceeding with tokenization...")
456
+ need_tokenization = True
457
+ path_to_load = None
458
+
459
+ elif distributed_mode: # Tokenized doesn't exist, non-main ranks need to wait
460
+ logging.info(f"Rank {rank}: Tokenization required. Waiting for main process...")
461
+ need_tokenization = True
462
+ path_to_load = tokenized_dataset_path
463
+
464
+ # --- Perform Tokenization (if needed by Rank 0) ---
465
+ if need_tokenization and is_main_process:
466
+ tokenized_dataset_obj = None # Use a distinct name for the object returned by map
467
+ try:
468
+ # Process the dataset using dataset.map with internal parallelism
469
+ start_time = time.time() # Define start_time here
470
+
471
+ # Standard tokenization with caching enabled
472
+ logging.info(f"Rank {rank}: Starting tokenization using dataset.map with {TOKENIZATION_NUM_WORKERS} workers.")
473
+
474
+ tokenized_dataset_obj = dataset.map(
475
+ preprocess_function,
476
+ batched=True,
477
+ batch_size=1000,
478
+ num_proc=TOKENIZATION_NUM_WORKERS,
479
+ remove_columns=["text"],
480
+ load_from_cache_file=True, # Allow using cache file if it exists
481
+ desc=f"Tokenizing dataset ({TOKENIZATION_NUM_WORKERS} workers)"
482
+ )
483
+
484
+ elapsed = time.time() - start_time
485
+ logging.info(f"Rank {rank}: Tokenization successful in {elapsed:.2f} seconds.")
486
+
487
+ # If tokenization was successful:
488
+ if tokenized_dataset_obj is not None:
489
+ logging.info(f"Rank {rank}: Dataset tokenization completed.")
490
+
491
+ # Save directly to final path
492
+ logging.info(f"Rank {rank}: Saving tokenized dataset to {tokenized_dataset_path}...")
493
+ save_start = time.time()
494
+
495
+ # Ensure target directory doesn't exist (needed for clean save)
496
+ if os.path.exists(tokenized_dataset_path):
497
+ shutil.rmtree(tokenized_dataset_path)
498
+
499
+ tokenized_dataset_obj.save_to_disk(tokenized_dataset_path)
500
+ save_elapsed = time.time() - save_start
501
+ logging.info(f"Rank {rank}: Tokenized dataset saved in {save_elapsed:.2f} seconds.")
502
+
503
+ # Create completion marker file ONLY after successful save
504
+ with open(tokenization_done_file, "w") as f:
505
+ f.write(f"Tokenization completed and saved at {datetime.now().isoformat()}\n")
506
+ logging.info(f"Rank {rank}: Created tokenization completion marker")
507
+
508
+ # Keep the result in memory for Rank 0 for immediate use
509
+ dataset = tokenized_dataset_obj
510
+ path_to_load = None # Rank 0 uses the in-memory object directly
511
+
512
+ except Exception as e:
513
+ logging.error(f"Rank {rank}: Tokenization failed: {e}")
514
+ import traceback
515
+ logging.error(traceback.format_exc())
516
+ # Create done file indicating failure
517
+ with open(tokenization_done_file, "w") as f:
518
+ f.write(f"Tokenization FAILED at {datetime.now().isoformat()}\nError: {e}")
519
+ raise RuntimeError("Tokenization failed.") from e
520
+
521
+ # --- Load Dataset (All Ranks) ---
522
+ # This block now runs for all ranks *after* rank 0 has either tokenized or copied data
523
+ dataset_for_trainer = None # Use a distinct variable name for clarity
524
+ if path_to_load: # If path_to_load is set (means rank 0 copied or non-main rank needs to load)
525
+ if not is_main_process and need_tokenization:
526
+ # Non-main ranks wait for the done file if tokenization was required
527
+ logging.info(f"Rank {rank}: Waiting for tokenization completion signal (already checked for existence)...")
528
+ # Wait logic already happened if we got here and path_to_load is set
529
+ pass
530
+
531
+ # All ranks with a path_to_load proceed to load
532
+ logging.info(f"Rank {rank}: Loading dataset from {path_to_load}...")
533
+ load_start_time = time.time()
534
+ try:
535
+ # Load without forcing into memory initially
536
+ dataset_for_trainer = load_from_disk(path_to_load, keep_in_memory=False)
537
+ load_elapsed = time.time() - load_start_time
538
+ logging.info(f"Rank {rank}: Successfully loaded dataset in {load_elapsed:.2f}s. Length: {len(dataset_for_trainer)}")
539
+ except Exception as e:
540
+ logging.error(f"Rank {rank}: CRITICAL - Failed to load dataset from {path_to_load}: {e}")
541
+ raise
542
+ elif is_main_process and not need_tokenization:
543
+ # Rank 0 loaded existing, copied to RAM disk, and path_to_load points there
544
+ # It still needs to load it for the trainer
545
+ logging.info(f"Rank {rank}: Loading dataset from RAM disk copy {path_to_load}...")
546
+ try:
547
+ dataset_for_trainer = load_from_disk(path_to_load, keep_in_memory=False)
548
+ logging.info(f"Rank {rank}: Successfully loaded dataset from RAM disk copy.")
549
+ except Exception as e:
550
+ logging.error(f"Rank {rank}: CRITICAL - Failed to load from RAM disk copy {path_to_load}: {e}")
551
+ raise
552
+ elif is_main_process and need_tokenization:
553
+ # Rank 0 just tokenized, 'dataset' variable already holds the result in memory
554
+ logging.info(f"Rank {rank}: Using in-memory dataset from successful tokenization.")
555
+ dataset_for_trainer = dataset # Use the object directly
556
+ else:
557
+ # Should not happen
558
+ logging.error(f"Rank {rank}: Dataset path logic error. path_to_load='{path_to_load}', need_tokenization={need_tokenization}")
559
+ raise RuntimeError("Dataset preparation failed - logic error.")
560
+
561
+ # At this point, 'dataset' on all ranks should hold the ready-to-use data.
562
+
563
+ # Synchronize processes after dataset is ready on all ranks
564
+ if distributed_mode:
565
+ try:
566
+ logging.info(f"Rank {rank}: Synchronizing after dataset preparation...")
567
+ dist.barrier()
568
+ logging.info(f"Rank {rank}: Synchronization complete.")
569
+ except Exception as sync_e:
570
+ logging.error(f"Rank {rank}: Synchronization after dataset prep failed: {sync_e}")
571
+ raise
572
+
573
+ # --- Helper Function for Memory Check ---
574
+ def check_gpu_memory_utilization():
575
+ """Check and report GPU memory utilization"""
576
+ if not torch.cuda.is_available():
577
+ logging.info("CUDA not available, skipping GPU memory check.")
578
+ return 0 # Return 0 utilization if no GPU
579
+
580
+ logging.info("==== GPU MEMORY UTILIZATION CHECK ====")
581
+ total_allocated_gb = 0
582
+ total_reserved_gb = 0
583
+ total_capacity_gb = 0
584
+
585
+ try:
586
+ for i in range(torch.cuda.device_count()):
587
+ free_mem, total_mem = torch.cuda.mem_get_info(i)
588
+ allocated = torch.cuda.memory_allocated(i)
589
+ reserved = torch.cuda.memory_reserved(i)
590
+
591
+ free_gb = free_mem / (1024**3)
592
+ total_gb = total_mem / (1024**3)
593
+ allocated_gb = allocated / (1024**3)
594
+ reserved_gb = reserved / (1024**3)
595
+ utilized_pct = (1 - free_mem/total_mem) * 100 if total_mem > 0 else 0
596
+
597
+ total_allocated_gb += allocated_gb
598
+ total_reserved_gb += reserved_gb
599
+ total_capacity_gb += total_gb
600
+
601
+ logging.info(f"GPU {i}: Allocated {allocated_gb:.1f}GB, Reserved {reserved_gb:.1f}GB, "
602
+ f"Free {free_gb:.1f}GB, Total {total_gb:.1f}GB, "
603
+ f"Utilization: {utilized_pct:.1f}%")
604
+
605
+ avg_utilization = (total_allocated_gb / total_capacity_gb) * 100 if total_capacity_gb > 0 else 0
606
+ logging.info(f"OVERALL: Using {total_allocated_gb:.1f}GB / {total_capacity_gb:.1f}GB ({avg_utilization:.1f}% allocated)")
607
+ logging.info("========================================")
608
+ return avg_utilization
609
+ except Exception as e:
610
+ logging.error(f"Error checking GPU memory: {e}")
611
+ return 0 # Return 0 on error
612
+
613
+ # --- Model Loading & Preparation (Runs on ALL ranks) ---
614
+ logging.info(f"Rank {rank}: Loading model: {MODEL_ID}...")
615
+
616
+ # 1. Load Model Configuration
617
+ config = AutoConfig.from_pretrained(MODEL_ID, trust_remote_code=True)
618
+ logging.info("Enabling YaRN scaling in model configuration.")
619
+ config.rope_scaling = {
620
+ "type": "yarn",
621
+ "factor": 4.0,
622
+ "original_max_position_embeddings": 32768,
623
+ }
624
+
625
+ # Determine torch dtype
626
+ torch_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
627
+
628
+ # Set device_map based on distributed mode
629
+ # When using FSDP, device_map should typically be None or "auto", FSDP handles placement.
630
+ if USE_FSDP:
631
+ device_map = None
632
+ logging.info("FSDP enabled: Setting device_map=None")
633
+ elif distributed_mode:
634
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
635
+ device_map = {"": local_rank}
636
+ logging.info(f"Rank {rank}: DDP mode: Loading model on device {local_rank}")
637
+ else:
638
+ device_map = "auto"
639
+ logging.info("Rank {rank}: Single process mode: Using automatic device mapping")
640
+
641
+ # Configure Flash Attention and other optimizations
642
+ use_flash_attn = USE_FLASH_ATTN and FLASH_ATTN_AVAILABLE
643
+ attn_implementation = "flash_attention_2" if use_flash_attn else None
644
+
645
+ # Configure Quantization if enabled
646
+ # quantization_config = None
647
+ # if USE_4BIT_QUANTIZATION:
648
+ # logging.info("Configuring 4-bit quantization (QLoRA)...")
649
+ # compute_dtype = getattr(torch, BNB_4BIT_COMPUTE_DTYPE)
650
+ # quantization_config = BitsAndBytesConfig(
651
+ # load_in_4bit=True,
652
+ # bnb_4bit_quant_type=BNB_4BIT_QUANT_TYPE,
653
+ # bnb_4bit_compute_dtype=compute_dtype,
654
+ # bnb_4bit_use_double_quant=True, # Qwen models often benefit from double quant
655
+ # )
656
+ # # Override torch_dtype when using quantization as recommended
657
+ # # torch_dtype = None
658
+ # logging.info(f"4-bit quantization config created: type={BNB_4BIT_QUANT_TYPE}, compute={BNB_4BIT_COMPUTE_DTYPE}")
659
+
660
+ # Configure model loading kwargs
661
+ model_load_kwargs = {
662
+ "config": config,
663
+ "device_map": device_map,
664
+ "low_cpu_mem_usage": True,
665
+ "trust_remote_code": True,
666
+ }
667
+ if use_flash_attn:
668
+ model_load_kwargs["attn_implementation"] = "flash_attention_2"
669
+ # if quantization_config:
670
+ # model_load_kwargs["quantization_config"] = quantization_config
671
+ # Always set torch_dtype when not using quantization
672
+ model_load_kwargs["torch_dtype"] = torch_dtype
673
+
674
+ # Log memory before loading
675
+ # ... (memory logging logic - keep as is) ...
676
+
677
+ # Load the model
678
+ model = None # Initialize model variable
679
+ try:
680
+ logging.info(f"Rank {rank}: Calling AutoModelForCausalLM.from_pretrained...")
681
+ model = AutoModelForCausalLM.from_pretrained(
682
+ MODEL_ID,
683
+ **model_load_kwargs
684
+ )
685
+ logging.info(f"Rank {rank}: Base model loaded successfully on device: {model.device if device_map is None else 'CPU/Multi'}")
686
+
687
+ # Ensure consistent dtype before FSDP wrapping (which happens in trainer.train)
688
+ if torch_dtype == torch.bfloat16:
689
+ logging.info("Explicitly casting model to bfloat16...")
690
+ model = model.to(torch.bfloat16)
691
+
692
+ # Apply Better Transformers optimization
693
+ use_better_transformers_flag = USE_BETTER_TRANSFORMERS and BETTER_TRANSFORMERS_AVAILABLE
694
+ if use_better_transformers_flag:
695
+ try:
696
+ logging.info("Applying BetterTransformer optimizations...")
697
+ model = BetterTransformer.transform(model)
698
+ logging.info("BetterTransformer optimizations applied successfully")
699
+ except Exception as bt_e:
700
+ logging.warning(f"Could not apply BetterTransformer optimizations: {str(bt_e)}")
701
+
702
+ # Apply activation checkpointing
703
+ if USE_ACTIVATION_CHECKPOINTING:
704
+ try:
705
+ logging.info("Enabling activation checkpointing...")
706
+ model.gradient_checkpointing_enable()
707
+ logging.info("Activation checkpointing enabled.")
708
+ except Exception as ac_e:
709
+ logging.warning(f"Could not enable activation checkpointing: {str(ac_e)}")
710
+
711
+ # Log model config and check memory utilization
712
+ logging.info(f"Rank {rank}: Model setup complete.")
713
+ check_gpu_memory_utilization() # This function needs to be defined or moved
714
+
715
+ except Exception as model_load_e: # Correct indentation for except
716
+ logging.error(f"Rank {rank}: Failed during model loading or preparation: {model_load_e}")
717
+ import traceback
718
+ logging.error(traceback.format_exc())
719
+ # Attempt to clean up distributed env before raising
720
+ if distributed_mode and dist.is_initialized():
721
+ try: dist.destroy_process_group()
722
+ except: pass
723
+ raise # Re-raise error
724
+
725
+ # --- LoRA Configuration ---
726
+ # ... (LoRA config - keep as is) ...
727
+ peft_config = LoraConfig(
728
+ r=LORA_R,
729
+ lora_alpha=LORA_ALPHA,
730
+ lora_dropout=LORA_DROPOUT,
731
+ target_modules=LORA_TARGET_MODULES,
732
+ bias="none",
733
+ task_type="CAUSAL_LM",
734
+ )
735
+
736
+ # --- Synchronize AFTER model loading & PEFT config ---
737
+ if distributed_mode:
738
+ try:
739
+ logging.info(f"Rank {rank}: Synchronizing after model loading...")
740
+ dist.barrier()
741
+ logging.info(f"Rank {rank}: Synchronization after model loading complete.")
742
+ except Exception as sync_e:
743
+ logging.error(f"Rank {rank}: Synchronization after model loading failed: {sync_e}")
744
+ raise
745
+
746
+ # --- Define Training Arguments ---
747
+ # (Determine determined_run_name logic here as before)
748
+ determined_run_name = None
749
+ if REPORT_TO_WANDB and is_main_process:
750
+ try:
751
+ import wandb
752
+ if wandb.run is not None: determined_run_name = wandb.run.name
753
+ except Exception: pass # Ignore errors here, handled by report_to
754
+
755
+ base_training_args = {
756
+ # ... (all base args, including max_seq_length) ...
757
+ "output_dir": OUTPUT_DIR,
758
+ "per_device_train_batch_size": PER_DEVICE_TRAIN_BATCH_SIZE,
759
+ "gradient_accumulation_steps": GRADIENT_ACCUMULATION_STEPS,
760
+ "optim": OPTIMIZER,
761
+ "save_steps": SAVE_STEPS,
762
+ "logging_steps": LOGGING_STEPS,
763
+ "learning_rate": LEARNING_RATE,
764
+ "num_train_epochs": EPOCHS,
765
+ "max_steps": -1,
766
+ "fp16": False,
767
+ "bf16": torch_dtype == torch.bfloat16, # Use previously determined dtype
768
+ "max_grad_norm": 0.3,
769
+ "warmup_ratio": WARMUP_RATIO,
770
+ "group_by_length": False, # Explicitly disable to prevent pre-computation hang
771
+ "lr_scheduler_type": LR_SCHEDULER_TYPE,
772
+ "report_to": report_to,
773
+ "save_total_limit": 3,
774
+ "logging_first_step": True,
775
+ **({"run_name": determined_run_name} if determined_run_name is not None else {}),
776
+ "fsdp": "full_shard" if USE_FSDP else "", # Pass FSDP strategy string (removed offload)
777
+ "fsdp_config": FSDP_CONFIG if USE_FSDP else {}, # Pass FSDP config dict
778
+ "dataloader_num_workers": DATALOADER_NUM_WORKERS,
779
+ "resume_from_checkpoint": "auto",
780
+ "save_strategy": "steps",
781
+ "load_best_model_at_end": False,
782
+ "metric_for_best_model": None,
783
+ "dataset_text_field": "text",
784
+ "packing": False,
785
+ "max_seq_length": MAX_SEQ_LENGTH,
786
+ # Memory/Performance Optimizations
787
+ "gradient_checkpointing_kwargs": {"use_reentrant": False}, # More stable checkpointing for FSDP activation checkpointing
788
+ "ddp_find_unused_parameters": False, # Should be False for FSDP
789
+ "tf32": True, # Enable TF32 for faster compute on compatible GPUs
790
+ }
791
+ training_arguments = SFTConfig(**base_training_args)
792
+ logging.info(f"Rank {rank}: Training arguments (SFTConfig) created.")
793
+
794
+ # --- Define Callbacks ---
795
+
796
+ # Create memory monitoring callback
797
+ class MemoryMonitorCallback(TrainerCallback):
798
+ def on_step_end(self, args, state, control, **kwargs):
799
+ if state.global_step % 10 == 0: # Log every 10 steps
800
+ if torch.cuda.is_available():
801
+ gc.collect()
802
+ torch.cuda.empty_cache()
803
+ rank = int(os.environ.get("RANK", 0))
804
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
805
+ try:
806
+ free_mem, total_mem = torch.cuda.mem_get_info(local_rank)
807
+ free_gb = free_mem / (1024**3)
808
+ used_gb = (total_mem - free_mem) / (1024**3)
809
+ total_gb = total_mem / (1024**3)
810
+ reserved = torch.cuda.memory_reserved(local_rank) / (1024**3)
811
+ allocated = torch.cuda.memory_allocated(local_rank) / (1024**3)
812
+ logging.info(f"Rank {rank}: Memory at step {state.global_step}: "
813
+ f"{free_gb:.1f}GB free, {used_gb:.1f}GB used, {total_gb:.1f}GB total, "
814
+ f"{reserved:.1f}GB reserved, {allocated:.1f}GB allocated")
815
+ except Exception as mem_e:
816
+ logging.warning(f"Rank {rank}: Could not get memory info: {mem_e}")
817
+ return control
818
+
819
+ memory_monitor = MemoryMonitorCallback()
820
+
821
+ # Create a special first step callback with WandB support
822
+ class FirstStepCallback(TrainerCallback):
823
+ def __init__(self):
824
+ self.first_step_start_time = None
825
+ self.progress_indicators = 0
826
+ self.update_interval = 60 # Check every minute
827
+ self.last_update_time = time.time()
828
+
829
+ def on_step_begin(self, args, state, control, **kwargs):
830
+ if state.global_step == 0:
831
+ self.first_step_start_time = time.time()
832
+ logging.info(f"FIRST STEP STARTING at {datetime.now().strftime('%H:%M:%S')}")
833
+ if REPORT_TO_WANDB and 'wandb' in sys.modules:
834
+ try:
835
+ import wandb # Import locally
836
+ if wandb.run:
837
+ wandb.log({"training_status": "first_step_started"})
838
+ except Exception as log_e: logging.warning(f"Wandb log error: {log_e}")
839
+ return control
840
+
841
+ def on_step_end(self, args, state, control, **kwargs):
842
+ if state.global_step == 0:
843
+ if self.first_step_start_time is None: # Should not happen, but safeguard
844
+ logging.warning("First step ended but start time was not recorded.")
845
+ return control
846
+ duration = time.time() - self.first_step_start_time
847
+ logging.info(f"FIRST STEP COMPLETED at {datetime.now().strftime('%H:%M:%S')} (took {duration:.2f} seconds)")
848
+ if REPORT_TO_WANDB and 'wandb' in sys.modules:
849
+ try:
850
+ import wandb # Import locally
851
+ if wandb.run:
852
+ wandb.log({
853
+ "training_status": "first_step_completed",
854
+ "first_step_duration": duration
855
+ })
856
+ except Exception as log_e: logging.warning(f"Wandb log error: {log_e}")
857
+ return control
858
+
859
+ def on_substep_end(self, args, state, control, **kwargs):
860
+ # This tracks progress within a step (during gradient accumulation)
861
+ current_time = time.time()
862
+ # Only report for the first step/substep and only from rank 0
863
+ if (self.first_step_start_time is not None and
864
+ state.global_step == 0 and
865
+ current_time - self.last_update_time >= self.update_interval and
866
+ (not distributed_mode or int(os.environ.get("LOCAL_RANK", 0)) == 0)):
867
+ self.progress_indicators += 1
868
+ elapsed = current_time - self.first_step_start_time
869
+ logging.info(f"First step still in progress... ({elapsed:.1f}s elapsed, progress indicator {self.progress_indicators})")
870
+ if REPORT_TO_WANDB and 'wandb' in sys.modules:
871
+ try:
872
+ import wandb # Import locally
873
+ if wandb.run:
874
+ wandb.log({
875
+ "training_status": "first_step_in_progress",
876
+ "first_step_elapsed": elapsed,
877
+ "progress_indicator": self.progress_indicators
878
+ })
879
+ except Exception as log_e: logging.warning(f"Wandb log error: {log_e}")
880
+ self.last_update_time = current_time
881
+ return control
882
+
883
+ first_step_callback = FirstStepCallback()
884
+
885
+ # Add WandB logging callback if WandB is enabled
886
+ wandb_callback = None # Initialize
887
+ if REPORT_TO_WANDB and 'wandb' in sys.modules and (not distributed_mode or int(os.environ.get("LOCAL_RANK", 0)) == 0):
888
+ try:
889
+ # **** FULL WandBLoggingCallback Class Definition ****
890
+ class WandBLoggingCallback(TrainerCallback):
891
+ """Logs comprehensive training metrics and progress to Weights & Biases"""
892
+
893
+ def __init__(self):
894
+ self.training_start_time = None
895
+ self.last_log_time = None
896
+ self.total_steps = None
897
+ self.samples_seen = 0
898
+ self.tokens_seen = 0
899
+ self.current_epoch = 0
900
+ self.epoch_start_time = None
901
+ self.step_history = [] # For tracking steps/second
902
+ self.global_tokens_per_second = 0
903
+ self.progress_table = None # Initialize table to None
904
+
905
+ def on_train_begin(self, args, state, control, **kwargs):
906
+ """Log hyperparameters and initialize tracking at the start of training"""
907
+ if not (REPORT_TO_WANDB and 'wandb' in sys.modules): return # Check if WandB should be used
908
+
909
+ try:
910
+ import wandb # Import locally
911
+ if not wandb.run:
912
+ logging.warning("WandBCallback: Wandb not initialized in on_train_begin.")
913
+ return
914
+ except ImportError:
915
+ logging.warning("WandBCallback: wandb not imported, cannot log on_train_begin")
916
+ return
917
+
918
+ self.training_start_time = time.time()
919
+ self.epoch_start_time = time.time()
920
+ self.last_log_time = time.time()
921
+
922
+ # Calculate total expected steps
923
+ if args.max_steps > 0:
924
+ self.total_steps = args.max_steps
925
+ else:
926
+ # Use trainer passed in kwargs if available (prioritize 'trainer' key)
927
+ trainer_instance = kwargs.get('trainer', None)
928
+ if trainer_instance is None:
929
+ trainer_instance = kwargs.get('model', None) # Fallback to 'model' key
930
+
931
+ dataset_length = 0
932
+ if trainer_instance and hasattr(trainer_instance, 'train_dataset') and trainer_instance.train_dataset is not None:
933
+ try:
934
+ dataset_length = len(trainer_instance.train_dataset)
935
+ except Exception as len_e:
936
+ logging.warning(f"WandBCallback: Error getting dataset length: {len_e}")
937
+ else:
938
+ logging.warning("WandBCallback: Could not access train_dataset length during on_train_begin.")
939
+
940
+ batch_size = args.per_device_train_batch_size
941
+ accumulation = args.gradient_accumulation_steps
942
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
943
+ global_batch_denom = (batch_size * world_size * accumulation)
944
+ if dataset_length > 0 and global_batch_denom > 0:
945
+ self.total_steps = (dataset_length // global_batch_denom) * args.num_train_epochs
946
+ else:
947
+ self.total_steps = -1 # Indicate unknown total steps
948
+
949
+ # Log key hyperparameters
950
+ config = {
951
+ "model_name": MODEL_ID,
952
+ "lora_r": LORA_R,
953
+ "lora_alpha": LORA_ALPHA,
954
+ "batch_size": PER_DEVICE_TRAIN_BATCH_SIZE,
955
+ "grad_accum": GRADIENT_ACCUMULATION_STEPS,
956
+ "effective_batch": PER_DEVICE_TRAIN_BATCH_SIZE * GRADIENT_ACCUMULATION_STEPS,
957
+ "global_batch": PER_DEVICE_TRAIN_BATCH_SIZE * GRADIENT_ACCUMULATION_STEPS * world_size,
958
+ "learning_rate": LEARNING_RATE,
959
+ "seq_length": MAX_SEQ_LENGTH,
960
+ "epochs": EPOCHS,
961
+ "total_steps_estimated": self.total_steps,
962
+ "optimizer": OPTIMIZER,
963
+ "warmup_ratio": WARMUP_RATIO,
964
+ "scheduler": LR_SCHEDULER_TYPE,
965
+ }
966
+ wandb.config.update(config)
967
+
968
+ # Initialize training progress table
969
+ columns = ["step", "epoch", "loss", "lr", "tokens/sec", "eta", "elapsed_hrs"]
970
+ self.progress_table = wandb.Table(columns=columns)
971
+
972
+ # Log training start
973
+ wandb.log({"training_status": "started"})
974
+ logging.info(f"Training started - total estimated steps: {self.total_steps}")
975
+
976
+ def on_log(self, args, state, control, logs=None, **kwargs):
977
+ """Log detailed metrics and progress after each logging step"""
978
+ if not (REPORT_TO_WANDB and 'wandb' in sys.modules): return # Check if WandB should be used
979
+
980
+ try:
981
+ import wandb # Import locally
982
+ if not wandb.run:
983
+ logging.warning("WandBCallback: Wandb run not active during on_log.")
984
+ return
985
+ except ImportError:
986
+ logging.warning("WandBCallback: wandb not imported, cannot log on_log")
987
+ return
988
+
989
+ if not logs:
990
+ return
991
+
992
+ # Format metrics for logging
993
+ metrics = {}
994
+ for k, v in logs.items():
995
+ if isinstance(v, (int, float)):
996
+ metrics[k] = v
997
+ elif hasattr(v, "item"): # Handle tensors
998
+ try: metrics[k] = v.item()
999
+ except: pass
1000
+
1001
+ if not metrics:
1002
+ return
1003
+
1004
+ # Calculate time-based metrics
1005
+ current_time = time.time()
1006
+ if self.training_start_time is None: self.training_start_time = current_time # Safeguard
1007
+ elapsed_time = current_time - self.training_start_time
1008
+ elapsed_hrs = elapsed_time / 3600
1009
+
1010
+ # Estimate tokens processed
1011
+ batch_size = args.per_device_train_batch_size
1012
+ grad_accum = args.gradient_accumulation_steps
1013
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
1014
+ global_batch_size = batch_size * grad_accum * world_size
1015
+ tokens_per_step = global_batch_size * MAX_SEQ_LENGTH # Use MAX_SEQ_LENGTH from outer scope
1016
+
1017
+ # Update tokens seen
1018
+ steps_since_last = state.global_step - (self.step_history[-1][0] if self.step_history else -1)
1019
+ if steps_since_last <= 0: steps_since_last = 1 # Avoid issues on first log
1020
+ new_tokens = tokens_per_step * steps_since_last
1021
+ self.tokens_seen += new_tokens
1022
+
1023
+ # Calculate throughput
1024
+ time_since_last = current_time - (self.last_log_time if self.last_log_time else current_time)
1025
+ if time_since_last <= 0: time_since_last = 1.0 # Avoid division by zero
1026
+ tokens_per_second = new_tokens / time_since_last
1027
+
1028
+ # Update rolling average of tokens/sec
1029
+ alpha = 0.1
1030
+ self.global_tokens_per_second = alpha * tokens_per_second + (1 - alpha) * self.global_tokens_per_second
1031
+
1032
+ # Track epoch progress
1033
+ if "epoch" in metrics:
1034
+ new_epoch = int(metrics["epoch"])
1035
+ if new_epoch > self.current_epoch:
1036
+ epoch_time = current_time - (self.epoch_start_time if self.epoch_start_time else current_time)
1037
+ self.epoch_start_time = current_time
1038
+ self.current_epoch = new_epoch
1039
+ wandb.log({"epoch/duration_sec": epoch_time}, step=state.global_step)
1040
+ logging.info(f"Epoch {self.current_epoch-1} completed in {epoch_time:.2f} seconds")
1041
+
1042
+ epoch_float = metrics["epoch"]
1043
+ epoch_progress = epoch_float - int(epoch_float)
1044
+ metrics["epoch_progress"] = epoch_progress * 100
1045
+
1046
+ # Estimate time remaining
1047
+ eta_hours = float('nan')
1048
+ if self.total_steps and self.total_steps > 0 and state.global_step > 0:
1049
+ progress_fraction = state.global_step / self.total_steps
1050
+ if progress_fraction > 1e-6: # Avoid division by zero early on
1051
+ eta_seconds = elapsed_time / progress_fraction - elapsed_time
1052
+ eta_hours = eta_seconds / 3600
1053
+ metrics["eta_hours"] = eta_hours
1054
+
1055
+ # Add additional calculated metrics
1056
+ metrics.update({
1057
+ "progress/elapsed_hours": elapsed_hrs,
1058
+ "progress/tokens_total": self.tokens_seen,
1059
+ "performance/tokens_per_second": tokens_per_second,
1060
+ "performance/tokens_per_second_avg": self.global_tokens_per_second,
1061
+ "performance/global_batch_size": global_batch_size,
1062
+ })
1063
+
1064
+ # Add GPU utilization if available
1065
+ if torch.cuda.is_available():
1066
+ try:
1067
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
1068
+ # Note: torch.cuda.utilization might not be available/reliable
1069
+ # metrics["gpu/utilization"] = torch.cuda.utilization(local_rank)
1070
+ metrics["gpu/memory_allocated_gb"] = torch.cuda.memory_allocated(local_rank) / 1e9
1071
+ metrics["gpu/memory_reserved_gb"] = torch.cuda.memory_reserved(local_rank) / 1e9
1072
+ except Exception as gpu_e:
1073
+ logging.debug(f"Could not log GPU metrics: {gpu_e}")
1074
+
1075
+ # Log all metrics to wandb
1076
+ wandb.log(metrics, step=state.global_step)
1077
+
1078
+ # Add row to progress table
1079
+ if self.progress_table is not None:
1080
+ loss_val = metrics.get("loss", float("nan"))
1081
+ lr_val = metrics.get("learning_rate", float("nan"))
1082
+ epoch_val = metrics.get("epoch", 0)
1083
+ tokens_sec = metrics.get("performance/tokens_per_second_avg", 0)
1084
+
1085
+ self.progress_table.add_data(
1086
+ state.global_step,
1087
+ f"{epoch_val:.2f}",
1088
+ f"{loss_val:.4f}",
1089
+ f"{lr_val:.2e}",
1090
+ f"{tokens_sec:.1f}",
1091
+ f"{eta_hours:.1f} hrs",
1092
+ f"{elapsed_hrs:.1f} hrs"
1093
+ )
1094
+ # Log the updated progress table (might be verbose, consider less frequent logging)
1095
+ # wandb.log({"training_progress": self.progress_table}, step=state.global_step)
1096
+
1097
+ # Print concise metrics to console
1098
+ log_info = (
1099
+ f"Step {state.global_step}"
1100
+ + (f"/{self.total_steps} ({100 * state.global_step / self.total_steps:.1f}%)" if self.total_steps and self.total_steps > 0 else "")
1101
+ + f" | Loss: {loss_val:.4f} | LR: {lr_val:.2e} | Epoch: {epoch_val:.2f}"
1102
+ + f" | Tokens/sec: {tokens_sec:.1f}"
1103
+ + (f" | ETA: {eta_hours:.1f}h" if not math.isnan(eta_hours) else "")
1104
+ )
1105
+ logging.info(log_info)
1106
+
1107
+ # Update time tracking
1108
+ self.last_log_time = current_time
1109
+ self.step_history.append((state.global_step, current_time))
1110
+ if len(self.step_history) > 100: # Keep only recent history
1111
+ self.step_history = self.step_history[-100:]
1112
+
1113
+ def on_train_end(self, args, state, control, **kwargs):
1114
+ """Log final statistics at the end of training"""
1115
+ if not (REPORT_TO_WANDB and 'wandb' in sys.modules): return # Check if WandB should be used
1116
+
1117
+ try:
1118
+ import wandb # Import locally
1119
+ if not wandb.run:
1120
+ logging.warning("WandBCallback: Wandb run not active during on_train_end.")
1121
+ return
1122
+ except ImportError:
1123
+ logging.warning("WandBCallback: wandb not imported, cannot log on_train_end")
1124
+ return
1125
+
1126
+ total_time = time.time() - (self.training_start_time if self.training_start_time else time.time())
1127
+ hours = total_time / 3600
1128
+
1129
+ final_stats = {
1130
+ "training_status": "completed",
1131
+ "total_steps_completed": state.global_step,
1132
+ "total_epochs_completed": self.current_epoch,
1133
+ "total_training_time_hours": hours,
1134
+ "total_tokens_processed": self.tokens_seen,
1135
+ "average_tokens_per_second": self.tokens_seen / total_time if total_time > 0 else 0
1136
+ }
1137
+ wandb.log(final_stats, step=state.global_step) # Log at final step
1138
+
1139
+ wandb.run.summary.update({
1140
+ "training_duration_hours": hours,
1141
+ "total_steps": state.global_step,
1142
+ "total_epochs": self.current_epoch,
1143
+ "total_tokens": self.tokens_seen
1144
+ })
1145
+ logging.info(f"Training complete - {hours:.2f} hours, {state.global_step} steps, {self.tokens_seen:,} tokens processed")
1146
+ # **** End of WandBLoggingCallback Definition ****
1147
+
1148
+ # Create callback instance
1149
+ wandb_callback = WandBLoggingCallback()
1150
+ logging.info("Enhanced WandB logging callback created")
1151
+ except Exception as e:
1152
+ logging.error(f"Error creating WandB callback: {str(e)}")
1153
+ wandb_callback = None
1154
+
1155
+ # Create the list of callbacks
1156
+ trainer_callbacks = [memory_monitor, first_step_callback] # Use the instance names
1157
+ if wandb_callback:
1158
+ trainer_callbacks.append(wandb_callback)
1159
+ logging.info("Added WandB callback to trainer")
1160
+ # trainer_callbacks = [] # Temporarily disable all callbacks
1161
+
1162
+ # --- Initialize Trainer ---
1163
+ logging.info(f"Rank {rank}: Initializing SFTTrainer...")
1164
+
1165
+ trainer = None
1166
+ try:
1167
+ trainer = SFTTrainer(
1168
+ model=model,
1169
+ # Using processing_class as per user confirmation
1170
+ processing_class=tokenizer,
1171
+ args=training_arguments,
1172
+ train_dataset=dataset_for_trainer,
1173
+ peft_config=peft_config,
1174
+ # Ensure this matches whether the collator is defined/needed
1175
+ preprocess_logits_for_metrics=None,
1176
+ callbacks=trainer_callbacks, # Pass the list here
1177
+ )
1178
+ logging.info(f"Rank {rank}: SFTTrainer initialized successfully.")
1179
+ except Exception as e:
1180
+ logging.error(f"Rank {rank}: Error initializing SFTTrainer: {e}")
1181
+ import traceback
1182
+ logging.error(traceback.format_exc())
1183
+ if distributed_mode and dist.is_initialized():
1184
+ try: dist.destroy_process_group()
1185
+ except: pass
1186
+ raise
1187
+
1188
+ # --- Train ---
1189
+ if trainer is not None:
1190
+ logging.info(f"Beginning trainer.train() call at {datetime.now().strftime('%H:%M:%S')}")
1191
+ try:
1192
+ trainer.train()
1193
+ logging.info(f"Training finished successfully at {datetime.now().strftime('%H:%M:%S')}")
1194
+ except Exception as e:
1195
+ logging.error(f"Exception during training: {e}")
1196
+ import traceback
1197
+ logging.error(traceback.format_exc())
1198
+ if distributed_mode and dist.is_initialized():
1199
+ try:
1200
+ dist.destroy_process_group()
1201
+ logging.info("Destroyed process group after training error")
1202
+ except:
1203
+ pass
1204
+ raise
1205
+
1206
+ # --- Merge Model and Save Full Model ---
1207
+ logging.info("Merging adapter weights into base model...")
1208
+
1209
+ # Clear some memory first if needed (especially if not using massive GPUs)
1210
+ # del model
1211
+ # del trainer
1212
+ # torch.cuda.empty_cache()
1213
+
1214
+ # Reload the base model (consider lower precision to save VRAM during merge)
1215
+ logging.info(f"Reloading base model ({MODEL_ID}) for merging...")
1216
+ base_model = AutoModelForCausalLM.from_pretrained(
1217
+ MODEL_ID,
1218
+ config=config, # Ensure YaRN config is used if applied during training
1219
+ torch_dtype=torch.bfloat16, # Or torch.float16, adjust as needed
1220
+ low_cpu_mem_usage=True, # Helps with large models
1221
+ trust_remote_code=True,
1222
+ device_map=None, # Load onto CPU first to potentially save GPU VRAM if needed
1223
+ attn_implementation="flash_attention_2"
1224
+ )
1225
+
1226
+ # Load the PEFT model with adapters
1227
+ logging.info(f"Loading PEFT model from {OUTPUT_DIR}...")
1228
+ merged_model = PeftModel.from_pretrained(
1229
+ base_model,
1230
+ OUTPUT_DIR,
1231
+ device_map=None, # Load onto CPU first
1232
+ )
1233
+
1234
+ # Merge the adapter weights
1235
+ logging.info("Merging LoRA weights...")
1236
+ merged_model = merged_model.merge_and_unload()
1237
+ logging.info("LoRA weights merged.")
1238
+
1239
+ # Define path for the full model save
1240
+ full_model_save_path = os.path.join(OUTPUT_DIR, "final_merged_model")
1241
+
1242
+ # Save the merged model
1243
+ logging.info(f"Saving merged model to {full_model_save_path}...")
1244
+ merged_model.save_pretrained(full_model_save_path)
1245
+ logging.info("Merged model saved.")
1246
+
1247
+ # Save the tokenizer associated with the merged model
1248
+ logging.info(f"Saving tokenizer to {full_model_save_path}...")
1249
+ tokenizer.save_pretrained(full_model_save_path)
1250
+ logging.info("Tokenizer saved.")
1251
+
1252
+ logging.info(f"Fine-tuning and merging process complete. Full model saved to {full_model_save_path}")
1253
+
1254
+ # --- Notes on Inference and Resuming Training ---
1255
+ logging.info("Training Checkpoint Notes:")
1256
+ logging.info(f" • Checkpoints saved to: {OUTPUT_DIR}")
1257
+ logging.info(f" • To resume training from the latest checkpoint, just rerun this script")
1258
+ logging.info(f" (resume_from_checkpoint='auto' will automatically find the latest checkpoint)")
1259
+ logging.info(f" • To resume from a specific checkpoint, set resume_from_checkpoint='path/to/checkpoint'")
1260
+
1261
+ # --- Notes on Inference ---
1262
+ # To use the trained adapters:
1263
+ # from peft import PeftModel
1264
+ # base_model = AutoModelForCausalLM.from_pretrained(MODEL_ID, ...)
1265
+ # model = PeftModel.from_pretrained(base_model, final_adapter_path)
1266
+ # model = model.merge_and_unload() # Optional: merge adapters for faster inference
1267
+ # Then use model and tokenizer for generation.
layer_influence.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Measure per-layer causal influence via gating and/or swapping.
4
+ # Mapping fix: correctly map composite layer indices to donor indices.
5
+
6
+ import argparse
7
+ import math
8
+ from contextlib import contextmanager
9
+ from dataclasses import dataclass
10
+ from typing import Dict, List, Optional, Tuple
11
+
12
+ import torch
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer
14
+
15
+
16
+ def parse_layers(spec: str) -> List[int]:
17
+ out: List[int] = []
18
+ for chunk in spec.split(","):
19
+ chunk = chunk.strip()
20
+ if not chunk:
21
+ continue
22
+ if "-" in chunk:
23
+ a, b = chunk.split("-")
24
+ a, b = int(a), int(b)
25
+ out.extend(list(range(a, b + 1)))
26
+ else:
27
+ out.append(int(chunk))
28
+ out = sorted(list({x for x in out}))
29
+ return out
30
+
31
+
32
+ def load_lines(
33
+ prompts: Optional[str], prompts_file: Optional[str]
34
+ ) -> List[str]:
35
+ lines: List[str] = []
36
+ if prompts_file:
37
+ with open(prompts_file, "r", encoding="utf-8") as f:
38
+ for line in f:
39
+ s = line.strip("\n")
40
+ if s:
41
+ lines.append(s)
42
+ if prompts:
43
+ for s in prompts.split("\n"):
44
+ s = s.strip()
45
+ if s:
46
+ lines.append(s)
47
+ if not lines:
48
+ lines = [
49
+ "You are a helpful assistant. Say hi in one sentence.",
50
+ "Explain transformers in 2-3 sentences.",
51
+ "Summarize the benefits of bfloat16 training.",
52
+ ]
53
+ return lines
54
+
55
+
56
+ def get_embed_device(model: torch.nn.Module) -> torch.device:
57
+ return model.get_input_embeddings().weight.device
58
+
59
+
60
+ @torch.inference_mode()
61
+ def dataset_nll(
62
+ model: AutoModelForCausalLM,
63
+ tok: AutoTokenizer,
64
+ texts: List[str],
65
+ max_length: int = 512,
66
+ batch_size: int = 4,
67
+ input_device: Optional[torch.device] = None,
68
+ ) -> Tuple[float, int]:
69
+ if input_device is None:
70
+ input_device = get_embed_device(model)
71
+
72
+ total_nll = 0.0
73
+ total_tokens = 0
74
+
75
+ i = 0
76
+ while i < len(texts):
77
+ batch = texts[i : i + batch_size]
78
+ i += batch_size
79
+
80
+ enc = tok(
81
+ batch,
82
+ return_tensors="pt",
83
+ padding=True,
84
+ truncation=True,
85
+ max_length=max_length,
86
+ )
87
+ for k in enc:
88
+ enc[k] = enc[k].to(input_device)
89
+
90
+ input_ids = enc["input_ids"]
91
+ attention_mask = enc["attention_mask"]
92
+ labels = input_ids.clone()
93
+ labels[labels == tok.pad_token_id] = -100
94
+
95
+ out = model(
96
+ input_ids=input_ids,
97
+ attention_mask=attention_mask,
98
+ labels=labels,
99
+ use_cache=False,
100
+ )
101
+ loss = out.loss
102
+ valid = labels.ne(-100)
103
+ n_tokens = int(valid.sum().item())
104
+ total_nll += float(loss.item()) * n_tokens
105
+ total_tokens += n_tokens
106
+
107
+ return total_nll, total_tokens
108
+
109
+
110
+ def ppl_from_nll(total_nll: float, total_tokens: int) -> float:
111
+ if total_tokens == 0:
112
+ return float("inf")
113
+ return float(math.exp(total_nll / total_tokens))
114
+
115
+
116
+ @dataclass
117
+ class GateSpec:
118
+ layer: int
119
+ attn_scale: float = 0.0
120
+ mlp_scale: float = 0.0
121
+
122
+
123
+ @contextmanager
124
+ def gate_layer(model: AutoModelForCausalLM, spec: GateSpec):
125
+ """
126
+ Temporarily scale a layer's residual contribution by scaling:
127
+ - self_attn.o_proj.weight by attn_scale
128
+ - mlp.down_proj.weight by mlp_scale
129
+ Using 0.0 disables that sublayer's residual addition.
130
+ """
131
+ backups: List[Tuple[torch.nn.Parameter, torch.Tensor]] = []
132
+
133
+ def scale_param(p: torch.nn.Parameter, s: float):
134
+ backups.append((p, p.data.detach().clone()))
135
+ p.data.mul_(s)
136
+
137
+ layer = model.model.layers[spec.layer] # type: ignore[attr-defined]
138
+
139
+ try:
140
+ if hasattr(layer.self_attn, "o_proj"):
141
+ scale_param(layer.self_attn.o_proj.weight, spec.attn_scale)
142
+ else:
143
+ raise AttributeError("No o_proj in self_attn")
144
+
145
+ if hasattr(layer.mlp, "down_proj"):
146
+ scale_param(layer.mlp.down_proj.weight, spec.mlp_scale)
147
+ else:
148
+ raise AttributeError("No down_proj in mlp")
149
+
150
+ yield
151
+ finally:
152
+ for p, old in backups:
153
+ p.data.copy_(old)
154
+ backups.clear()
155
+
156
+
157
+ @contextmanager
158
+ def swap_layer_from_donor(
159
+ model_dst: AutoModelForCausalLM,
160
+ model_src: AutoModelForCausalLM,
161
+ dst_layer_idx: int,
162
+ src_layer_idx: int,
163
+ ):
164
+ """
165
+ Temporarily copy all parameters/buffers for dst_layer_idx from
166
+ model_src's src_layer_idx, then restore.
167
+ """
168
+ dst_prefix = f"model.layers.{dst_layer_idx}."
169
+ src_prefix = f"model.layers.{src_layer_idx}."
170
+
171
+ src_named_params = dict(model_src.named_parameters())
172
+ dst_named_params = dict(model_dst.named_parameters())
173
+ src_named_bufs = dict(model_src.named_buffers())
174
+ dst_named_bufs = dict(model_dst.named_buffers())
175
+
176
+ src_params_by_suffix: Dict[str, torch.Tensor] = {}
177
+ for name, p in src_named_params.items():
178
+ if name.startswith(src_prefix):
179
+ suffix = name[len(src_prefix) :]
180
+ src_params_by_suffix[suffix] = p
181
+
182
+ src_bufs_by_suffix: Dict[str, torch.Tensor] = {}
183
+ for name, b in src_named_bufs.items():
184
+ if name.startswith(src_prefix):
185
+ suffix = name[len(src_prefix) :]
186
+ src_bufs_by_suffix[suffix] = b
187
+
188
+ backups_p: List[Tuple[str, torch.Tensor]] = []
189
+ backups_b: List[Tuple[str, torch.Tensor]] = []
190
+
191
+ try:
192
+ with torch.no_grad():
193
+ for name, p_dst in list(dst_named_params.items()):
194
+ if not name.startswith(dst_prefix):
195
+ continue
196
+ suffix = name[len(dst_prefix) :]
197
+ if suffix not in src_params_by_suffix:
198
+ continue
199
+ p_src = src_params_by_suffix[suffix]
200
+ backups_p.append((name, p_dst.data.detach().clone()))
201
+ p_dst.data.copy_(
202
+ p_src.data.to(device=p_dst.device, dtype=p_dst.dtype)
203
+ )
204
+ for name, b_dst in list(dst_named_bufs.items()):
205
+ if not name.startswith(dst_prefix):
206
+ continue
207
+ suffix = name[len(dst_prefix) :]
208
+ if suffix not in src_bufs_by_suffix:
209
+ continue
210
+ b_src = src_bufs_by_suffix[suffix]
211
+ backups_b.append((name, b_dst.data.detach().clone()))
212
+ b_dst.data.copy_(
213
+ b_src.data.to(device=b_dst.device, dtype=b_dst.dtype)
214
+ )
215
+ yield
216
+ finally:
217
+ with torch.no_grad():
218
+ for name, old in backups_p:
219
+ p_dst = dst_named_params[name]
220
+ p_dst.data.copy_(old)
221
+ for name, old in backups_b:
222
+ b_dst = dst_named_bufs[name]
223
+ b_dst.data.copy_(old)
224
+
225
+
226
+ def map_layer_idx(
227
+ dst_idx: int, dst_total: int, src_total: int, mode: str = "ratio"
228
+ ) -> int:
229
+ """
230
+ Map a composite (dst) layer index to donor (src) layer index.
231
+
232
+ - ratio (default): floor(dst_idx * src_total / dst_total)
233
+ - wrap: dst_idx % src_total
234
+ """
235
+ if src_total <= 0:
236
+ raise ValueError("src_total must be > 0")
237
+ if mode == "wrap":
238
+ return dst_idx % src_total
239
+ x = int(math.floor(dst_idx * src_total / max(1, dst_total)))
240
+ return max(0, min(src_total - 1, x))
241
+
242
+
243
+ def main():
244
+ ap = argparse.ArgumentParser(
245
+ description="Per-layer influence via gating and/or swapping."
246
+ )
247
+ ap.add_argument("--model", type=str, required=True)
248
+ ap.add_argument("--donor_model", type=str)
249
+ ap.add_argument("--layers", type=str, required=True)
250
+ ap.add_argument("--prompts", type=str)
251
+ ap.add_argument("--prompts_file", type=str)
252
+ ap.add_argument("--max_length", type=int, default=512)
253
+ ap.add_argument("--batch_size", type=int, default=4)
254
+ ap.add_argument(
255
+ "--dtype",
256
+ type=str,
257
+ default="bfloat16",
258
+ choices=["bfloat16", "float16", "float32"],
259
+ )
260
+ ap.add_argument("--device_map", type=str, default="auto")
261
+ ap.add_argument("--gate_scan", action="store_true")
262
+ ap.add_argument("--swap_scan", action="store_true")
263
+ ap.add_argument("--attn_only", action="store_true")
264
+ ap.add_argument("--mlp_only", action="store_true")
265
+ ap.add_argument(
266
+ "--swap_map", type=str, default="ratio", choices=["ratio", "wrap"]
267
+ )
268
+ args = ap.parse_args()
269
+
270
+ dtype_map = {
271
+ "bfloat16": torch.bfloat16,
272
+ "float16": torch.float16,
273
+ "float32": torch.float32,
274
+ }
275
+ torch_dtype = dtype_map[args.dtype]
276
+
277
+ layers = parse_layers(args.layers)
278
+ texts = load_lines(args.prompts, args.prompts_file)
279
+
280
+ print(f"Loading model: {args.model}")
281
+ tok = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
282
+ model = AutoModelForCausalLM.from_pretrained(
283
+ args.model,
284
+ torch_dtype=torch_dtype,
285
+ trust_remote_code=True,
286
+ device_map=args.device_map,
287
+ ).eval()
288
+
289
+ final_layers = int(
290
+ getattr(model.config, "num_hidden_layers", len(model.model.layers))
291
+ )
292
+ print(f"Composite num_hidden_layers: {final_layers}")
293
+
294
+ print("Computing baseline NLL/PPL...")
295
+ base_nll, base_tokens = dataset_nll(
296
+ model,
297
+ tok,
298
+ texts,
299
+ max_length=args.max_length,
300
+ batch_size=args.batch_size,
301
+ input_device=get_embed_device(model),
302
+ )
303
+ base_ppl = ppl_from_nll(base_nll, base_tokens)
304
+ print(f"Baseline: tokens={base_tokens} NLL={base_nll:.3f} PPL={base_ppl:.3f}")
305
+
306
+ if args.gate_scan:
307
+ print("\n== Gate scan (disable residual contribution per layer) ==")
308
+ a_scale = 0.0 if not args.mlp_only else 1.0
309
+ m_scale = 0.0 if not args.attn_only else 1.0
310
+
311
+ results: List[Tuple[int, float, float]] = []
312
+ for L in layers:
313
+ spec = GateSpec(layer=L, attn_scale=a_scale, mlp_scale=m_scale)
314
+ with gate_layer(model, spec):
315
+ nll, ntok = dataset_nll(
316
+ model,
317
+ tok,
318
+ texts,
319
+ max_length=args.max_length,
320
+ batch_size=args.batch_size,
321
+ input_device=get_embed_device(model),
322
+ )
323
+ ppl = ppl_from_nll(nll, ntok)
324
+ delta_nll = nll - base_nll
325
+ delta_ppl = ppl - base_ppl
326
+ results.append((L, delta_nll, delta_ppl))
327
+ print(
328
+ f"Layer {L:>3}: ΔNLL={delta_nll:+.3f} ΔPPL={delta_ppl:+.3f} "
329
+ f"(NLL={nll:.3f}, PPL={ppl:.3f})"
330
+ )
331
+
332
+ if args.swap_scan:
333
+ if not args.donor_model:
334
+ raise ValueError("--swap_scan requires --donor_model.")
335
+ print(f"\nLoading donor model: {args.donor_model}")
336
+ donor = AutoModelForCausalLM.from_pretrained(
337
+ args.donor_model,
338
+ torch_dtype=torch_dtype,
339
+ trust_remote_code=True,
340
+ device_map="cpu",
341
+ ).eval()
342
+ donor_layers = int(
343
+ getattr(donor.config, "num_hidden_layers", len(donor.model.layers))
344
+ )
345
+ print(
346
+ f"Donor num_hidden_layers: {donor_layers} "
347
+ f"(mapping mode: {args.swap_map})"
348
+ )
349
+
350
+ print("\n== Swap scan (replace composite layer with donor-mapped) ==")
351
+ results_s: List[Tuple[int, int, float, float]] = []
352
+ for L in layers:
353
+ src_L = map_layer_idx(L, final_layers, donor_layers, mode=args.swap_map)
354
+ with swap_layer_from_donor(model, donor, L, src_L):
355
+ nll, ntok = dataset_nll(
356
+ model,
357
+ tok,
358
+ texts,
359
+ max_length=args.max_length,
360
+ batch_size=args.batch_size,
361
+ input_device=get_embed_device(model),
362
+ )
363
+ ppl = ppl_from_nll(nll, ntok)
364
+ delta_nll = nll - base_nll
365
+ delta_ppl = ppl - base_ppl
366
+ results_s.append((L, src_L, delta_nll, delta_ppl))
367
+ print(
368
+ f"Layer {L:>3} <- donor {src_L:>2}: "
369
+ f"ΔNLL={delta_nll:+.3f} ΔPPL={delta_ppl:+.3f} "
370
+ f"(NLL={nll:.3f}, PPL={ppl:.3f})"
371
+ )
372
+
373
+
374
+ if __name__ == "__main__":
375
+ main()
layer_surgery.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Layer surgery on safetensors shards:
4
+ # - Replace selected transformer blocks with donor blocks
5
+ # - Optionally rescale specific projections per layer
6
+ #
7
+ # Example:
8
+ # python layer_surgery.py \
9
+ # --composite ./qwen3-8b-plus-moe-64L \
10
+ # --base Qwen/Qwen3-8B \
11
+ # --out ./qwen3-8b-plus-moe-64L-surgery \
12
+ # --replace_layers 61 \
13
+ # --map ratio
14
+
15
+ import argparse
16
+ import glob
17
+ import json
18
+ import math
19
+ import os
20
+ import shutil
21
+ from pathlib import Path
22
+ from typing import Dict, List, Optional, Tuple
23
+
24
+ import torch
25
+ from safetensors import safe_open
26
+ from safetensors.torch import save_file
27
+ from huggingface_hub import snapshot_download
28
+
29
+
30
+ def read_json(p: str) -> Dict:
31
+ with open(p, "r") as f:
32
+ return json.load(f)
33
+
34
+
35
+ def write_json(p: Path, data: Dict):
36
+ with open(p, "w") as f:
37
+ json.dump(data, f, indent=2)
38
+
39
+
40
+ def ensure_local(model_or_path: str) -> str:
41
+ if os.path.isdir(model_or_path):
42
+ return model_or_path
43
+ print(f"Downloading {model_or_path} ...")
44
+ return snapshot_download(
45
+ model_or_path, cache_dir="./model_cache", resume_download=True
46
+ )
47
+
48
+
49
+ def index_dir(model_dir: str) -> Tuple[Dict[str, str], List[str]]:
50
+ idx_path = os.path.join(model_dir, "model.safetensors.index.json")
51
+ weight_map: Dict[str, str] = {}
52
+ files: List[str] = []
53
+ if os.path.exists(idx_path):
54
+ idx = read_json(idx_path)
55
+ weight_map = idx.get("weight_map", {})
56
+ files = sorted(list({os.path.join(model_dir, f) for f in weight_map.values()}))
57
+ return weight_map, files
58
+
59
+ st_files = glob.glob(os.path.join(model_dir, "*.safetensors"))
60
+ if not st_files:
61
+ raise FileNotFoundError(f"No .safetensors found in {model_dir}")
62
+ for fpath in st_files:
63
+ with safe_open(fpath, framework="pt") as f:
64
+ for k in f.keys():
65
+ weight_map[k] = os.path.basename(fpath)
66
+ files = sorted(st_files)
67
+ return weight_map, files
68
+
69
+
70
+ def parse_layers(spec: str) -> List[int]:
71
+ out: List[int] = []
72
+ for chunk in spec.split(","):
73
+ chunk = chunk.strip()
74
+ if not chunk:
75
+ continue
76
+ if "-" in chunk:
77
+ a, b = chunk.split("-")
78
+ a, b = int(a), int(b)
79
+ out.extend(list(range(a, b + 1)))
80
+ else:
81
+ out.append(int(chunk))
82
+ return sorted(list({x for x in out}))
83
+
84
+
85
+ def layer_prefix(li: int) -> str:
86
+ return f"model.layers.{li}."
87
+
88
+
89
+ def map_layer(dst_idx: int, dst_total: int, src_total: int, mode: str) -> int:
90
+ if src_total <= 0:
91
+ raise ValueError("src_total must be > 0")
92
+ if mode == "wrap":
93
+ return dst_idx % src_total
94
+ x = int(math.floor(dst_idx * src_total / max(1, dst_total)))
95
+ return max(0, min(src_total - 1, x))
96
+
97
+
98
+ def build_explicit_map(pairs: Optional[str]) -> Dict[int, int]:
99
+ m: Dict[int, int] = {}
100
+ if not pairs:
101
+ return m
102
+ for token in pairs.split(","):
103
+ token = token.strip()
104
+ if not token:
105
+ continue
106
+ a, b = token.split(":")
107
+ m[int(a)] = int(b)
108
+ return m
109
+
110
+
111
+ SCALE_KEYS = {
112
+ "attn_q": ".self_attn.q_proj.weight",
113
+ "attn_k": ".self_attn.k_proj.weight",
114
+ "attn_v": ".self_attn.v_proj.weight",
115
+ "attn_o": ".self_attn.o_proj.weight",
116
+ "mlp_up": ".mlp.up_proj.weight",
117
+ "mlp_gate": ".mlp.gate_proj.weight",
118
+ "mlp_down": ".mlp.down_proj.weight",
119
+ }
120
+
121
+
122
+ def load_scales(scale_json: Optional[str]) -> Dict[int, Dict[str, float]]:
123
+ if not scale_json:
124
+ return {}
125
+ data = read_json(scale_json)
126
+ out: Dict[int, Dict[str, float]] = {}
127
+ for k, v in data.items():
128
+ li = int(k)
129
+ out[li] = {}
130
+ for mk, sf in v.items():
131
+ if mk not in SCALE_KEYS:
132
+ raise ValueError(f"Unknown scale key '{mk}'. Valid: {list(SCALE_KEYS)}")
133
+ out[li][mk] = float(sf)
134
+ return out
135
+
136
+
137
+ def tensor_layer_idx(tensor_name: str) -> Optional[int]:
138
+ parts = tensor_name.split(".")
139
+ if len(parts) > 3 and parts[0] == "model" and parts[1] == "layers":
140
+ try:
141
+ return int(parts[2])
142
+ except Exception:
143
+ return None
144
+ return None
145
+
146
+
147
+ def apply_scales_if_needed(
148
+ tname: str, tensor: torch.Tensor, li: int, scales: Dict[int, Dict[str, float]]
149
+ ) -> torch.Tensor:
150
+ if li not in scales:
151
+ return tensor
152
+ spec = scales[li]
153
+ for key, suffix in SCALE_KEYS.items():
154
+ if key in spec and tname.endswith(suffix):
155
+ s = spec[key]
156
+ return (tensor * tensor.new_tensor(s)).contiguous()
157
+ return tensor
158
+
159
+
160
+ def main():
161
+ ap = argparse.ArgumentParser(
162
+ description="Layer surgery on safetensors: replace and/or rescale layers."
163
+ )
164
+ ap.add_argument("--composite", type=str, required=True)
165
+ ap.add_argument("--base", type=str, help="Donor model dir or HF ID")
166
+ ap.add_argument("--out", type=str, required=True)
167
+ ap.add_argument("--replace_layers", type=str, help='e.g. "61" or "48-55,60,62"')
168
+ ap.add_argument(
169
+ "--map", type=str, default="ratio", choices=["ratio", "wrap"]
170
+ )
171
+ ap.add_argument("--map_pairs", type=str, help='e.g. "61:34,55:30"')
172
+ ap.add_argument("--scale_json", type=str)
173
+ args = ap.parse_args()
174
+
175
+ comp_dir = ensure_local(args.composite)
176
+ out_dir = Path(args.out)
177
+ out_dir.mkdir(parents=True, exist_ok=True)
178
+
179
+ comp_cfg = read_json(os.path.join(comp_dir, "config.json"))
180
+ L_comp = int(comp_cfg.get("num_hidden_layers"))
181
+ print(f"Composite layers: {L_comp}")
182
+
183
+ replace_set: List[int] = []
184
+ if args.replace_layers:
185
+ replace_set = parse_layers(args.replace_layers)
186
+ if not args.base:
187
+ raise ValueError("--base is required when --replace_layers is set.")
188
+ base_dir = ensure_local(args.base)
189
+ base_cfg = read_json(os.path.join(base_dir, "config.json"))
190
+ L_base = int(base_cfg.get("num_hidden_layers"))
191
+ print(f"Donor layers: {L_base}")
192
+ explicit = build_explicit_map(args.map_pairs)
193
+ else:
194
+ base_dir = ""
195
+ L_base = 0
196
+ explicit = {}
197
+
198
+ comp_map, comp_files = index_dir(comp_dir)
199
+ if replace_set:
200
+ base_map, base_files = index_dir(base_dir)
201
+ else:
202
+ base_map, base_files = {}, []
203
+
204
+ scales = load_scales(args.scale_json)
205
+ if scales:
206
+ print("Scales loaded for layers:", sorted(scales.keys()))
207
+
208
+ to_copy = [
209
+ "config.json",
210
+ "tokenizer.json",
211
+ "tokenizer_config.json",
212
+ "special_tokens_map.json",
213
+ "vocab.json",
214
+ "merges.txt",
215
+ "tokenizer.model",
216
+ "generation_config.json",
217
+ ]
218
+ for fname in to_copy:
219
+ src = os.path.join(comp_dir, fname)
220
+ if os.path.exists(src):
221
+ shutil.copy2(src, out_dir / fname)
222
+
223
+ print("Performing surgery shard-by-shard...")
224
+ out_weight_map: Dict[str, str] = {}
225
+ for comp_f in comp_files:
226
+ rel = os.path.basename(comp_f)
227
+ out_f = out_dir / rel
228
+ new_tensors: Dict[str, torch.Tensor] = {}
229
+
230
+ with safe_open(comp_f, framework="pt") as fcomp:
231
+ keys = list(fcomp.keys())
232
+ for k in keys:
233
+ li = tensor_layer_idx(k)
234
+ tensor = None
235
+
236
+ if li is not None and li in replace_set:
237
+ if li in explicit:
238
+ src_li = explicit[li]
239
+ else:
240
+ src_li = map_layer(li, L_comp, L_base, args.map)
241
+ src_prefix = layer_prefix(src_li)
242
+ dst_prefix = layer_prefix(li)
243
+ donor_k = src_prefix + k[len(dst_prefix) :]
244
+
245
+ donor_file = base_map.get(donor_k)
246
+ if donor_file is None:
247
+ raise KeyError(f"Donor tensor not found: {donor_k}")
248
+ donor_path = os.path.join(base_dir, donor_file)
249
+ with safe_open(donor_path, framework="pt") as fbase:
250
+ tensor = fbase.get_tensor(donor_k)
251
+ else:
252
+ tensor = fcomp.get_tensor(k)
253
+
254
+ if li is not None:
255
+ tensor = apply_scales_if_needed(k, tensor, li, scales)
256
+
257
+ if not tensor.is_contiguous():
258
+ tensor = tensor.contiguous()
259
+ new_tensors[k] = tensor
260
+ out_weight_map[k] = rel
261
+
262
+ save_file(new_tensors, str(out_f))
263
+
264
+ total_size = 0
265
+ for fname in set(out_weight_map.values()):
266
+ fp = out_dir / fname
267
+ if fp.exists():
268
+ total_size += fp.stat().st_size
269
+ index = {"metadata": {"total_size": total_size, "format": "safetensors"}, "weight_map": out_weight_map}
270
+ write_json(out_dir / "model.safetensors.index.json", index)
271
+ print(f"Done. Wrote modified shards and index to: {out_dir}")
272
+
273
+ print("\nTip: validate load quickly (meta device):")
274
+ print(f" from transformers import AutoModelForCausalLM")
275
+ print(f" AutoModelForCausalLM.from_pretrained('{str(out_dir)}', device_map='meta', trust_remote_code=True)")
276
+
277
+
278
+ if __name__ == "__main__":
279
+ main()
moe_to_dense.py ADDED
@@ -0,0 +1,1097 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert Qwen3 MoE model to dense format with target model compatibility,
4
+ then optionally build a larger composite model by interleaving layers
5
+ with a base dense model (e.g., Qwen3-8B).
6
+
7
+ Usage (MoE -> dense):
8
+ python moe_to_dense.py \
9
+ --model_id Qwen/Qwen3-235B-A22B-Instruct-2507 \
10
+ --target_model Qwen/Qwen3-8B \
11
+ --output_path ./qwen3-235b-dense-avg \
12
+ --method average \
13
+ --low_memory
14
+
15
+ Usage (build larger composite by interleaving):
16
+ python moe_to_dense.py \
17
+ --compose_interleaved \
18
+ --base_model Qwen/Qwen3-8B \
19
+ --moe_converted ./qwen3-235b-dense-avg \
20
+ --composite_output_path ./qwen3-8b-plus-moe-64L \
21
+ --final_layers 64 \
22
+ --interleave_strategy even \
23
+ --cast_dtype bfloat16
24
+
25
+ Validate load (meta device, no allocations):
26
+ python moe_to_dense.py \
27
+ --validate_model ./qwen3-8b-plus-moe-64L
28
+ """
29
+
30
+ import os
31
+ import json
32
+ import torch
33
+ import argparse
34
+ from pathlib import Path
35
+ from typing import Dict, Any, Optional, List, Tuple
36
+ from tqdm import tqdm
37
+ import logging
38
+ from safetensors import safe_open
39
+ from safetensors.torch import save_file
40
+ import glob
41
+ from huggingface_hub import snapshot_download
42
+ import shutil
43
+ import gc
44
+ import math
45
+
46
+ logging.basicConfig(level=logging.INFO)
47
+ logger = logging.getLogger(__name__)
48
+
49
+
50
+ def read_json(path: str) -> Dict[str, Any]:
51
+ with open(path, "r") as f:
52
+ return json.load(f)
53
+
54
+
55
+ def write_json(path: Path, data: Dict[str, Any]):
56
+ with open(path, "w") as f:
57
+ json.dump(data, f, indent=2)
58
+
59
+
60
+ def cast_tensor_dtype(t: torch.Tensor, cast: Optional[str]) -> torch.Tensor:
61
+ if cast is None:
62
+ return t
63
+ target = {
64
+ "float32": torch.float32,
65
+ "fp32": torch.float32,
66
+ "float16": torch.float16,
67
+ "fp16": torch.float16,
68
+ "bfloat16": torch.bfloat16,
69
+ "bf16": torch.bfloat16,
70
+ }[cast.lower()]
71
+ if t.dtype == target:
72
+ return t
73
+ return t.to(dtype=target)
74
+
75
+
76
+ class MoEToDenseConverter:
77
+ def __init__(
78
+ self,
79
+ model_path: str,
80
+ target_model_path: str,
81
+ output_path: str,
82
+ method: str = "average",
83
+ low_memory: bool = False,
84
+ ):
85
+ """
86
+ Initialize the converter with target model compatibility.
87
+
88
+ Args:
89
+ model_path: Path to MoE model or HuggingFace model ID
90
+ target_model_path: Path to target dense model for dimension matching
91
+ output_path: Where to save the converted dense model
92
+ method: How to handle experts:
93
+ - "concat_experts": Concatenate experts per projection
94
+ - "average": Average experts per projection (recommended)
95
+ - "first": Use first expert
96
+ low_memory: Process per-shard with minimal RAM
97
+ """
98
+ self.model_path = model_path
99
+ self.target_model_path = target_model_path
100
+ self.output_path = Path(output_path)
101
+ self.method = method
102
+ self.low_memory = low_memory
103
+ self.output_path.mkdir(parents=True, exist_ok=True)
104
+
105
+ # Will be set in load_config
106
+ self.source_config: Optional[Dict[str, Any]] = None
107
+
108
+ # Load target model config for dimension matching
109
+ self.target_config = self.load_target_config()
110
+
111
+ def load_target_config(self) -> Dict[str, Any]:
112
+ if not os.path.exists(self.target_model_path):
113
+ logger.info(f"Downloading target model {self.target_model_path}...")
114
+ self.target_model_path = snapshot_download(
115
+ self.target_model_path,
116
+ cache_dir="./model_cache",
117
+ allow_patterns=["config.json"],
118
+ )
119
+
120
+ config_path = os.path.join(self.target_model_path, "config.json")
121
+ config = read_json(config_path)
122
+
123
+ logger.info("Target model dimensions:")
124
+ logger.info(f" hidden_size: {config.get('hidden_size')}")
125
+ logger.info(f" intermediate_size: {config.get('intermediate_size')}")
126
+ logger.info(
127
+ f" num_attention_heads: {config.get('num_attention_heads')}"
128
+ )
129
+ logger.info(
130
+ f" num_key_value_heads: {config.get('num_key_value_heads')}"
131
+ )
132
+
133
+ return config
134
+
135
+ def download_model_if_needed(self):
136
+ if not os.path.exists(self.model_path):
137
+ logger.info(
138
+ f"Downloading model {self.model_path} from HuggingFace..."
139
+ )
140
+ self.model_path = snapshot_download(
141
+ self.model_path,
142
+ cache_dir="./model_cache",
143
+ resume_download=True,
144
+ )
145
+ return self.model_path
146
+
147
+ def load_config(self) -> Dict[str, Any]:
148
+ config_path = os.path.join(self.model_path, "config.json")
149
+ source_cfg = read_json(config_path)
150
+ self.source_config = dict(source_cfg)
151
+
152
+ logger.info(
153
+ f"Source MoE architecture: "
154
+ f"{source_cfg.get('architectures', ['Unknown'])}"
155
+ )
156
+ logger.info(f" num_experts: {source_cfg.get('num_experts')}")
157
+ logger.info(
158
+ f" moe_intermediate_size: "
159
+ f"{source_cfg.get('moe_intermediate_size')}"
160
+ )
161
+
162
+ cfg = dict(source_cfg)
163
+ if "Qwen3MoeForCausalLM" in cfg.get("architectures", []):
164
+ cfg["architectures"] = ["Qwen3ForCausalLM"]
165
+
166
+ cfg["hidden_size"] = self.target_config["hidden_size"]
167
+ cfg["intermediate_size"] = self.target_config["intermediate_size"]
168
+ cfg["num_attention_heads"] = self.target_config["num_attention_heads"]
169
+ cfg["num_key_value_heads"] = self.target_config["num_key_value_heads"]
170
+
171
+ moe_params = [
172
+ "num_experts",
173
+ "num_experts_per_tok",
174
+ "moe_intermediate_size",
175
+ "decoder_sparse_step",
176
+ "norm_topk_prob",
177
+ "output_router_logits",
178
+ "router_aux_loss_coef",
179
+ "mlp_only_layers",
180
+ ]
181
+ for param in moe_params:
182
+ if param in cfg:
183
+ del cfg[param]
184
+
185
+ if cfg.get("model_type") == "qwen3_moe":
186
+ cfg["model_type"] = "qwen3"
187
+
188
+ return cfg
189
+
190
+ @staticmethod
191
+ def _pad_trunc_rows(t: torch.Tensor, rows: int) -> torch.Tensor:
192
+ if t.shape[0] == rows:
193
+ return t
194
+ if t.shape[0] > rows:
195
+ return t[:rows, :].contiguous()
196
+ pad = torch.zeros(
197
+ rows - t.shape[0], t.shape[1], dtype=t.dtype, device=t.device
198
+ )
199
+ return torch.cat([t, pad], dim=0).contiguous()
200
+
201
+ @staticmethod
202
+ def _pad_trunc_cols(t: torch.Tensor, cols: int) -> torch.Tensor:
203
+ if t.shape[1] == cols:
204
+ return t
205
+ if t.shape[1] > cols:
206
+ return t[:, :cols].contiguous()
207
+ pad = torch.zeros(
208
+ t.shape[0], cols - t.shape[1], dtype=t.dtype, device=t.device
209
+ )
210
+ return torch.cat([t, pad], dim=1).contiguous()
211
+
212
+ def convert_attention_layers(
213
+ self, tensors: Dict[str, torch.Tensor], layer_idx: int
214
+ ) -> Dict[str, torch.Tensor]:
215
+ """
216
+ Convert attention layers to match target dimensions with proper GQA
217
+ head remapping.
218
+
219
+ Linear weights are [out_features, in_features]:
220
+ - q_proj: out = num_attention_heads * head_dim (= hidden_size)
221
+ - k_proj: out = num_key_value_heads * head_dim
222
+ - v_proj: out = num_key_value_heads * head_dim
223
+ - o_proj: in = num_attention_heads * head_dim (= hidden_size)
224
+ """
225
+ if self.source_config is None:
226
+ raise RuntimeError(
227
+ "source_config not set. load_config must be called first."
228
+ )
229
+
230
+ converted: Dict[str, torch.Tensor] = {}
231
+
232
+ tgt_hidden = int(self.target_config["hidden_size"])
233
+ tgt_heads = int(self.target_config["num_attention_heads"])
234
+ tgt_kv_heads = int(self.target_config["num_key_value_heads"])
235
+ if tgt_heads == 0 or tgt_hidden % tgt_heads != 0:
236
+ raise ValueError(
237
+ f"Invalid target heads/hidden: hidden={tgt_hidden}, "
238
+ f"heads={tgt_heads}"
239
+ )
240
+ tgt_head_dim = tgt_hidden // tgt_heads
241
+
242
+ src_heads = int(
243
+ self.source_config.get("num_attention_heads", tgt_heads)
244
+ )
245
+ src_kv_heads = int(
246
+ self.source_config.get("num_key_value_heads", tgt_kv_heads)
247
+ )
248
+
249
+ def remap_heads(
250
+ W: torch.Tensor,
251
+ src_n: int,
252
+ tgt_n: int,
253
+ src_hd: int,
254
+ tgt_hd: int,
255
+ ) -> torch.Tensor:
256
+ # W: [src_n * src_hd, in]
257
+ W3 = W.view(src_n, src_hd, W.shape[1])
258
+ if src_hd != tgt_hd:
259
+ if src_hd > tgt_hd:
260
+ W3 = W3[:, :tgt_hd, :].contiguous()
261
+ else:
262
+ pad = torch.zeros(
263
+ src_n,
264
+ tgt_hd - src_hd,
265
+ W.shape[1],
266
+ dtype=W.dtype,
267
+ device=W.device,
268
+ )
269
+ W3 = torch.cat([W3, pad], dim=1).contiguous()
270
+ if src_n == tgt_n:
271
+ Wm = W3
272
+ elif src_n > tgt_n:
273
+ if src_n % tgt_n != 0:
274
+ Wm = W3[:tgt_n, :, :].contiguous()
275
+ else:
276
+ g = src_n // tgt_n
277
+ Wm = (
278
+ W3.view(tgt_n, g, tgt_hd, W.shape[1])
279
+ .mean(dim=1)
280
+ .contiguous()
281
+ )
282
+ else:
283
+ r = tgt_n // max(1, src_n)
284
+ if r * src_n == tgt_n:
285
+ Wm = W3.repeat_interleave(r, dim=0).contiguous()
286
+ else:
287
+ reps = math.ceil(tgt_n / src_n)
288
+ Wm = (
289
+ W3.repeat((reps, 1, 1))[:tgt_n, :, :].contiguous()
290
+ )
291
+ W2 = Wm.view(tgt_n * tgt_hd, W.shape[1])
292
+ return W2
293
+
294
+ for key, tensor in tensors.items():
295
+ if "self_attn" not in key:
296
+ continue
297
+
298
+ if "q_proj" in key:
299
+ out_src = tensor.shape[0]
300
+ src_hd = out_src // max(1, src_heads)
301
+ if src_hd * src_heads != out_src:
302
+ src_hd = tgt_head_dim
303
+ W = remap_heads(tensor, src_heads, tgt_heads, src_hd, tgt_head_dim)
304
+ W = self._pad_trunc_cols(W, tgt_hidden)
305
+ converted[key] = W
306
+
307
+ elif "k_proj" in key or "v_proj" in key:
308
+ out_src = tensor.shape[0]
309
+ src_hd = out_src // max(1, src_kv_heads)
310
+ if src_hd * src_kv_heads != out_src:
311
+ src_hd = tgt_head_dim
312
+ W = remap_heads(
313
+ tensor, src_kv_heads, tgt_kv_heads, src_hd, tgt_head_dim
314
+ )
315
+ W = self._pad_trunc_cols(W, tgt_hidden)
316
+ converted[key] = W
317
+
318
+ elif "o_proj" in key:
319
+ W = self._pad_trunc_cols(tensor, tgt_hidden)
320
+ W = self._pad_trunc_rows(W, tgt_hidden)
321
+ converted[key] = W
322
+
323
+ return converted
324
+
325
+ def convert_moe_layer_to_dense(
326
+ self, layer_tensors: Dict[str, torch.Tensor], layer_idx: int
327
+ ) -> Dict[str, torch.Tensor]:
328
+ """
329
+ Convert MoE FFN experts to a single dense FFN matching target dims.
330
+
331
+ Orientation:
332
+ - up_proj, gate_proj -> [intermediate, hidden] (concat along rows)
333
+ - down_proj -> [hidden, intermediate] (concat along cols)
334
+ """
335
+ dense_tensors: Dict[str, torch.Tensor] = {}
336
+ expert_tensors = {"up_proj": [], "down_proj": [], "gate_proj": []}
337
+
338
+ for key, tensor in layer_tensors.items():
339
+ if "experts" in key:
340
+ if "up_proj" in key:
341
+ expert_tensors["up_proj"].append(tensor)
342
+ elif "down_proj" in key:
343
+ expert_tensors["down_proj"].append(tensor)
344
+ elif "gate_proj" in key:
345
+ expert_tensors["gate_proj"].append(tensor)
346
+ elif "router" not in key and "mlp" not in key:
347
+ dense_tensors[key] = tensor
348
+
349
+ attention_tensors = self.convert_attention_layers(
350
+ {k: v for k, v in layer_tensors.items() if "self_attn" in k},
351
+ layer_idx,
352
+ )
353
+ dense_tensors.update(attention_tensors)
354
+
355
+ target_intermediate = int(self.target_config["intermediate_size"])
356
+ target_hidden = int(self.target_config["hidden_size"])
357
+
358
+ def infer_per_expert_ffn() -> int:
359
+ src = (
360
+ expert_tensors["up_proj"]
361
+ or expert_tensors["gate_proj"]
362
+ or expert_tensors["down_proj"]
363
+ )
364
+ if not src:
365
+ return 1536
366
+ s = src[0].shape
367
+ if s[0] == target_hidden:
368
+ return int(s[1])
369
+ if s[1] == target_hidden:
370
+ return int(s[0])
371
+ return int(min(s[0], s[1]))
372
+
373
+ per_expert_ffn = infer_per_expert_ffn()
374
+ logger.info(f" per_expert_ffn inferred as {per_expert_ffn}")
375
+
376
+ def to_up_gate_shape(W: torch.Tensor) -> torch.Tensor:
377
+ if W.shape == (target_hidden, per_expert_ffn):
378
+ return W.t().contiguous()
379
+ if W.shape == (per_expert_ffn, target_hidden):
380
+ return W.contiguous()
381
+ return W.t().contiguous()
382
+
383
+ def to_down_shape(W: torch.Tensor) -> torch.Tensor:
384
+ if W.shape == (per_expert_ffn, target_hidden):
385
+ return W.t().contiguous()
386
+ if W.shape == (target_hidden, per_expert_ffn):
387
+ return W.contiguous()
388
+ return W.t().contiguous()
389
+
390
+ if self.method == "concat_experts":
391
+ num_experts_needed = math.ceil(
392
+ target_intermediate / per_expert_ffn
393
+ )
394
+ for proj_type in ["up_proj", "gate_proj"]:
395
+ if expert_tensors[proj_type]:
396
+ selected = expert_tensors[proj_type][:num_experts_needed]
397
+ while len(selected) < num_experts_needed:
398
+ selected.append(
399
+ expert_tensors[proj_type][
400
+ len(selected)
401
+ % len(expert_tensors[proj_type])
402
+ ]
403
+ )
404
+ blocks = [to_up_gate_shape(W) for W in selected]
405
+ W_cat = torch.cat(blocks, dim=0)
406
+ W_cat = W_cat[:target_intermediate, :].contiguous()
407
+ dense_key = (
408
+ f"model.layers.{layer_idx}.mlp.{proj_type}.weight"
409
+ )
410
+ dense_tensors[dense_key] = W_cat
411
+
412
+ if expert_tensors["down_proj"]:
413
+ selected = expert_tensors["down_proj"][:num_experts_needed]
414
+ while len(selected) < num_experts_needed:
415
+ selected.append(
416
+ expert_tensors["down_proj"][
417
+ len(selected)
418
+ % len(expert_tensors["down_proj"])
419
+ ]
420
+ )
421
+ blocks = [to_down_shape(W) for W in selected]
422
+ W_cat = torch.cat(blocks, dim=1)
423
+ W_cat = W_cat[:, :target_intermediate].contiguous()
424
+ dense_key = (
425
+ f"model.layers.{layer_idx}.mlp.down_proj.weight"
426
+ )
427
+ dense_tensors[dense_key] = W_cat
428
+
429
+ elif self.method == "average":
430
+ for proj_type in ["up_proj", "gate_proj"]:
431
+ if expert_tensors[proj_type]:
432
+ stack = torch.stack(
433
+ [to_up_gate_shape(e) for e in expert_tensors[proj_type]]
434
+ )
435
+ W = torch.mean(stack, dim=0)
436
+ if W.shape[0] < target_intermediate:
437
+ pad = torch.zeros(
438
+ target_intermediate - W.shape[0],
439
+ W.shape[1],
440
+ dtype=W.dtype,
441
+ )
442
+ W = torch.cat([W, pad], dim=0).contiguous()
443
+ else:
444
+ W = W[:target_intermediate, :].contiguous()
445
+ dense_key = (
446
+ f"model.layers.{layer_idx}.mlp.{proj_type}.weight"
447
+ )
448
+ dense_tensors[dense_key] = W
449
+
450
+ if expert_tensors["down_proj"]:
451
+ stack = torch.stack(
452
+ [to_down_shape(e) for e in expert_tensors["down_proj"]]
453
+ )
454
+ W = torch.mean(stack, dim=0)
455
+ if W.shape[1] < target_intermediate:
456
+ pad = torch.zeros(
457
+ W.shape[0],
458
+ target_intermediate - W.shape[1],
459
+ dtype=W.dtype,
460
+ )
461
+ W = torch.cat([W, pad], dim=1).contiguous()
462
+ else:
463
+ W = W[:, :target_intermediate].contiguous()
464
+ dense_key = (
465
+ f"model.layers.{layer_idx}.mlp.down_proj.weight"
466
+ )
467
+ dense_tensors[dense_key] = W
468
+
469
+ elif self.method == "first":
470
+ for proj_type in ["up_proj", "gate_proj"]:
471
+ if expert_tensors[proj_type]:
472
+ W = to_up_gate_shape(expert_tensors[proj_type][0])
473
+ if W.shape[0] < target_intermediate:
474
+ pad = torch.zeros(
475
+ target_intermediate - W.shape[0],
476
+ W.shape[1],
477
+ dtype=W.dtype,
478
+ )
479
+ W = torch.cat([W, pad], dim=0).contiguous()
480
+ else:
481
+ W = W[:target_intermediate, :].contiguous()
482
+ dense_key = (
483
+ f"model.layers.{layer_idx}.mlp.{proj_type}.weight"
484
+ )
485
+ dense_tensors[dense_key] = W
486
+
487
+ if expert_tensors["down_proj"]:
488
+ W = to_down_shape(expert_tensors["down_proj"][0])
489
+ if W.shape[1] < target_intermediate:
490
+ pad = torch.zeros(
491
+ W.shape[0],
492
+ target_intermediate - W.shape[1],
493
+ dtype=W.dtype,
494
+ )
495
+ W = torch.cat([W, pad], dim=1).contiguous()
496
+ else:
497
+ W = W[:, :target_intermediate].contiguous()
498
+ dense_key = (
499
+ f"model.layers.{layer_idx}.mlp.down_proj.weight"
500
+ )
501
+ dense_tensors[dense_key] = W
502
+
503
+ return dense_tensors
504
+
505
+ def convert_safetensors_file(
506
+ self, input_file: str, output_file: str
507
+ ) -> Tuple[List[str], str]:
508
+ logger.info(f"Converting {os.path.basename(input_file)}...")
509
+
510
+ tensors_by_layer: Dict[int, Dict[str, torch.Tensor]] = {}
511
+ other_tensors: Dict[str, torch.Tensor] = {}
512
+
513
+ with safe_open(input_file, framework="pt") as f:
514
+ for key in f.keys():
515
+ tensor = f.get_tensor(key)
516
+ if "model.layers." in key:
517
+ parts = key.split(".")
518
+ layer_idx = int(parts[2])
519
+ if layer_idx not in tensors_by_layer:
520
+ tensors_by_layer[layer_idx] = {}
521
+ tensors_by_layer[layer_idx][key] = tensor
522
+ else:
523
+ other_tensors[key] = tensor
524
+
525
+ converted_tensors: Dict[str, torch.Tensor] = {}
526
+ for layer_idx in sorted(tensors_by_layer.keys()):
527
+ logger.info(f"Processing layer {layer_idx}")
528
+ layer_tensors = tensors_by_layer[layer_idx]
529
+ has_experts = any("experts" in key for key in layer_tensors.keys())
530
+
531
+ if has_experts:
532
+ dense_layer = self.convert_moe_layer_to_dense(
533
+ layer_tensors, layer_idx
534
+ )
535
+ converted_tensors.update(dense_layer)
536
+ else:
537
+ attention_tensors = self.convert_attention_layers(
538
+ {
539
+ k: v
540
+ for k, v in layer_tensors.items()
541
+ if "self_attn" in k
542
+ },
543
+ layer_idx,
544
+ )
545
+ converted_tensors.update(attention_tensors)
546
+ for key, tensor in layer_tensors.items():
547
+ if "router" not in key and "self_attn" not in key:
548
+ converted_tensors[key] = tensor
549
+
550
+ converted_tensors.update(other_tensors)
551
+
552
+ for key in converted_tensors:
553
+ if not converted_tensors[key].is_contiguous():
554
+ converted_tensors[key] = converted_tensors[key].contiguous()
555
+
556
+ save_file(converted_tensors, output_file)
557
+ logger.info(f"Saved to {os.path.basename(output_file)}")
558
+ return list(converted_tensors.keys()), output_file
559
+
560
+ def convert(self):
561
+ self.model_path = self.download_model_if_needed()
562
+ logger.info("Converting configuration...")
563
+ config = self.load_config()
564
+
565
+ config_output = self.output_path / "config.json"
566
+ write_json(config_output, config)
567
+ logger.info(f"Saved config to {config_output}")
568
+
569
+ logger.info("Copying tokenizer files...")
570
+ tokenizer_files = [
571
+ "tokenizer.json",
572
+ "tokenizer_config.json",
573
+ "special_tokens_map.json",
574
+ "vocab.json",
575
+ "merges.txt",
576
+ "tokenizer.model",
577
+ "generation_config.json",
578
+ ]
579
+ for file in tokenizer_files:
580
+ src = os.path.join(self.model_path, file)
581
+ if os.path.exists(src):
582
+ dst = self.output_path / file
583
+ shutil.copy2(src, dst)
584
+ logger.info(f" Copied {file}")
585
+
586
+ weight_files = glob.glob(os.path.join(self.model_path, "*.safetensors"))
587
+ if not weight_files:
588
+ weight_files = glob.glob(
589
+ os.path.join(self.model_path, "model*.safetensors")
590
+ )
591
+ if not weight_files:
592
+ raise FileNotFoundError(
593
+ f"No safetensors files found in {self.model_path}"
594
+ )
595
+
596
+ weight_files.sort()
597
+ logger.info(f"Found {len(weight_files)} weight files to convert")
598
+
599
+ tensor_map: Dict[str, str] = {}
600
+ total_tensors = 0
601
+
602
+ for i, weight_file in enumerate(weight_files, 1):
603
+ output_filename = (
604
+ f"model-{i:05d}-of-{len(weight_files):05d}.safetensors"
605
+ )
606
+ output_file = self.output_path / output_filename
607
+ tensor_names, _ = self.convert_safetensors_file(
608
+ weight_file, str(output_file)
609
+ )
610
+
611
+ for tensor_name in tensor_names:
612
+ tensor_map[tensor_name] = output_filename
613
+
614
+ total_tensors += len(tensor_names)
615
+ logger.info(f"Progress: {i}/{len(weight_files)} files converted")
616
+
617
+ if self.low_memory:
618
+ gc.collect()
619
+
620
+ self.create_model_index(tensor_map)
621
+
622
+ logger.info("Conversion complete")
623
+ logger.info(f" Total tensors converted: {total_tensors}")
624
+ logger.info(f" Output saved to: {self.output_path}")
625
+ return self.output_path
626
+
627
+ def create_model_index(self, tensor_map: Dict[str, str]):
628
+ total_size = 0
629
+ for filename in set(tensor_map.values()):
630
+ file_path = self.output_path / filename
631
+ if file_path.exists():
632
+ total_size += file_path.stat().st_size
633
+
634
+ index = {
635
+ "metadata": {"total_size": total_size, "format": "safetensors"},
636
+ "weight_map": tensor_map,
637
+ }
638
+
639
+ index_path = self.output_path / "model.safetensors.index.json"
640
+ write_json(index_path, index)
641
+ logger.info(
642
+ f"Created index file with {len(tensor_map)} tensor mappings"
643
+ )
644
+
645
+
646
+ def index_safetensors_dir(
647
+ model_dir: str,
648
+ ) -> Tuple[Dict[str, str], List[str]]:
649
+ model_dir = str(model_dir)
650
+ index_path = os.path.join(model_dir, "model.safetensors.index.json")
651
+ weight_map: Dict[str, str] = {}
652
+ files: List[str] = []
653
+
654
+ if os.path.exists(index_path):
655
+ idx = read_json(index_path)
656
+ weight_map = idx.get("weight_map", {})
657
+ files = sorted(
658
+ list({os.path.join(model_dir, f) for f in weight_map.values()})
659
+ )
660
+ return weight_map, files
661
+
662
+ st_files = glob.glob(os.path.join(model_dir, "*.safetensors"))
663
+ if not st_files:
664
+ raise FileNotFoundError(
665
+ f"No safetensors files found in {model_dir}"
666
+ )
667
+
668
+ for fpath in st_files:
669
+ with safe_open(fpath, framework="pt") as f:
670
+ for key in f.keys():
671
+ weight_map[key] = os.path.basename(fpath)
672
+ files = sorted(st_files)
673
+ return weight_map, files
674
+
675
+
676
+ def list_layer_keys(weight_map: Dict[str, str], layer_idx: int) -> List[str]:
677
+ prefix = f"model.layers.{layer_idx}."
678
+ return [k for k in weight_map.keys() if k.startswith(prefix)]
679
+
680
+
681
+ def load_tensors_by_keys(
682
+ model_dir: str,
683
+ weight_map: Dict[str, str],
684
+ keys: List[str],
685
+ cast_dtype_str: Optional[str] = None,
686
+ ) -> Dict[str, torch.Tensor]:
687
+ files_to_keys: Dict[str, List[str]] = {}
688
+ for k in keys:
689
+ filename = weight_map[k]
690
+ files_to_keys.setdefault(filename, []).append(k)
691
+
692
+ out: Dict[str, torch.Tensor] = {}
693
+ for filename, klist in files_to_keys.items():
694
+ fpath = os.path.join(model_dir, filename)
695
+ with safe_open(fpath, framework="pt") as f:
696
+ for k in klist:
697
+ t = f.get_tensor(k)
698
+ t = cast_tensor_dtype(t, cast_dtype_str)
699
+ if not t.is_contiguous():
700
+ t = t.contiguous()
701
+ out[k] = t
702
+ return out
703
+
704
+
705
+ def rename_layer_keys(
706
+ tensors: Dict[str, torch.Tensor],
707
+ src_layer: int,
708
+ dst_layer: int,
709
+ ) -> Dict[str, torch.Tensor]:
710
+ src_prefix = f"model.layers.{src_layer}."
711
+ dst_prefix = f"model.layers.{dst_layer}."
712
+ out: Dict[str, torch.Tensor] = {}
713
+ for k, v in tensors.items():
714
+ if not k.startswith(src_prefix):
715
+ continue
716
+ new_k = dst_prefix + k[len(src_prefix) :]
717
+ out[new_k] = v
718
+ return out
719
+
720
+
721
+ def copy_non_layer_tensors(
722
+ src_dir: str,
723
+ cast_dtype_str: Optional[str] = None,
724
+ ) -> Dict[str, torch.Tensor]:
725
+ weight_map, _ = index_safetensors_dir(src_dir)
726
+ keys = [k for k in weight_map.keys() if "model.layers." not in k]
727
+ return load_tensors_by_keys(src_dir, weight_map, keys, cast_dtype_str)
728
+
729
+
730
+ def build_even_interleave_plan(
731
+ final_layers: int,
732
+ base_layers: int,
733
+ moe_layers: int,
734
+ ) -> List[Tuple[str, int]]:
735
+ n_moe = min(moe_layers, max(0, final_layers - base_layers))
736
+ n_base = final_layers - n_moe
737
+ plan: List[Tuple[str, int]] = []
738
+
739
+ moe_slots = set()
740
+ for i in range(final_layers):
741
+ if (
742
+ math.floor((i + 1) * n_moe / max(1, final_layers))
743
+ != math.floor(i * n_moe / max(1, final_layers))
744
+ and len(moe_slots) < n_moe
745
+ ):
746
+ moe_slots.add(i)
747
+
748
+ used_moe = 0
749
+ used_base = 0
750
+ for i in range(final_layers):
751
+ if i in moe_slots:
752
+ src_idx = 0
753
+ if n_moe > 0:
754
+ src_idx = min(
755
+ moe_layers - 1,
756
+ math.floor(used_moe * moe_layers / max(1, n_moe)),
757
+ )
758
+ plan.append(("moe", src_idx))
759
+ used_moe += 1
760
+ else:
761
+ src_idx = 0
762
+ if n_base > 0:
763
+ src_idx = min(
764
+ base_layers - 1,
765
+ math.floor(used_base * base_layers / max(1, n_base)),
766
+ )
767
+ plan.append(("base", src_idx))
768
+ used_base += 1
769
+
770
+ return plan
771
+
772
+
773
+ def build_alternate_plan(
774
+ final_layers: int,
775
+ base_layers: int,
776
+ moe_layers: int,
777
+ ) -> List[Tuple[str, int]]:
778
+ plan: List[Tuple[str, int]] = []
779
+ b = 0
780
+ m = 0
781
+ turn_moe = True
782
+ while len(plan) < final_layers:
783
+ if turn_moe and m < moe_layers:
784
+ plan.append(("moe", m))
785
+ m += 1
786
+ elif b < base_layers:
787
+ plan.append(("base", b))
788
+ b += 1
789
+ elif m < moe_layers:
790
+ plan.append(("moe", m))
791
+ m += 1
792
+ else:
793
+ plan.append(plan[-1])
794
+ turn_moe = not turn_moe
795
+ return plan
796
+
797
+
798
+ def build_composite_model(
799
+ base_model_dir: str,
800
+ moe_model_dir: str,
801
+ output_dir: str,
802
+ final_layers: int,
803
+ interleave_strategy: str = "even",
804
+ cast_dtype_str: Optional[str] = None,
805
+ low_memory: bool = True,
806
+ ):
807
+ out_dir = Path(output_dir)
808
+ out_dir.mkdir(parents=True, exist_ok=True)
809
+
810
+ base_cfg = read_json(os.path.join(base_model_dir, "config.json"))
811
+ moe_cfg = read_json(os.path.join(moe_model_dir, "config.json"))
812
+
813
+ for k in ["hidden_size", "intermediate_size"]:
814
+ if base_cfg.get(k) != moe_cfg.get(k):
815
+ raise ValueError(
816
+ f"Config mismatch for {k}: base={base_cfg.get(k)} "
817
+ f"moe={moe_cfg.get(k)}"
818
+ )
819
+
820
+ base_layers = int(base_cfg.get("num_hidden_layers"))
821
+ moe_layers = int(moe_cfg.get("num_hidden_layers"))
822
+
823
+ logger.info(
824
+ f"Composite plan: base_layers={base_layers}, "
825
+ f"moe_layers={moe_layers}, final_layers={final_layers}"
826
+ )
827
+
828
+ if interleave_strategy == "even":
829
+ plan = build_even_interleave_plan(
830
+ final_layers, base_layers, moe_layers
831
+ )
832
+ elif interleave_strategy == "alternate":
833
+ plan = build_alternate_plan(
834
+ final_layers, base_layers, moe_layers
835
+ )
836
+ else:
837
+ raise ValueError(
838
+ "interleave_strategy must be 'even' or 'alternate'"
839
+ )
840
+
841
+ out_cfg = dict(base_cfg)
842
+ out_cfg["num_hidden_layers"] = final_layers
843
+ write_json(out_dir / "config.json", out_cfg)
844
+
845
+ logger.info("Copying tokenizer/aux files from base...")
846
+ for fname in [
847
+ "tokenizer.json",
848
+ "tokenizer_config.json",
849
+ "special_tokens_map.json",
850
+ "vocab.json",
851
+ "merges.txt",
852
+ "tokenizer.model",
853
+ "generation_config.json",
854
+ ]:
855
+ src = os.path.join(base_model_dir, fname)
856
+ if os.path.exists(src):
857
+ shutil.copy2(src, out_dir / fname)
858
+
859
+ base_map, _ = index_safetensors_dir(base_model_dir)
860
+ moe_map, _ = index_safetensors_dir(moe_model_dir)
861
+
862
+ logger.info("Saving non-layer tensors...")
863
+ non_layer_tensors = copy_non_layer_tensors(base_model_dir, cast_dtype_str)
864
+ non_layer_file = "model-nonlayers.safetensors"
865
+ save_file(non_layer_tensors, str(out_dir / non_layer_file))
866
+ out_weight_map: Dict[str, str] = {
867
+ k: non_layer_file for k in non_layer_tensors.keys()
868
+ }
869
+ del non_layer_tensors
870
+ if low_memory:
871
+ gc.collect()
872
+
873
+ logger.info("Building layers...")
874
+ for tgt_idx, (src_tag, src_idx) in tqdm(
875
+ list(enumerate(plan)), dynamic_ncols=True
876
+ ):
877
+ src_dir = base_model_dir if src_tag == "base" else moe_model_dir
878
+ src_map = base_map if src_tag == "base" else moe_map
879
+
880
+ src_keys = list_layer_keys(src_map, src_idx)
881
+ if not src_keys:
882
+ raise RuntimeError(
883
+ f"No layer keys found for {src_tag} layer {src_idx}"
884
+ )
885
+ tensors = load_tensors_by_keys(
886
+ src_dir, src_map, src_keys, cast_dtype_str
887
+ )
888
+ renamed = rename_layer_keys(tensors, src_idx, tgt_idx)
889
+
890
+ layer_fname = f"model-layer-{tgt_idx:05d}.safetensors"
891
+ save_file(renamed, str(out_dir / layer_fname))
892
+ for k in renamed.keys():
893
+ out_weight_map[k] = layer_fname
894
+
895
+ del tensors, renamed
896
+ if low_memory:
897
+ gc.collect()
898
+
899
+ total_size = 0
900
+ for fname in set(out_weight_map.values()):
901
+ fp = out_dir / fname
902
+ if fp.exists():
903
+ total_size += fp.stat().st_size
904
+
905
+ index = {
906
+ "metadata": {"total_size": total_size, "format": "safetensors"},
907
+ "weight_map": out_weight_map,
908
+ }
909
+ write_json(out_dir / "model.safetensors.index.json", index)
910
+ logger.info(
911
+ f"Composite model written to {out_dir} with {final_layers} layers."
912
+ )
913
+
914
+
915
+ def validate_model_load(model_dir: str):
916
+ try:
917
+ from transformers import AutoModelForCausalLM
918
+
919
+ _ = AutoModelForCausalLM.from_pretrained(
920
+ model_dir,
921
+ torch_dtype="auto",
922
+ trust_remote_code=True,
923
+ device_map="meta",
924
+ )
925
+ logger.info("Model loads successfully on meta device.")
926
+ except Exception as e:
927
+ logger.error("Model failed to load on meta device.")
928
+ raise
929
+
930
+
931
+ def main():
932
+ parser = argparse.ArgumentParser(
933
+ description=(
934
+ "Convert MoE model to dense format with target compatibility, "
935
+ "and/or build a larger composite model by interleaving layers."
936
+ )
937
+ )
938
+
939
+ parser.add_argument("--model_id", type=str, help="MoE model ID or path")
940
+ parser.add_argument(
941
+ "--target_model",
942
+ type=str,
943
+ help="Target dense model for dimension matching",
944
+ )
945
+ parser.add_argument(
946
+ "--output_path",
947
+ type=str,
948
+ help="Path to save the converted dense model",
949
+ )
950
+ parser.add_argument(
951
+ "--method",
952
+ type=str,
953
+ choices=["concat_experts", "average", "first"],
954
+ default="average",
955
+ help="Expert merge method",
956
+ )
957
+ parser.add_argument(
958
+ "--low_memory",
959
+ action="store_true",
960
+ help="Low memory conversion",
961
+ )
962
+ parser.add_argument(
963
+ "--test_merge",
964
+ action="store_true",
965
+ help="Write a sample merge config",
966
+ )
967
+
968
+ parser.add_argument(
969
+ "--compose_interleaved",
970
+ action="store_true",
971
+ help="Build composite model by interleaving layers",
972
+ )
973
+ parser.add_argument(
974
+ "--base_model", type=str, help="Base dense model path or HF ID"
975
+ )
976
+ parser.add_argument(
977
+ "--moe_converted", type=str, help="Converted MoE-dense model dir"
978
+ )
979
+ parser.add_argument(
980
+ "--composite_output_path",
981
+ type=str,
982
+ help="Output path for composite model",
983
+ )
984
+ parser.add_argument(
985
+ "--final_layers",
986
+ type=int,
987
+ help="Number of transformer layers in composite",
988
+ )
989
+ parser.add_argument(
990
+ "--interleave_strategy",
991
+ type=str,
992
+ choices=["even", "alternate"],
993
+ default="even",
994
+ help="Interleaving strategy",
995
+ )
996
+ parser.add_argument(
997
+ "--cast_dtype",
998
+ type=str,
999
+ choices=["float32", "fp32", "float16", "fp16", "bfloat16", "bf16"],
1000
+ help="Optional cast during composite build",
1001
+ )
1002
+
1003
+ parser.add_argument(
1004
+ "--validate_model",
1005
+ type=str,
1006
+ help="Validate a model directory on meta device",
1007
+ )
1008
+
1009
+ args = parser.parse_args()
1010
+
1011
+ if args.validate_model:
1012
+ validate_model_load(args.validate_model)
1013
+ return
1014
+
1015
+ if args.compose_interleaved:
1016
+ if not args.base_model or not args.moe_converted:
1017
+ raise ValueError(
1018
+ "--compose_interleaved requires --base_model and "
1019
+ "--moe_converted"
1020
+ )
1021
+ base_dir = args.base_model
1022
+ if not os.path.exists(base_dir):
1023
+ logger.info(f"Downloading base model {base_dir}...")
1024
+ base_dir = snapshot_download(
1025
+ base_dir,
1026
+ cache_dir="./model_cache",
1027
+ resume_download=True,
1028
+ )
1029
+ moe_dir = args.moe_converted
1030
+ if not os.path.exists(moe_dir):
1031
+ raise FileNotFoundError(
1032
+ f"--moe_converted path not found: {moe_dir}"
1033
+ )
1034
+ out_dir = args.composite_output_path or "./composite_interleaved"
1035
+ if not args.final_layers:
1036
+ base_cfg = read_json(os.path.join(base_dir, "config.json"))
1037
+ moe_cfg = read_json(os.path.join(moe_dir, "config.json"))
1038
+ args.final_layers = int(base_cfg["num_hidden_layers"]) + int(
1039
+ moe_cfg["num_hidden_layers"]
1040
+ )
1041
+ build_composite_model(
1042
+ base_model_dir=base_dir,
1043
+ moe_model_dir=moe_dir,
1044
+ output_dir=out_dir,
1045
+ final_layers=int(args.final_layers),
1046
+ interleave_strategy=args.interleave_strategy,
1047
+ cast_dtype_str=args.cast_dtype,
1048
+ low_memory=args.low_memory,
1049
+ )
1050
+ logger.info(
1051
+ f"Composite interleaving complete. Output: {out_dir}"
1052
+ )
1053
+ return
1054
+
1055
+ if not args.model_id or not args.target_model or not args.output_path:
1056
+ parser.error(
1057
+ "Conversion mode requires --model_id, --target_model, "
1058
+ "and --output_path"
1059
+ )
1060
+
1061
+ converter = MoEToDenseConverter(
1062
+ model_path=args.model_id,
1063
+ target_model_path=args.target_model,
1064
+ output_path=args.output_path,
1065
+ method=args.method,
1066
+ low_memory=args.low_memory,
1067
+ )
1068
+
1069
+ output_path = converter.convert()
1070
+
1071
+ if args.test_merge:
1072
+ merge_config = {
1073
+ "models": [
1074
+ {"model": args.target_model, "parameters": {"weight": 0.7}},
1075
+ {"model": str(output_path), "parameters": {"weight": 0.3}},
1076
+ ],
1077
+ "merge_method": "linear",
1078
+ "base_model": args.target_model,
1079
+ "dtype": "bfloat16",
1080
+ }
1081
+ merge_config_path = Path(args.output_path).parent / "merge_config.yaml"
1082
+ try:
1083
+ import yaml
1084
+
1085
+ with open(merge_config_path, "w") as f:
1086
+ yaml.dump(merge_config, f)
1087
+ logger.info(
1088
+ f"Wrote sample merge configuration to {merge_config_path}"
1089
+ )
1090
+ except Exception as e:
1091
+ logger.warning(
1092
+ f"Could not write sample merge YAML: {e}"
1093
+ )
1094
+
1095
+
1096
+ if __name__ == "__main__":
1097
+ main()
sample.txt ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a helpful assistant. Respond to the next user message in a single paragraph.
2
+ Explain why the sky appears blue using a two-sentence summary.
3
+ List three practical uses of hash maps and one limitation.
4
+ Summarize how gradient descent works without equations.
5
+ Give a neutral definition of reinforcement learning and a common pitfall.
6
+ Describe the difference between latency and throughput with a concrete example.
7
+ Explain what a vector database is and when you would not use one.
8
+ In one paragraph, compare JSON and Parquet from a data engineering perspective.
9
+ Outline the steps to reproduce a minimal bug report for a Python library.
10
+ Provide three strategies to reduce overfitting in neural networks.
11
+ Write a short product description for a reusable water bottle aimed at travelers.
12
+ Translate this to Spanish: The library opens at nine and closes at six.
13
+ Paraphrase this sentence: The results were surprising but not conclusive.
14
+ Convert the following bullet list into a single coherent paragraph: speed, safety, cost.
15
+ Explain what a checksum is and why it matters for file downloads.
16
+ State the pros and cons of using WebAssembly in the browser.
17
+ Explain CAP theorem in one paragraph and give a real-world trade-off.
18
+ Outline a basic incident response checklist for a small engineering team.
19
+ Describe how HTTP caching works and why ETags are useful.
20
+ Explain the purpose of unit tests versus integration tests.
21
+ Give a concise explanation of SIMD and where it helps.
22
+ Describe a reliable backup strategy for a personal laptop.
23
+ In two sentences, explain how public key cryptography enables secure messaging.
24
+ Explain the difference between imperative and declarative programming with an example.
25
+ Write a short release note for a minor version update of a CLI tool.
26
+ Explain what cosine similarity measures and where it’s used.
27
+ Provide a brief, friendly onboarding message for a new community member.
28
+ Give a two-sentence description of how transformers use attention.
29
+ Describe what a memory leak is and how to spot one.
30
+ Explain why idempotency keys are important in payment APIs.
31
+ Summarize the key ideas behind zero-copy I/O.
32
+ Define a feature flag and explain one safe rollout pattern.
33
+ Write a short announcement for scheduled maintenance with expected impact.
34
+ Explain what a bloom filter is and when false positives are acceptable.
35
+ Give a checklist for code review that fits on a sticky note.
36
+ Describe a resilient way to schedule background jobs in a web app.
37
+ Explain the concept of backpressure in streaming systems.
38
+ Compare columnar vs row-oriented storage in one paragraph.
39
+ Explain how pagination strategies differ between offset and cursor methods.
40
+ Write a brief description of a dataset card for a public corpus of recipes.
41
+ Explain what a content-addressable store is and why it’s powerful.
42
+ In one paragraph, describe how to interpret a confusion matrix.
43
+ Give guidance for writing good commit messages with examples.
44
+ Describe the trade-offs of strongly typed schemas versus schema-on-read.
45
+ Explain what vector quantization is in plain language.
46
+ Provide a short primer on HTTP/2 multiplexing and head-of-line blocking.
47
+ Explain what a rolling hash is and where it’s useful.
48
+ Write a brief warning about common pitfalls when using floating point numbers.
49
+ Describe how JWTs work and one reason to rotate signing keys.
50
+ Explain the difference between top-k and nucleus sampling in text generation.
51
+ Provide a simple migration plan from REST to gRPC for a single service.
52
+ Give a one-paragraph overview of entropy as used in information theory.
53
+ Explain how learned positional encodings differ from rotary encodings at a high level.
54
+ Write a concise guide to choosing batch size under a fixed memory budget.
55
+ Explain what an embedding dimension means and why larger isn’t always better.
56
+ Describe a safe pattern for storing API secrets in a deployment pipeline.
57
+ Provide a two-sentence overview of LoRA fine-tuning and its benefits.
58
+ Explain the idea of teacher forcing in sequence models and a downside.
59
+ Write a short FAQ entry: “Why are my generations repetitive?”
60
+ Describe how to evaluate a summarization system without human raters.
61
+ Explain the difference between deterministic and stochastic decoding.
62
+ Provide a brief note on choosing between FP16 and BF16 on modern GPUs.
63
+ Write a compact introduction to beam search and its main trade-offs.
64
+ Give a minimal example of a retry policy with exponential backoff described in words.
65
+ Explain why logging PII can create compliance risks and how to avoid it.
scales.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "9": { "attn_q": 0.96, "attn_k": 0.96, "mlp_down": 0.98 },
3
+ "11": { "attn_q": 0.90, "attn_k": 0.90 },
4
+ "13": { "attn_q": 0.90, "attn_k": 0.90 },
5
+ "25": { "attn_q": 0.92, "attn_k": 0.92 },
6
+ "30": { "attn_q": 0.88, "attn_k": 0.88, "mlp_down": 0.95 },
7
+ "34": { "attn_q": 0.90, "attn_k": 0.90 }
8
+ }
visualize_activations.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Visualize activation statistics JSON produced by activation_stats.py.
4
+
5
+ Generates an interactive HTML dashboard with:
6
+ - Token RMS mean across layers for attention q/k/v/o and MLP up/gate/down
7
+ - Zero fraction heatmap per layer and module type
8
+ - Attention entropy per layer (if present)
9
+ - Top-N modules by token_rms_mean and zero_fraction
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import re
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Dict, Any, List, Optional, Tuple
18
+
19
+ import plotly.graph_objects as go
20
+
21
+ try:
22
+ import pandas as pd
23
+ except Exception:
24
+ pd = None
25
+
26
+
27
+ @dataclass
28
+ class ModuleStat:
29
+ name: str
30
+ layer: Optional[int]
31
+ mtype: str
32
+ token_rms_mean: Optional[float]
33
+ token_rms_std: Optional[float]
34
+ mean: Optional[float]
35
+ std: Optional[float]
36
+ min: Optional[float]
37
+ max: Optional[float]
38
+ zero_frac: Optional[float]
39
+ count: int
40
+ nan_count: int
41
+ inf_count: int
42
+
43
+
44
+ ATTN_TYPES = ["q_proj", "k_proj", "v_proj", "o_proj"]
45
+ MLP_TYPES = ["mlp.up_proj", "mlp.gate_proj", "mlp.down_proj"]
46
+ NORM_HINTS = ["layernorm", ".norm"]
47
+
48
+
49
+ def parse_layer_idx(name: str) -> Optional[int]:
50
+ m = re.search(r"model\.layers\.(\d+)\.", name)
51
+ if m:
52
+ try:
53
+ return int(m.group(1))
54
+ except Exception:
55
+ return None
56
+ return None
57
+
58
+
59
+ def infer_type(name: str) -> str:
60
+ lname = name.lower()
61
+ for t in ATTN_TYPES:
62
+ if f".self_attn.{t}" in lname:
63
+ return t
64
+ for t in MLP_TYPES:
65
+ if t in lname:
66
+ return t
67
+ for h in NORM_HINTS:
68
+ if h in lname:
69
+ return "norm"
70
+ return "other"
71
+
72
+
73
+ def try_float(x: Any) -> Optional[float]:
74
+ try:
75
+ if x is None:
76
+ return None
77
+ return float(x)
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ def load_stats_json(path: str) -> Tuple[List[ModuleStat], Dict[int, float]]:
83
+ with open(path, "r") as f:
84
+ data = json.load(f)
85
+
86
+ rows: List[ModuleStat] = []
87
+ attn_entropy: Dict[int, float] = {}
88
+ if "_attention_entropy" in data and isinstance(
89
+ data["_attention_entropy"], dict
90
+ ):
91
+ for k, v in data["_attention_entropy"].items():
92
+ try:
93
+ attn_entropy[int(k)] = float(v)
94
+ except Exception:
95
+ continue
96
+
97
+ for name, entry in data.items():
98
+ if name.startswith("_"):
99
+ continue
100
+ if not isinstance(entry, dict):
101
+ continue
102
+ g = entry.get("global", {})
103
+ tr = entry.get("token_rms", {})
104
+
105
+ count = int(g.get("count", 0) or 0)
106
+ zero_count = int(g.get("zero_count", 0) or 0)
107
+ zero_frac = (zero_count / count) if count > 0 else None
108
+
109
+ rows.append(
110
+ ModuleStat(
111
+ name=name,
112
+ layer=parse_layer_idx(name),
113
+ mtype=infer_type(name),
114
+ token_rms_mean=try_float(tr.get("mean")),
115
+ token_rms_std=try_float(tr.get("std")),
116
+ mean=try_float(g.get("mean")),
117
+ std=try_float(g.get("std")),
118
+ min=try_float(g.get("min")),
119
+ max=try_float(g.get("max")),
120
+ zero_frac=zero_frac,
121
+ count=count,
122
+ nan_count=int(g.get("nan_count", 0) or 0),
123
+ inf_count=int(g.get("inf_count", 0) or 0),
124
+ )
125
+ )
126
+
127
+ return rows, attn_entropy
128
+
129
+
130
+ def filter_rows(
131
+ rows: List[ModuleStat],
132
+ allowed_types: Optional[List[str]],
133
+ layer_min: Optional[int],
134
+ layer_max: Optional[int],
135
+ ) -> List[ModuleStat]:
136
+ out: List[ModuleStat] = []
137
+ for r in rows:
138
+ if allowed_types and (r.mtype not in allowed_types):
139
+ continue
140
+ if r.layer is not None:
141
+ if layer_min is not None and r.layer < layer_min:
142
+ continue
143
+ if layer_max is not None and r.layer > layer_max:
144
+ continue
145
+ out.append(r)
146
+ return out
147
+
148
+
149
+ def group_by_layer_type(
150
+ rows: List[ModuleStat], types: List[str]
151
+ ) -> Dict[str, Dict[int, ModuleStat]]:
152
+ d: Dict[str, Dict[int, ModuleStat]] = {t: {} for t in types}
153
+ for r in rows:
154
+ if r.layer is None:
155
+ continue
156
+ if r.mtype in d and r.layer not in d[r.mtype]:
157
+ d[r.mtype][r.layer] = r
158
+ return d
159
+
160
+
161
+ def make_sorted_layers(mapping: Dict[int, Any]) -> List[int]:
162
+ return sorted(list(mapping.keys()))
163
+
164
+
165
+ def fig_token_rms_lines(
166
+ rows: List[ModuleStat],
167
+ types: List[str],
168
+ title: str,
169
+ y_field: str = "token_rms_mean",
170
+ ) -> go.Figure:
171
+ grouped = group_by_layer_type(rows, types)
172
+ fig = go.Figure()
173
+ for t in types:
174
+ lay2stat = grouped.get(t, {})
175
+ if not lay2stat:
176
+ continue
177
+ layers = make_sorted_layers(lay2stat)
178
+ ys = [
179
+ getattr(lay2stat[L], y_field) if lay2stat[L] else None
180
+ for L in layers
181
+ ]
182
+ fig.add_trace(
183
+ go.Scatter(
184
+ x=layers,
185
+ y=ys,
186
+ mode="lines+markers",
187
+ name=t,
188
+ connectgaps=False,
189
+ )
190
+ )
191
+ fig.update_layout(
192
+ title=title,
193
+ xaxis_title="Layer",
194
+ yaxis_title=y_field,
195
+ template="plotly_white",
196
+ legend_title="Module type",
197
+ )
198
+ return fig
199
+
200
+
201
+ def fig_zero_frac_heatmap(rows: List[ModuleStat], types: List[str]) -> go.Figure:
202
+ grouped = group_by_layer_type(rows, types)
203
+ all_layers = sorted(
204
+ list({L for t in types for L in grouped.get(t, {}).keys()})
205
+ )
206
+ if not all_layers:
207
+ return go.Figure()
208
+ z = []
209
+ for t in types:
210
+ lay2stat = grouped.get(t, {})
211
+ row = []
212
+ for L in all_layers:
213
+ s = lay2stat.get(L)
214
+ row.append(s.zero_frac if s else None)
215
+ z.append(row)
216
+
217
+ fig = go.Figure(
218
+ data=go.Heatmap(
219
+ z=z,
220
+ x=all_layers,
221
+ y=types,
222
+ colorscale="Viridis",
223
+ colorbar_title="zero_fraction",
224
+ )
225
+ )
226
+ fig.update_layout(
227
+ title="Zero fraction heatmap by layer and module type",
228
+ xaxis_title="Layer",
229
+ yaxis_title="Module type",
230
+ template="plotly_white",
231
+ )
232
+ return fig
233
+
234
+
235
+ def fig_attention_entropy(entropy: Dict[int, float]) -> go.Figure:
236
+ if not entropy:
237
+ return go.Figure()
238
+ layers = sorted(entropy.keys())
239
+ vals = [entropy[L] for L in layers]
240
+ fig = go.Figure(
241
+ data=go.Scatter(
242
+ x=layers, y=vals, mode="lines+markers", name="attn_entropy"
243
+ )
244
+ )
245
+ fig.update_layout(
246
+ title="Attention entropy (mean per layer)",
247
+ xaxis_title="Layer",
248
+ yaxis_title="Entropy",
249
+ template="plotly_white",
250
+ )
251
+ return fig
252
+
253
+
254
+ def top_k_bar(
255
+ rows: List[ModuleStat],
256
+ field: str,
257
+ title: str,
258
+ top_k: int = 20,
259
+ reverse: bool = True,
260
+ ) -> go.Figure:
261
+ vals: List[Tuple[str, float]] = []
262
+ for r in rows:
263
+ v = getattr(r, field)
264
+ if v is None:
265
+ continue
266
+ vals.append((r.name, float(v)))
267
+ if not vals:
268
+ return go.Figure()
269
+ vals.sort(key=lambda x: x[1], reverse=reverse)
270
+ vals = vals[:top_k]
271
+ names = [v[0] for v in vals]
272
+ ys = [v[1] for v in vals]
273
+ fig = go.Figure(
274
+ data=go.Bar(
275
+ x=ys,
276
+ y=names,
277
+ orientation="h",
278
+ marker_color="steelblue",
279
+ name=field,
280
+ )
281
+ )
282
+ fig.update_layout(
283
+ title=title,
284
+ xaxis_title=field,
285
+ yaxis_title="Module",
286
+ template="plotly_white",
287
+ margin=dict(l=200),
288
+ )
289
+ return fig
290
+
291
+
292
+ def make_dashboard(
293
+ attn_rows: List[ModuleStat],
294
+ mlp_rows: List[ModuleStat],
295
+ all_rows: List[ModuleStat],
296
+ attn_entropy: Dict[int, float],
297
+ top_k: int,
298
+ ) -> str:
299
+ figs: List[go.Figure] = []
300
+
301
+ figs.append(
302
+ fig_token_rms_lines(
303
+ attn_rows, ATTN_TYPES, "Attention Token RMS mean by layer"
304
+ )
305
+ )
306
+ figs.append(
307
+ fig_token_rms_lines(
308
+ mlp_rows, MLP_TYPES, "MLP Token RMS mean by layer"
309
+ )
310
+ )
311
+
312
+ figs.append(fig_zero_frac_heatmap(attn_rows, ATTN_TYPES))
313
+ figs.append(fig_zero_frac_heatmap(mlp_rows, MLP_TYPES))
314
+
315
+ if attn_entropy:
316
+ figs.append(fig_attention_entropy(attn_entropy))
317
+
318
+ figs.append(
319
+ top_k_bar(
320
+ all_rows,
321
+ "token_rms_mean",
322
+ f"Top {top_k} modules by token_rms_mean",
323
+ top_k=top_k,
324
+ )
325
+ )
326
+ figs.append(
327
+ top_k_bar(
328
+ all_rows,
329
+ "zero_frac",
330
+ f"Top {top_k} modules by zero_fraction",
331
+ top_k=top_k,
332
+ )
333
+ )
334
+
335
+ parts = []
336
+ for i, fig in enumerate(figs):
337
+ parts.append(
338
+ fig.to_html(
339
+ full_html=False,
340
+ include_plotlyjs="cdn",
341
+ default_width="100%",
342
+ default_height="600px",
343
+ )
344
+ )
345
+
346
+ html = f"""
347
+ <!DOCTYPE html>
348
+ <html lang="en">
349
+ <head>
350
+ <meta charset="utf-8" />
351
+ <title>Activation Statistics Dashboard</title>
352
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
353
+ <style>
354
+ body {{
355
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
356
+ "Helvetica Neue", Arial, "Noto Sans", "Liberation Sans",
357
+ sans-serif;
358
+ margin: 0;
359
+ padding: 0 16px 64px 16px;
360
+ background: #ffffff;
361
+ color: #111;
362
+ }}
363
+ h1 {{
364
+ font-size: 22px;
365
+ font-weight: 600;
366
+ margin-top: 16px;
367
+ }}
368
+ .fig {{
369
+ margin: 24px 0;
370
+ border: 1px solid #eee;
371
+ padding: 8px;
372
+ border-radius: 8px;
373
+ box-shadow: 0 1px 0 rgba(0,0,0,0.04);
374
+ }}
375
+ </style>
376
+ </head>
377
+ <body>
378
+ <h1>Activation Statistics Dashboard</h1>
379
+ <div class="fig">{parts[0] if len(parts) > 0 else ""}</div>
380
+ <div class="fig">{parts[1] if len(parts) > 1 else ""}</div>
381
+ <div class="fig">{parts[2] if len(parts) > 2 else ""}</div>
382
+ <div class="fig">{parts[3] if len(parts) > 3 else ""}</div>
383
+ <div class="fig">{parts[4] if len(parts) > 4 else ""}</div>
384
+ <div class="fig">{parts[5] if len(parts) > 5 else ""}</div>
385
+ <div class="fig">{parts[6] if len(parts) > 6 else ""}</div>
386
+ </body>
387
+ </html>
388
+ """
389
+ return html
390
+
391
+
392
+ def main():
393
+ ap = argparse.ArgumentParser(
394
+ description="Visualize activation stats JSON to interactive HTML."
395
+ )
396
+ ap.add_argument("--stats_json", type=str, required=True)
397
+ ap.add_argument("--out_html", type=str, required=True)
398
+ ap.add_argument("--out_csv", type=str)
399
+ ap.add_argument("--types", type=str, default=None)
400
+ ap.add_argument("--layer_min", type=int, default=None)
401
+ ap.add_argument("--layer_max", type=int, default=None)
402
+ ap.add_argument("--top_k", type=int, default=20)
403
+ args = ap.parse_args()
404
+
405
+ rows, attn_entropy = load_stats_json(args.stats_json)
406
+
407
+ allowed_types = None
408
+ if args.types:
409
+ allowed_types = [t.strip() for t in args.types.split(",") if t.strip()]
410
+
411
+ attn_rows = filter_rows(
412
+ rows,
413
+ allowed_types or ATTN_TYPES,
414
+ args.layer_min,
415
+ args.layer_max,
416
+ )
417
+ attn_rows = [r for r in attn_rows if r.mtype in ATTN_TYPES]
418
+
419
+ mlp_rows = filter_rows(
420
+ rows,
421
+ allowed_types or MLP_TYPES,
422
+ args.layer_min,
423
+ args.layer_max,
424
+ )
425
+ mlp_rows = [r for r in mlp_rows if r.mtype in MLP_TYPES]
426
+
427
+ all_rows = filter_rows(rows, allowed_types, args.layer_min, args.layer_max)
428
+
429
+ html = make_dashboard(attn_rows, mlp_rows, all_rows, attn_entropy, args.top_k)
430
+ out_html = Path(args.out_html)
431
+ out_html.parent.mkdir(parents=True, exist_ok=True)
432
+ with open(out_html, "w", encoding="utf-8") as f:
433
+ f.write(html)
434
+ print(f"Wrote HTML dashboard to: {out_html}")
435
+
436
+ if args.out_csv:
437
+ if pd is None:
438
+ print("pandas not available; CSV not written.")
439
+ else:
440
+ df = pd.DataFrame(
441
+ [
442
+ {
443
+ "name": r.name,
444
+ "layer": r.layer,
445
+ "type": r.mtype,
446
+ "token_rms_mean": r.token_rms_mean,
447
+ "token_rms_std": r.token_rms_std,
448
+ "mean": r.mean,
449
+ "std": r.std,
450
+ "min": r.min,
451
+ "max": r.max,
452
+ "zero_frac": r.zero_frac,
453
+ "count": r.count,
454
+ "nan_count": r.nan_count,
455
+ "inf_count": r.inf_count,
456
+ }
457
+ for r in all_rows
458
+ ]
459
+ )
460
+ out_csv = Path(args.out_csv)
461
+ out_csv.parent.mkdir(parents=True, exist_ok=True)
462
+ df.to_csv(out_csv, index=False)
463
+ print(f"Wrote CSV summary to: {out_csv}")
464
+
465
+
466
+ if __name__ == "__main__":
467
+ main()