anpaurehf commited on
Commit
c87638e
·
verified ·
1 Parent(s): 6f816b1

Upload 2 files

Browse files
v5/eval_inverter_v5_generate.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Eval V5 inverter on GPT-OSS-20B generated text (sliding windows, overlapping).
4
+
5
+ Fixes / robustness:
6
+ - GPT-OSS does NOT support SDPA in HF currently -> map sdpa -> eager.
7
+ - If flash_attention_2 requested but flash_attn missing -> fallback to eager.
8
+ - IMPORTANT: Do NOT enable output_router_logits during .generate() (it triggers
9
+ MoE aux-loss path that can crash). We only request router logits in the
10
+ separate router-collection pass.
11
+ - Auto-enable layer_gating if checkpoint contains encoder_in.layer_gate.
12
+ - By default, override inverter hyperparams from checkpoint config (prevents
13
+ state_dict shape mismatches).
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import random
20
+ import sys
21
+ from dataclasses import dataclass
22
+ from typing import Iterable, List, Tuple
23
+
24
+ import numpy as np
25
+ import torch
26
+ from transformers import AutoModelForCausalLM, AutoTokenizer
27
+
28
+ from train_inverter_v5 import EncoderOnlyModel
29
+
30
+
31
+ # ----------------- misc -----------------
32
+
33
+ def _set_seed(seed: int) -> None:
34
+ random.seed(seed)
35
+ np.random.seed(seed)
36
+ torch.manual_seed(seed)
37
+ torch.cuda.manual_seed_all(seed)
38
+
39
+
40
+ def _default_device() -> str:
41
+ return "cuda" if torch.cuda.is_available() else "cpu"
42
+
43
+
44
+ # ----------------- ckpt helpers -----------------
45
+
46
+ def _load_ckpt(path: str) -> dict:
47
+ return torch.load(path, map_location="cpu")
48
+
49
+
50
+ def _load_state_dict(path: str) -> dict:
51
+ ckpt = _load_ckpt(path)
52
+ state = ckpt.get("model", ckpt)
53
+ if any(k.startswith("_orig_mod.") for k in state.keys()):
54
+ state = {k.replace("_orig_mod.", ""): v for k, v in state.items()}
55
+ return state
56
+
57
+
58
+ def _load_ckpt_config(path: str) -> dict:
59
+ ckpt = _load_ckpt(path)
60
+ cfg = ckpt.get("config", None)
61
+ return cfg if isinstance(cfg, dict) else {}
62
+
63
+
64
+ # ----------------- router logits reshape -----------------
65
+
66
+ def _reshape_router_logits(
67
+ layer_logits: torch.Tensor,
68
+ batch_size: int,
69
+ seq_len: int,
70
+ layer_idx: int,
71
+ ) -> torch.Tensor:
72
+ """Normalize per-layer router logits into [B, S, E]."""
73
+ if layer_logits.ndim == 3:
74
+ if layer_logits.shape[0] == batch_size:
75
+ return layer_logits
76
+ if layer_logits.shape[1] == batch_size:
77
+ return layer_logits.permute(1, 0, 2)
78
+ raise RuntimeError(
79
+ f"Unexpected 3D router logits shape for layer {layer_idx}: "
80
+ f"{tuple(layer_logits.shape)} (batch={batch_size}, seq={seq_len})"
81
+ )
82
+
83
+ if layer_logits.ndim == 2:
84
+ if layer_logits.shape[0] == batch_size * seq_len:
85
+ return layer_logits.view(batch_size, seq_len, -1)
86
+ if layer_logits.shape[0] == seq_len and batch_size == 1:
87
+ return layer_logits.unsqueeze(0)
88
+ raise RuntimeError(
89
+ f"Unexpected 2D router logits shape for layer {layer_idx}: "
90
+ f"{tuple(layer_logits.shape)} (batch={batch_size}, seq={seq_len})"
91
+ )
92
+
93
+ raise RuntimeError(
94
+ f"Unexpected router logits rank for layer {layer_idx}: {tuple(layer_logits.shape)}"
95
+ )
96
+
97
+
98
+ # ----------------- LLM loading with attention fallback -----------------
99
+
100
+ def _load_llm_with_fallback(
101
+ model_name: str,
102
+ revision: str | None,
103
+ device: str,
104
+ attn_impl: str | None,
105
+ ):
106
+ """
107
+ GPT-OSS in HF:
108
+ - supports eager
109
+ - supports flash_attention_2 if flash_attn installed
110
+ - does NOT support sdpa (errors)
111
+ """
112
+ dtype = torch.bfloat16 if device != "cpu" else torch.float32
113
+
114
+ def _try(attn: str | None):
115
+ kwargs = {"revision": revision}
116
+ if attn is not None:
117
+ kwargs["attn_implementation"] = attn
118
+ # Prefer `dtype` (newer stacks), fall back to torch_dtype if needed.
119
+ try:
120
+ m = AutoModelForCausalLM.from_pretrained(
121
+ model_name,
122
+ dtype=dtype,
123
+ device_map={"": device} if device != "cpu" else "auto",
124
+ **kwargs,
125
+ )
126
+ except TypeError:
127
+ m = AutoModelForCausalLM.from_pretrained(
128
+ model_name,
129
+ torch_dtype=dtype,
130
+ device_map={"": device} if device != "cpu" else "auto",
131
+ **kwargs,
132
+ )
133
+ return m
134
+
135
+ # Normalize request
136
+ if attn_impl == "sdpa":
137
+ print("Note: GPT-OSS does not support SDPA; using eager instead.", file=sys.stderr)
138
+ attn_impl = "eager"
139
+
140
+ tried = []
141
+ llm = None
142
+
143
+ if attn_impl is not None:
144
+ try:
145
+ tried.append(attn_impl)
146
+ llm = _try(attn_impl)
147
+ except (ImportError, ValueError) as exc:
148
+ print(f"Warning: attn_implementation={attn_impl} failed: {exc}", file=sys.stderr)
149
+ llm = None
150
+
151
+ if llm is None:
152
+ if "eager" not in tried:
153
+ tried.append("eager")
154
+ llm = _try("eager")
155
+
156
+ llm.eval()
157
+ for p in llm.parameters():
158
+ p.requires_grad_(False)
159
+
160
+ # IMPORTANT: do NOT set llm.config.output_router_logits = True globally.
161
+ # We only request router logits in the router-collection forward pass.
162
+
163
+ # Also try to disable any aux-loss coefficients (harmless for inference).
164
+ for attr in ("router_aux_loss_coef", "aux_loss_coef", "moe_aux_loss_coef"):
165
+ if hasattr(llm.config, attr):
166
+ try:
167
+ setattr(llm.config, attr, 0.0)
168
+ except Exception:
169
+ pass
170
+
171
+ return llm, dtype
172
+
173
+
174
+ # ----------------- generation -----------------
175
+
176
+ @torch.inference_mode()
177
+ def generate_tokens(
178
+ llm,
179
+ tokenizer,
180
+ prompt: str,
181
+ max_new_tokens: int,
182
+ temperature: float,
183
+ top_p: float,
184
+ device: str,
185
+ ) -> Tuple[List[int], int]:
186
+ enc = tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
187
+ input_ids = enc["input_ids"].to(device)
188
+ prompt_len = int(input_ids.shape[1])
189
+
190
+ # Ensure we do NOT accidentally enable router logits during generation.
191
+ # Some configs might have it set; force-off temporarily.
192
+ had_cfg = hasattr(llm, "config")
193
+ old_output_router = getattr(llm.config, "output_router_logits", None) if had_cfg else None
194
+ if had_cfg and old_output_router is not None:
195
+ llm.config.output_router_logits = False
196
+
197
+ do_sample = temperature is not None and temperature > 0.0
198
+ try:
199
+ gen = llm.generate(
200
+ input_ids=input_ids,
201
+ max_new_tokens=max_new_tokens,
202
+ do_sample=do_sample,
203
+ temperature=temperature if do_sample else None,
204
+ top_p=top_p if do_sample else None,
205
+ use_cache=True,
206
+ pad_token_id=tokenizer.pad_token_id,
207
+ eos_token_id=tokenizer.eos_token_id,
208
+ )
209
+ finally:
210
+ if had_cfg and old_output_router is not None:
211
+ llm.config.output_router_logits = old_output_router
212
+
213
+ return gen[0].tolist(), prompt_len
214
+
215
+
216
+ # ----------------- router topk collection (chunked KV cache) -----------------
217
+
218
+ @torch.inference_mode()
219
+ def collect_router_topk_indices_chunked(
220
+ llm,
221
+ input_ids_cpu: torch.LongTensor, # [1, N] on CPU
222
+ topk: int,
223
+ chunk_size: int,
224
+ min_chunk_size: int,
225
+ save_dtype: torch.dtype = torch.int32,
226
+ ) -> torch.Tensor:
227
+ """
228
+ Returns:
229
+ topk_idx_cpu: [N, L, topk] on CPU
230
+ """
231
+ if input_ids_cpu.ndim != 2 or input_ids_cpu.shape[0] != 1:
232
+ raise ValueError("input_ids_cpu must have shape [1, N]")
233
+
234
+ device = next(llm.parameters()).device
235
+ n_tokens = int(input_ids_cpu.shape[1])
236
+ num_layers = int(llm.config.num_hidden_layers)
237
+ num_experts = int(llm.config.num_local_experts)
238
+ if topk > num_experts:
239
+ raise ValueError(f"router topk={topk} exceeds num_experts={num_experts}")
240
+
241
+ topk_idx_cpu = torch.empty((n_tokens, num_layers, topk), dtype=save_dtype, device="cpu")
242
+
243
+ past = None
244
+ pos = 0
245
+ batch_size = 1
246
+ chunk_size = max(1, min(int(chunk_size), n_tokens))
247
+ min_chunk_size = max(1, int(min_chunk_size))
248
+
249
+ while pos < n_tokens:
250
+ current_chunk = min(chunk_size, n_tokens - pos)
251
+ while True:
252
+ try:
253
+ chunk = input_ids_cpu[:, pos : pos + current_chunk].to(device, non_blocking=True)
254
+ chunk_len = int(chunk.shape[1])
255
+
256
+ outputs = llm(
257
+ input_ids=chunk,
258
+ use_cache=True,
259
+ past_key_values=past,
260
+ output_router_logits=True, # ONLY HERE
261
+ return_dict=True,
262
+ )
263
+ break
264
+ except torch.cuda.OutOfMemoryError:
265
+ if device.type != "cuda":
266
+ raise
267
+ torch.cuda.empty_cache()
268
+ if current_chunk <= min_chunk_size:
269
+ raise
270
+ current_chunk = max(min_chunk_size, current_chunk // 2)
271
+ chunk_size = min(chunk_size, current_chunk)
272
+
273
+ past = outputs.past_key_values
274
+ router_logits_layers = outputs.router_logits
275
+ if router_logits_layers is None:
276
+ raise RuntimeError("outputs.router_logits is None (model may not support router logits)")
277
+
278
+ per_layer = []
279
+ for i, layer_logits in enumerate(router_logits_layers):
280
+ reshaped = _reshape_router_logits(layer_logits, batch_size, chunk_len, i) # [1,S,E]
281
+ per_layer.append(reshaped[0]) # [S,E]
282
+
283
+ router_chunk = torch.stack(per_layer, dim=1) # [S, L, E]
284
+ idx = torch.topk(router_chunk, k=topk, dim=-1).indices # [S,L,topk]
285
+ topk_idx_cpu[pos : pos + chunk_len].copy_(idx.to("cpu", dtype=save_dtype))
286
+
287
+ pos += chunk_len
288
+
289
+ if device.type == "cuda":
290
+ torch.cuda.synchronize()
291
+
292
+ return topk_idx_cpu
293
+
294
+
295
+ # ----------------- sliding windows -----------------
296
+
297
+ def sliding_windows(
298
+ token_ids: List[int],
299
+ expert_topk_idx: torch.Tensor, # [N, L, K] on CPU
300
+ seq_len: int,
301
+ stride: int,
302
+ pad_id: int,
303
+ ) -> Iterable[Tuple[List[int], torch.Tensor, List[bool], List[bool]]]:
304
+ """
305
+ Counts each token exactly once:
306
+ - first window counts all real positions
307
+ - subsequent windows count only the NEW region (last `stride` positions)
308
+ """
309
+ n = len(token_ids)
310
+ if n == 0:
311
+ return
312
+
313
+ seq_len = int(seq_len)
314
+ stride = max(1, int(stride))
315
+ overlap_skip = max(0, seq_len - stride)
316
+
317
+ start = 0
318
+ first = True
319
+ while start < n:
320
+ end = min(start + seq_len, n)
321
+ win_len = end - start
322
+
323
+ win_tokens = token_ids[start:end]
324
+ win_experts = expert_topk_idx[start:end] # [win_len, L, K]
325
+
326
+ if win_len < seq_len:
327
+ win_tokens = win_tokens + [pad_id] * (seq_len - win_len)
328
+ if win_len > 0:
329
+ pad_row = win_experts[-1].unsqueeze(0) # [1,L,K]
330
+ else:
331
+ pad_row = torch.zeros_like(expert_topk_idx[:1])
332
+ pad_block = pad_row.expand(seq_len - win_len, -1, -1)
333
+ win_experts = torch.cat([win_experts, pad_block], dim=0)
334
+
335
+ attention_mask = [True] * win_len + [False] * (seq_len - win_len)
336
+
337
+ if first:
338
+ eval_mask = [True] * seq_len
339
+ first = False
340
+ else:
341
+ eval_mask = [False] * overlap_skip + [True] * (seq_len - overlap_skip)
342
+
343
+ yield win_tokens, win_experts, attention_mask, eval_mask
344
+ start += stride
345
+
346
+
347
+ # ----------------- main -----------------
348
+
349
+ def main():
350
+ parser = argparse.ArgumentParser(
351
+ description="Eval V5 inverter on GPT-OSS-20B generated text (sliding windows)."
352
+ )
353
+ parser.add_argument("--checkpoint", required=True)
354
+
355
+ # LLM
356
+ parser.add_argument("--model", default="openai/gpt-oss-20b")
357
+ parser.add_argument("--model-revision", default=None)
358
+ parser.add_argument(
359
+ "--attn-impl",
360
+ choices=["auto", "flash_attention_2", "sdpa", "eager"],
361
+ default="auto",
362
+ help="GPT-OSS: flash_attention_2 (needs flash_attn) or eager. sdpa maps to eager.",
363
+ )
364
+
365
+ # Generation
366
+ parser.add_argument("--prompt", action="append", default=None)
367
+ parser.add_argument("--gen-tokens", type=int, default=2048)
368
+ parser.add_argument("--temperature", type=float, default=1.0)
369
+ parser.add_argument("--top-p", type=float, default=0.95)
370
+ parser.add_argument("--seed", type=int, default=0)
371
+ parser.add_argument("--segments", type=int, default=1)
372
+ parser.add_argument("--include-prompt", action="store_true")
373
+
374
+ # Router collection
375
+ parser.add_argument("--router-topk", type=int, default=4)
376
+ parser.add_argument("--router-chunk-size", type=int, default=1024)
377
+ parser.add_argument("--router-min-chunk-size", type=int, default=128)
378
+
379
+ # Sliding window eval
380
+ parser.add_argument("--seq-len", type=int, default=32)
381
+ parser.add_argument("--stride", type=int, default=8)
382
+ parser.add_argument("--batch-size", type=int, default=8)
383
+ parser.add_argument("--eval-topk", default="1,5,10")
384
+
385
+ # Inverter arch (overridden from ckpt config by default)
386
+ parser.add_argument("--use-ckpt-config", action="store_true", default=True)
387
+ parser.add_argument("--no-use-ckpt-config", action="store_false", dest="use_ckpt_config")
388
+ parser.add_argument("--layers", type=int, default=24)
389
+ parser.add_argument("--d-model", type=int, default=768)
390
+ parser.add_argument("--n-head", type=int, default=12)
391
+ parser.add_argument("--d-ff", type=int, default=2048)
392
+ parser.add_argument("--n-layer", type=int, default=6)
393
+ parser.add_argument("--layer-hidden", type=int, default=64)
394
+ parser.add_argument("--layer-proj", type=int, default=64)
395
+ parser.add_argument("--dropout", type=float, default=0.1)
396
+ parser.add_argument("--logit-softcap", type=float, default=0.0)
397
+ parser.add_argument("--layer-gating", action="store_true", default=False)
398
+
399
+ parser.add_argument("--hard-exit", action="store_true")
400
+ parser.add_argument("--debug", action="store_true")
401
+ args = parser.parse_args()
402
+
403
+ device = _default_device()
404
+ if device == "cuda":
405
+ torch.backends.cuda.matmul.allow_tf32 = True
406
+ torch.backends.cudnn.allow_tf32 = True
407
+ torch.set_float32_matmul_precision("high")
408
+
409
+ _set_seed(args.seed)
410
+
411
+ # Load ckpt config/state early
412
+ ckpt_cfg = _load_ckpt_config(args.checkpoint)
413
+ state_dict = _load_state_dict(args.checkpoint)
414
+
415
+ # Auto-enable gating if checkpoint has it
416
+ ckpt_has_gate = bool(ckpt_cfg.get("layer_gating", False)) or ("encoder_in.layer_gate" in state_dict)
417
+ if ckpt_has_gate and not args.layer_gating:
418
+ print("Note: checkpoint contains encoder_in.layer_gate; enabling layer_gating for eval.", file=sys.stderr)
419
+ args.layer_gating = True
420
+
421
+ # Override arch from checkpoint config to avoid mismatches
422
+ if args.use_ckpt_config and ckpt_cfg:
423
+ mapping = {
424
+ "seq_len": "seq_len",
425
+ "layers": "layers",
426
+ "d_model": "d_model",
427
+ "n_head": "n_head",
428
+ "d_ff": "d_ff",
429
+ "n_layer": "n_layer",
430
+ "layer_hidden": "layer_hidden",
431
+ "layer_proj": "layer_proj",
432
+ "dropout": "dropout",
433
+ "logit_softcap": "logit_softcap",
434
+ }
435
+ for ck, ak in mapping.items():
436
+ if ck in ckpt_cfg:
437
+ setattr(args, ak, ckpt_cfg[ck])
438
+
439
+ # Tokenizer + LLM
440
+ tokenizer = AutoTokenizer.from_pretrained(args.model, revision=args.model_revision)
441
+ if tokenizer.pad_token_id is None:
442
+ tokenizer.pad_token_id = tokenizer.eos_token_id
443
+
444
+ attn_impl = args.attn_impl
445
+ if attn_impl == "auto":
446
+ attn_impl = "flash_attention_2" if device != "cpu" else "eager"
447
+
448
+ llm, _llm_dtype = _load_llm_with_fallback(args.model, args.model_revision, device, attn_impl)
449
+
450
+ # Build inverter
451
+ inv = EncoderOnlyModel(
452
+ vocab_size=len(tokenizer),
453
+ num_experts=32,
454
+ num_layers=int(args.layers),
455
+ topk=int(args.router_topk),
456
+ d_model=int(args.d_model),
457
+ n_head=int(args.n_head),
458
+ d_ff=int(args.d_ff),
459
+ n_layer=int(args.n_layer),
460
+ dropout=float(args.dropout),
461
+ max_len=int(args.seq_len),
462
+ layer_gating=bool(args.layer_gating),
463
+ logit_softcap=float(args.logit_softcap),
464
+ layer_hidden=int(args.layer_hidden),
465
+ layer_proj=int(args.layer_proj),
466
+ ).to(device)
467
+
468
+ inv.load_state_dict(state_dict, strict=True)
469
+ inv.eval()
470
+
471
+ eval_topk = sorted({int(x) for x in args.eval_topk.split(",") if x.strip() and int(x) > 0})
472
+ correct = {k: 0 for k in eval_topk}
473
+ total = 0
474
+
475
+ prompts = args.prompt or [
476
+ "Write a concise overview of black holes, including formation, event horizon, and Hawking radiation.\n\n",
477
+ "Explain transformers and attention in simple terms.\n\n",
478
+ "A dialogue between a detective and a chef.\n\n",
479
+ "Summarize the pros and cons of open-source AI models.\n\n",
480
+ ]
481
+
482
+ def run_window_batch(batch_tokens, batch_experts, batch_attn, batch_evalmask):
483
+ nonlocal total
484
+ input_ids = torch.tensor(batch_tokens, dtype=torch.long, device=device)
485
+ expert_idx = torch.stack(batch_experts, dim=0).to(device=device, dtype=torch.long) # [B,S,L,K]
486
+ attention_mask = torch.tensor(batch_attn, dtype=torch.bool, device=device)
487
+ eval_mask = torch.tensor(batch_evalmask, dtype=torch.bool, device=device)
488
+ count_mask = attention_mask & eval_mask
489
+
490
+ with torch.autocast(device_type=device, dtype=torch.bfloat16, enabled=(device == "cuda")):
491
+ logits = inv(expert_idx, attention_mask)
492
+
493
+ for k in eval_topk:
494
+ topk_pred = torch.topk(logits, k=k, dim=-1).indices
495
+ match = (topk_pred == input_ids.unsqueeze(-1)).any(dim=-1)
496
+ match = match & count_mask
497
+ correct[k] += int(match.sum().item())
498
+
499
+ total += int(count_mask.sum().item())
500
+
501
+ # segments
502
+ for seg in range(int(args.segments)):
503
+ prompt = prompts[seg % len(prompts)]
504
+
505
+ full_ids, prompt_len = generate_tokens(
506
+ llm=llm,
507
+ tokenizer=tokenizer,
508
+ prompt=prompt,
509
+ max_new_tokens=max(1, int(args.gen_tokens)),
510
+ temperature=float(args.temperature),
511
+ top_p=float(args.top_p),
512
+ device=device,
513
+ )
514
+
515
+ # Collect router indices on full sequence
516
+ input_ids_cpu = torch.tensor([full_ids], dtype=torch.long, device="cpu")
517
+ topk_idx_cpu = collect_router_topk_indices_chunked(
518
+ llm=llm,
519
+ input_ids_cpu=input_ids_cpu,
520
+ topk=int(args.router_topk),
521
+ chunk_size=max(1, int(args.router_chunk_size)),
522
+ min_chunk_size=max(1, int(args.router_min_chunk_size)),
523
+ save_dtype=torch.int32,
524
+ ) # [N, L, K] CPU
525
+
526
+ if (not args.include_prompt) and prompt_len > 0:
527
+ token_ids = full_ids[prompt_len:]
528
+ topk_idx_cpu = topk_idx_cpu[prompt_len:]
529
+ else:
530
+ token_ids = full_ids
531
+
532
+ if len(token_ids) == 0:
533
+ continue
534
+
535
+ # truncate router layers
536
+ L = int(args.layers)
537
+ topk_idx_cpu = topk_idx_cpu[:, :L, :]
538
+
539
+ # sliding eval
540
+ batch_tokens = []
541
+ batch_experts = []
542
+ batch_attn = []
543
+ batch_evalmask = []
544
+
545
+ for win_tokens, win_experts, attn_mask, eval_mask in sliding_windows(
546
+ token_ids=token_ids,
547
+ expert_topk_idx=topk_idx_cpu,
548
+ seq_len=int(args.seq_len),
549
+ stride=int(args.stride),
550
+ pad_id=int(tokenizer.pad_token_id),
551
+ ):
552
+ batch_tokens.append(win_tokens)
553
+ batch_experts.append(win_experts)
554
+ batch_attn.append(attn_mask)
555
+ batch_evalmask.append(eval_mask)
556
+
557
+ if len(batch_tokens) >= int(args.batch_size):
558
+ run_window_batch(batch_tokens, batch_experts, batch_attn, batch_evalmask)
559
+ batch_tokens, batch_experts, batch_attn, batch_evalmask = [], [], [], []
560
+
561
+ if batch_tokens:
562
+ run_window_batch(batch_tokens, batch_experts, batch_attn, batch_evalmask)
563
+
564
+ acc = {str(k): (correct[k] / total if total > 0 else 0.0) for k in eval_topk}
565
+
566
+ if args.debug:
567
+ vals = [acc[str(k)] for k in eval_topk]
568
+ if any(vals[i] > vals[i + 1] + 1e-9 for i in range(len(vals) - 1)):
569
+ print("WARNING: accuracy is not monotonic with k; check eval.", file=sys.stderr)
570
+
571
+ result = {
572
+ "tokens": int(total),
573
+ "accuracy": acc,
574
+ "config": {
575
+ "llm": args.model,
576
+ "checkpoint": args.checkpoint,
577
+ "seq_len": int(args.seq_len),
578
+ "stride": int(args.stride),
579
+ "layers": int(args.layers),
580
+ "router_topk": int(args.router_topk),
581
+ "segments": int(args.segments),
582
+ "gen_tokens_per_segment": int(args.gen_tokens),
583
+ "include_prompt": bool(args.include_prompt),
584
+ "attn_impl_requested": args.attn_impl,
585
+ "layer_gating": bool(args.layer_gating),
586
+ "use_ckpt_config": bool(args.use_ckpt_config),
587
+ },
588
+ }
589
+ print(json.dumps(result, indent=2))
590
+
591
+ if args.hard_exit:
592
+ os._exit(0)
593
+
594
+
595
+ if __name__ == "__main__":
596
+ main()
v5/eval_inverter_v5_generate_chunks.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Eval V5 inverter on GPT-OSS-20B generated text using NON-overlapping chunks of seq_len
4
+ (default 32). (No sliding windows.)
5
+
6
+ Fixes / robustness:
7
+ - GPT-OSS does NOT support SDPA in HF currently -> map sdpa -> eager.
8
+ - If flash_attention_2 requested but flash_attn missing -> fallback to eager.
9
+ - IMPORTANT: Do NOT enable output_router_logits during .generate().
10
+ We only request router logits in the router-collection pass.
11
+ - Auto-enable layer_gating if checkpoint contains encoder_in.layer_gate.
12
+ - By default, override inverter hyperparams from checkpoint config (prevents shape mismatches).
13
+ """
14
+
15
+ import argparse
16
+ import json
17
+ import os
18
+ import random
19
+ import sys
20
+ from typing import Iterable, List, Tuple
21
+
22
+ import numpy as np
23
+ import torch
24
+ from transformers import AutoModelForCausalLM, AutoTokenizer
25
+
26
+ from train_inverter_v5 import EncoderOnlyModel
27
+
28
+
29
+ # ----------------- misc -----------------
30
+
31
+ def _set_seed(seed: int) -> None:
32
+ random.seed(seed)
33
+ np.random.seed(seed)
34
+ torch.manual_seed(seed)
35
+ torch.cuda.manual_seed_all(seed)
36
+
37
+
38
+ def _default_device() -> str:
39
+ return "cuda" if torch.cuda.is_available() else "cpu"
40
+
41
+
42
+ # ----------------- ckpt helpers -----------------
43
+
44
+ def _load_ckpt(path: str) -> dict:
45
+ return torch.load(path, map_location="cpu")
46
+
47
+
48
+ def _load_state_dict(path: str) -> dict:
49
+ ckpt = _load_ckpt(path)
50
+ state = ckpt.get("model", ckpt)
51
+ if any(k.startswith("_orig_mod.") for k in state.keys()):
52
+ state = {k.replace("_orig_mod.", ""): v for k, v in state.items()}
53
+ return state
54
+
55
+
56
+ def _load_ckpt_config(path: str) -> dict:
57
+ ckpt = _load_ckpt(path)
58
+ cfg = ckpt.get("config", None)
59
+ return cfg if isinstance(cfg, dict) else {}
60
+
61
+
62
+ # ----------------- router logits reshape -----------------
63
+
64
+ def _reshape_router_logits(
65
+ layer_logits: torch.Tensor,
66
+ batch_size: int,
67
+ seq_len: int,
68
+ layer_idx: int,
69
+ ) -> torch.Tensor:
70
+ """Normalize per-layer router logits into [B, S, E]."""
71
+ if layer_logits.ndim == 3:
72
+ if layer_logits.shape[0] == batch_size:
73
+ return layer_logits
74
+ if layer_logits.shape[1] == batch_size:
75
+ return layer_logits.permute(1, 0, 2)
76
+ raise RuntimeError(
77
+ f"Unexpected 3D router logits shape for layer {layer_idx}: "
78
+ f"{tuple(layer_logits.shape)} (batch={batch_size}, seq={seq_len})"
79
+ )
80
+
81
+ if layer_logits.ndim == 2:
82
+ if layer_logits.shape[0] == batch_size * seq_len:
83
+ return layer_logits.view(batch_size, seq_len, -1)
84
+ if layer_logits.shape[0] == seq_len and batch_size == 1:
85
+ return layer_logits.unsqueeze(0)
86
+ raise RuntimeError(
87
+ f"Unexpected 2D router logits shape for layer {layer_idx}: "
88
+ f"{tuple(layer_logits.shape)} (batch={batch_size}, seq={seq_len})"
89
+ )
90
+
91
+ raise RuntimeError(
92
+ f"Unexpected router logits rank for layer {layer_idx}: {tuple(layer_logits.shape)}"
93
+ )
94
+
95
+
96
+ # ----------------- LLM loading with attention fallback -----------------
97
+
98
+ def _load_llm_with_fallback(
99
+ model_name: str,
100
+ revision: str | None,
101
+ device: str,
102
+ attn_impl: str | None,
103
+ ):
104
+ """
105
+ GPT-OSS in HF:
106
+ - supports eager
107
+ - supports flash_attention_2 if flash_attn installed
108
+ - does NOT support sdpa (errors)
109
+ """
110
+ dtype = torch.bfloat16 if device != "cpu" else torch.float32
111
+
112
+ def _try(attn: str | None):
113
+ kwargs = {"revision": revision}
114
+ if attn is not None:
115
+ kwargs["attn_implementation"] = attn
116
+ try:
117
+ m = AutoModelForCausalLM.from_pretrained(
118
+ model_name,
119
+ dtype=dtype,
120
+ device_map={"": device} if device != "cpu" else "auto",
121
+ **kwargs,
122
+ )
123
+ except TypeError:
124
+ m = AutoModelForCausalLM.from_pretrained(
125
+ model_name,
126
+ torch_dtype=dtype,
127
+ device_map={"": device} if device != "cpu" else "auto",
128
+ **kwargs,
129
+ )
130
+ return m
131
+
132
+ if attn_impl == "sdpa":
133
+ print("Note: GPT-OSS does not support SDPA; using eager instead.", file=sys.stderr)
134
+ attn_impl = "eager"
135
+
136
+ tried = []
137
+ llm = None
138
+
139
+ if attn_impl is not None:
140
+ try:
141
+ tried.append(attn_impl)
142
+ llm = _try(attn_impl)
143
+ except (ImportError, ValueError) as exc:
144
+ print(f"Warning: attn_implementation={attn_impl} failed: {exc}", file=sys.stderr)
145
+ llm = None
146
+
147
+ if llm is None:
148
+ if "eager" not in tried:
149
+ tried.append("eager")
150
+ llm = _try("eager")
151
+
152
+ llm.eval()
153
+ for p in llm.parameters():
154
+ p.requires_grad_(False)
155
+
156
+ # Do NOT set output_router_logits globally.
157
+ for attr in ("router_aux_loss_coef", "aux_loss_coef", "moe_aux_loss_coef"):
158
+ if hasattr(llm.config, attr):
159
+ try:
160
+ setattr(llm.config, attr, 0.0)
161
+ except Exception:
162
+ pass
163
+
164
+ return llm, dtype
165
+
166
+
167
+ # ----------------- generation -----------------
168
+
169
+ @torch.inference_mode()
170
+ def generate_tokens(
171
+ llm,
172
+ tokenizer,
173
+ prompt: str,
174
+ max_new_tokens: int,
175
+ temperature: float,
176
+ top_p: float,
177
+ device: str,
178
+ ) -> Tuple[List[int], int]:
179
+ enc = tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
180
+ input_ids = enc["input_ids"].to(device)
181
+ prompt_len = int(input_ids.shape[1])
182
+
183
+ # Force router logits OFF during generation (prevents GPT-OSS aux-loss crash).
184
+ old_output_router = getattr(llm.config, "output_router_logits", None)
185
+ if old_output_router is not None:
186
+ llm.config.output_router_logits = False
187
+
188
+ do_sample = temperature is not None and temperature > 0.0
189
+ try:
190
+ gen = llm.generate(
191
+ input_ids=input_ids,
192
+ max_new_tokens=max_new_tokens,
193
+ do_sample=do_sample,
194
+ temperature=temperature if do_sample else None,
195
+ top_p=top_p if do_sample else None,
196
+ use_cache=True,
197
+ pad_token_id=tokenizer.pad_token_id,
198
+ eos_token_id=tokenizer.eos_token_id,
199
+ )
200
+ finally:
201
+ if old_output_router is not None:
202
+ llm.config.output_router_logits = old_output_router
203
+
204
+ return gen[0].tolist(), prompt_len
205
+
206
+
207
+ # ----------------- router topk collection (chunked KV cache) -----------------
208
+
209
+ @torch.inference_mode()
210
+ def collect_router_topk_indices_chunked(
211
+ llm,
212
+ input_ids_cpu: torch.LongTensor, # [1, N] on CPU
213
+ topk: int,
214
+ chunk_size: int,
215
+ min_chunk_size: int,
216
+ save_dtype: torch.dtype = torch.int32,
217
+ ) -> torch.Tensor:
218
+ """
219
+ Returns:
220
+ topk_idx_cpu: [N, L, topk] on CPU
221
+ """
222
+ if input_ids_cpu.ndim != 2 or input_ids_cpu.shape[0] != 1:
223
+ raise ValueError("input_ids_cpu must have shape [1, N]")
224
+
225
+ device = next(llm.parameters()).device
226
+ n_tokens = int(input_ids_cpu.shape[1])
227
+ num_layers = int(llm.config.num_hidden_layers)
228
+ num_experts = int(llm.config.num_local_experts)
229
+ if topk > num_experts:
230
+ raise ValueError(f"router topk={topk} exceeds num_experts={num_experts}")
231
+
232
+ topk_idx_cpu = torch.empty((n_tokens, num_layers, topk), dtype=save_dtype, device="cpu")
233
+
234
+ past = None
235
+ pos = 0
236
+ batch_size = 1
237
+ chunk_size = max(1, min(int(chunk_size), n_tokens))
238
+ min_chunk_size = max(1, int(min_chunk_size))
239
+
240
+ while pos < n_tokens:
241
+ current_chunk = min(chunk_size, n_tokens - pos)
242
+ while True:
243
+ try:
244
+ chunk = input_ids_cpu[:, pos : pos + current_chunk].to(device, non_blocking=True)
245
+ chunk_len = int(chunk.shape[1])
246
+
247
+ outputs = llm(
248
+ input_ids=chunk,
249
+ use_cache=True,
250
+ past_key_values=past,
251
+ output_router_logits=True,
252
+ return_dict=True,
253
+ )
254
+ break
255
+ except torch.cuda.OutOfMemoryError:
256
+ if device.type != "cuda":
257
+ raise
258
+ torch.cuda.empty_cache()
259
+ if current_chunk <= min_chunk_size:
260
+ raise
261
+ current_chunk = max(min_chunk_size, current_chunk // 2)
262
+ chunk_size = min(chunk_size, current_chunk)
263
+
264
+ past = outputs.past_key_values
265
+ router_logits_layers = outputs.router_logits
266
+ if router_logits_layers is None:
267
+ raise RuntimeError("outputs.router_logits is None (model may not support router logits)")
268
+
269
+ per_layer = []
270
+ for i, layer_logits in enumerate(router_logits_layers):
271
+ reshaped = _reshape_router_logits(layer_logits, batch_size, chunk_len, i) # [1,S,E]
272
+ per_layer.append(reshaped[0]) # [S,E]
273
+
274
+ router_chunk = torch.stack(per_layer, dim=1) # [S, L, E]
275
+ idx = torch.topk(router_chunk, k=topk, dim=-1).indices # [S,L,topk]
276
+ topk_idx_cpu[pos : pos + chunk_len].copy_(idx.to("cpu", dtype=save_dtype))
277
+
278
+ pos += chunk_len
279
+
280
+ if device.type == "cuda":
281
+ torch.cuda.synchronize()
282
+
283
+ return topk_idx_cpu
284
+
285
+
286
+ # ----------------- non-overlapping chunks of seq_len -----------------
287
+
288
+ def non_overlapping_chunks(
289
+ token_ids: List[int],
290
+ expert_topk_idx: torch.Tensor, # [N, L, K] on CPU
291
+ seq_len: int,
292
+ pad_id: int,
293
+ ) -> Iterable[Tuple[List[int], torch.Tensor, List[bool]]]:
294
+ """
295
+ Yield non-overlapping chunks of exactly seq_len:
296
+ - attention_mask marks real tokens
297
+ - last chunk is padded if needed (and we only count real tokens via attention_mask)
298
+ """
299
+ n = len(token_ids)
300
+ if n == 0:
301
+ return
302
+
303
+ seq_len = int(seq_len)
304
+ start = 0
305
+ while start < n:
306
+ end = min(start + seq_len, n)
307
+ clen = end - start
308
+
309
+ chunk_tokens = token_ids[start:end]
310
+ chunk_experts = expert_topk_idx[start:end] # [clen, L, K]
311
+
312
+ if clen < seq_len:
313
+ chunk_tokens = chunk_tokens + [pad_id] * (seq_len - clen)
314
+ if clen > 0:
315
+ pad_row = chunk_experts[-1].unsqueeze(0)
316
+ else:
317
+ pad_row = torch.zeros_like(expert_topk_idx[:1])
318
+ pad_block = pad_row.expand(seq_len - clen, -1, -1)
319
+ chunk_experts = torch.cat([chunk_experts, pad_block], dim=0)
320
+
321
+ attention_mask = [True] * clen + [False] * (seq_len - clen)
322
+
323
+ yield chunk_tokens, chunk_experts, attention_mask
324
+ start += seq_len
325
+
326
+
327
+ # ----------------- main -----------------
328
+
329
+ def main():
330
+ parser = argparse.ArgumentParser(
331
+ description="Eval V5 inverter on GPT-OSS-20B generated text (non-overlapping 32-token chunks)."
332
+ )
333
+ parser.add_argument("--checkpoint", required=True)
334
+
335
+ # LLM
336
+ parser.add_argument("--model", default="openai/gpt-oss-20b")
337
+ parser.add_argument("--model-revision", default=None)
338
+ parser.add_argument(
339
+ "--attn-impl",
340
+ choices=["auto", "flash_attention_2", "sdpa", "eager"],
341
+ default="auto",
342
+ help="GPT-OSS: flash_attention_2 (needs flash_attn) or eager. sdpa maps to eager.",
343
+ )
344
+
345
+ # Generation
346
+ parser.add_argument("--prompt", action="append", default=None)
347
+ parser.add_argument("--gen-tokens", type=int, default=2048)
348
+ parser.add_argument("--temperature", type=float, default=1.0)
349
+ parser.add_argument("--top-p", type=float, default=0.95)
350
+ parser.add_argument("--seed", type=int, default=0)
351
+ parser.add_argument("--segments", type=int, default=1)
352
+ parser.add_argument("--include-prompt", action="store_true")
353
+
354
+ # Router collection
355
+ parser.add_argument("--router-topk", type=int, default=4)
356
+ parser.add_argument("--router-chunk-size", type=int, default=1024)
357
+ parser.add_argument("--router-min-chunk-size", type=int, default=128)
358
+
359
+ # Chunk eval
360
+ parser.add_argument("--seq-len", type=int, default=32)
361
+ parser.add_argument("--batch-size", type=int, default=8)
362
+ parser.add_argument("--eval-topk", default="1,5,10")
363
+
364
+ # Inverter arch (overridden from ckpt config by default)
365
+ parser.add_argument("--use-ckpt-config", action="store_true", default=True)
366
+ parser.add_argument("--no-use-ckpt-config", action="store_false", dest="use_ckpt_config")
367
+ parser.add_argument("--layers", type=int, default=24)
368
+ parser.add_argument("--d-model", type=int, default=768)
369
+ parser.add_argument("--n-head", type=int, default=12)
370
+ parser.add_argument("--d-ff", type=int, default=2048)
371
+ parser.add_argument("--n-layer", type=int, default=6)
372
+ parser.add_argument("--layer-hidden", type=int, default=64)
373
+ parser.add_argument("--layer-proj", type=int, default=64)
374
+ parser.add_argument("--dropout", type=float, default=0.1)
375
+ parser.add_argument("--logit-softcap", type=float, default=0.0)
376
+ parser.add_argument("--layer-gating", action="store_true", default=False)
377
+
378
+ parser.add_argument("--hard-exit", action="store_true")
379
+ parser.add_argument("--debug", action="store_true")
380
+ args = parser.parse_args()
381
+
382
+ device = _default_device()
383
+ if device == "cuda":
384
+ torch.backends.cuda.matmul.allow_tf32 = True
385
+ torch.backends.cudnn.allow_tf32 = True
386
+ torch.set_float32_matmul_precision("high")
387
+
388
+ _set_seed(args.seed)
389
+
390
+ ckpt_cfg = _load_ckpt_config(args.checkpoint)
391
+ state_dict = _load_state_dict(args.checkpoint)
392
+
393
+ ckpt_has_gate = bool(ckpt_cfg.get("layer_gating", False)) or ("encoder_in.layer_gate" in state_dict)
394
+ if ckpt_has_gate and not args.layer_gating:
395
+ print("Note: checkpoint contains encoder_in.layer_gate; enabling layer_gating for eval.", file=sys.stderr)
396
+ args.layer_gating = True
397
+
398
+ if args.use_ckpt_config and ckpt_cfg:
399
+ mapping = {
400
+ "seq_len": "seq_len",
401
+ "layers": "layers",
402
+ "d_model": "d_model",
403
+ "n_head": "n_head",
404
+ "d_ff": "d_ff",
405
+ "n_layer": "n_layer",
406
+ "layer_hidden": "layer_hidden",
407
+ "layer_proj": "layer_proj",
408
+ "dropout": "dropout",
409
+ "logit_softcap": "logit_softcap",
410
+ }
411
+ for ck, ak in mapping.items():
412
+ if ck in ckpt_cfg:
413
+ setattr(args, ak, ckpt_cfg[ck])
414
+
415
+ tokenizer = AutoTokenizer.from_pretrained(args.model, revision=args.model_revision)
416
+ if tokenizer.pad_token_id is None:
417
+ tokenizer.pad_token_id = tokenizer.eos_token_id
418
+
419
+ attn_impl = args.attn_impl
420
+ if attn_impl == "auto":
421
+ attn_impl = "flash_attention_2" if device != "cpu" else "eager"
422
+
423
+ llm, _llm_dtype = _load_llm_with_fallback(args.model, args.model_revision, device, attn_impl)
424
+
425
+ inv = EncoderOnlyModel(
426
+ vocab_size=len(tokenizer),
427
+ num_experts=32,
428
+ num_layers=int(args.layers),
429
+ topk=int(args.router_topk),
430
+ d_model=int(args.d_model),
431
+ n_head=int(args.n_head),
432
+ d_ff=int(args.d_ff),
433
+ n_layer=int(args.n_layer),
434
+ dropout=float(args.dropout),
435
+ max_len=int(args.seq_len),
436
+ layer_gating=bool(args.layer_gating),
437
+ logit_softcap=float(args.logit_softcap),
438
+ layer_hidden=int(args.layer_hidden),
439
+ layer_proj=int(args.layer_proj),
440
+ ).to(device)
441
+
442
+ inv.load_state_dict(state_dict, strict=True)
443
+ inv.eval()
444
+
445
+ eval_topk = sorted({int(x) for x in args.eval_topk.split(",") if x.strip() and int(x) > 0})
446
+ correct = {k: 0 for k in eval_topk}
447
+ total = 0
448
+
449
+ prompts = args.prompt or [
450
+ "Write a concise overview of black holes, including formation, event horizon, and Hawking radiation.\n\n",
451
+ "Explain transformers and attention in simple terms.\n\n",
452
+ "A dialogue between a detective and a chef.\n\n",
453
+ "Summarize the pros and cons of open-source AI models.\n\n",
454
+ ]
455
+
456
+ def run_chunk_batch(batch_tokens, batch_experts, batch_attn):
457
+ nonlocal total
458
+ input_ids = torch.tensor(batch_tokens, dtype=torch.long, device=device)
459
+ expert_idx = torch.stack(batch_experts, dim=0).to(device=device, dtype=torch.long) # [B,S,L,K]
460
+ attention_mask = torch.tensor(batch_attn, dtype=torch.bool, device=device)
461
+ count_mask = attention_mask
462
+
463
+ with torch.autocast(device_type=device, dtype=torch.bfloat16, enabled=(device == "cuda")):
464
+ logits = inv(expert_idx, attention_mask)
465
+
466
+ for k in eval_topk:
467
+ topk_pred = torch.topk(logits, k=k, dim=-1).indices
468
+ match = (topk_pred == input_ids.unsqueeze(-1)).any(dim=-1)
469
+ match = match & count_mask
470
+ correct[k] += int(match.sum().item())
471
+
472
+ total += int(count_mask.sum().item())
473
+
474
+ for seg in range(int(args.segments)):
475
+ prompt = prompts[seg % len(prompts)]
476
+
477
+ full_ids, prompt_len = generate_tokens(
478
+ llm=llm,
479
+ tokenizer=tokenizer,
480
+ prompt=prompt,
481
+ max_new_tokens=max(1, int(args.gen_tokens)),
482
+ temperature=float(args.temperature),
483
+ top_p=float(args.top_p),
484
+ device=device,
485
+ )
486
+
487
+ input_ids_cpu = torch.tensor([full_ids], dtype=torch.long, device="cpu")
488
+ topk_idx_cpu = collect_router_topk_indices_chunked(
489
+ llm=llm,
490
+ input_ids_cpu=input_ids_cpu,
491
+ topk=int(args.router_topk),
492
+ chunk_size=max(1, int(args.router_chunk_size)),
493
+ min_chunk_size=max(1, int(args.router_min_chunk_size)),
494
+ save_dtype=torch.int32,
495
+ ) # [N, L, K]
496
+
497
+ if (not args.include_prompt) and prompt_len > 0:
498
+ token_ids = full_ids[prompt_len:]
499
+ topk_idx_cpu = topk_idx_cpu[prompt_len:]
500
+ else:
501
+ token_ids = full_ids
502
+
503
+ if len(token_ids) == 0:
504
+ continue
505
+
506
+ L = int(args.layers)
507
+ topk_idx_cpu = topk_idx_cpu[:, :L, :]
508
+
509
+ batch_tokens = []
510
+ batch_experts = []
511
+ batch_attn = []
512
+
513
+ for chunk_tokens, chunk_experts, attn_mask in non_overlapping_chunks(
514
+ token_ids=token_ids,
515
+ expert_topk_idx=topk_idx_cpu,
516
+ seq_len=int(args.seq_len),
517
+ pad_id=int(tokenizer.pad_token_id),
518
+ ):
519
+ batch_tokens.append(chunk_tokens)
520
+ batch_experts.append(chunk_experts)
521
+ batch_attn.append(attn_mask)
522
+
523
+ if len(batch_tokens) >= int(args.batch_size):
524
+ run_chunk_batch(batch_tokens, batch_experts, batch_attn)
525
+ batch_tokens, batch_experts, batch_attn = [], [], []
526
+
527
+ if batch_tokens:
528
+ run_chunk_batch(batch_tokens, batch_experts, batch_attn)
529
+
530
+ acc = {str(k): (correct[k] / total if total > 0 else 0.0) for k in eval_topk}
531
+
532
+ if args.debug:
533
+ vals = [acc[str(k)] for k in eval_topk]
534
+ if any(vals[i] > vals[i + 1] + 1e-9 for i in range(len(vals) - 1)):
535
+ print("WARNING: accuracy is not monotonic with k; check eval.", file=sys.stderr)
536
+
537
+ result = {
538
+ "tokens": int(total),
539
+ "accuracy": acc,
540
+ "config": {
541
+ "llm": args.model,
542
+ "checkpoint": args.checkpoint,
543
+ "seq_len": int(args.seq_len),
544
+ "layers": int(args.layers),
545
+ "router_topk": int(args.router_topk),
546
+ "segments": int(args.segments),
547
+ "gen_tokens_per_segment": int(args.gen_tokens),
548
+ "include_prompt": bool(args.include_prompt),
549
+ "attn_impl_requested": args.attn_impl,
550
+ "layer_gating": bool(args.layer_gating),
551
+ "use_ckpt_config": bool(args.use_ckpt_config),
552
+ },
553
+ }
554
+ print(json.dumps(result, indent=2))
555
+
556
+ if args.hard_exit:
557
+ os._exit(0)
558
+
559
+
560
+ if __name__ == "__main__":
561
+ main()