File size: 24,085 Bytes
830e33a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#!/usr/bin/env python3
"""Training-free looped LFM3: repeat a mid-stack window with damped residual steps.

Implements the "run x layers K times, 1/K of a step per pass" wrapper from
arXiv 2605.23872 (training-free looped transformers) as a *static* graph:
the window is physically duplicated and every application's residual output is
damped by alpha, so the result is a plain deeper HF model that supports
generate()/KV-cache with no runtime wrapper.

Why the damping goes in the sandwich norms
------------------------------------------
Each LFM3 layer is  h' = h + post_op_norm(op(pre_norm(h))) + post_ffn_norm(ffn(...)).
Scaling o_proj/out_proj/w2 does NOT damp the branch: the post-norm is RMSNorm, which
divides out the scale. Scaling `post_operator_norm.weight` / `post_ffn_norm.weight`
by alpha scales the branch output by exactly alpha, which is the step damping.

  alpha=1/reps, reps=2  -> damped Euler K=2: x <- x + 1/2 (g(x) - x), twice
  alpha=1.0,    reps=2  -> naive loop (control: paper says this degrades)
  alpha=0.75,   reps=1  -> static equivalent of the paper's K=2 RK beta=0.5

Subcommands: identity | ppl | grid | bake | gsm8k
"""
import argparse, copy, json, math, os, re, sys, time
import torch
import torch.nn as nn

BASE = os.environ.get("LFM3_BASE", "base-model")
DATA = os.environ.get("LFM3_DATA", "data")


def load(path=None, dtype=torch.bfloat16):
    path = path or BASE
    from transformers import AutoModelForCausalLM, AutoTokenizer
    tok = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
    m = AutoModelForCausalLM.from_pretrained(
        path, trust_remote_code=True, dtype=dtype, attn_implementation="sdpa", device_map={"": 0})
    return m, tok


def _damp(layer, alpha):
    if alpha == 1.0:
        return
    with torch.no_grad():
        layer.post_operator_norm.weight.mul_(alpha)
        layer.post_ffn_norm.weight.mul_(alpha)


def scale_q(m, beta):
    """Multiply every attention query projection by beta = global attention temperature."""
    with torch.no_grad():
        for lay in m.model.layers:
            if not hasattr(lay, "self_attn"):
                continue        # LFM3 alternates: conv layers have no attention
            q = lay.self_attn.q_proj
            q.weight.mul_(beta)
            if getattr(q, "bias", None) is not None:
                q.bias.mul_(beta)
    return m


def scale_all_post(m, gamma):
    """Scale every layer's residual branch output by gamma (global residual gain)."""
    with torch.no_grad():
        for lay in m.model.layers:
            lay.post_operator_norm.weight.mul_(gamma)
            lay.post_ffn_norm.weight.mul_(gamma)
    return m


def conv_loop(m, a, b, alpha=0.5):
    """Repeat ONLY the shortconv sublayer inside [a,b], damped alpha per pass.
    Attention layers in the window are left untouched (LFM3 alternates conv/attn)."""
    n = 0
    for lay in m.model.layers[a:b + 1]:
        if hasattr(lay, "self_attn"):
            continue

        def make(layer, al=alpha):
            def fwd(hidden_states, position_embeddings=None, attention_mask=None,
                    position_ids=None, past_key_values=None, seq_idx=None, **kw):
                res = hidden_states
                h = layer.conv(layer.operator_norm(res), past_key_values=past_key_values,
                               attention_mask=attention_mask, seq_idx=seq_idx)
                h = layer.post_operator_norm(h)
                mid = res + al * h
                h2 = layer.conv(layer.operator_norm(mid), past_key_values=past_key_values,
                                attention_mask=attention_mask, seq_idx=seq_idx)
                h2 = layer.post_operator_norm(h2)
                out = mid + al * h2
                f = layer.feed_forward(layer.ffn_norm(out))
                f = layer.post_ffn_norm(f)
                return out + f
            return fwd

        lay.forward = make(lay)
        n += 1
    print(f"conv_loop: patched {n} conv sublayers in [{a},{b}] alpha={alpha}", flush=True)
    return m


def build_multi(ops):
    """Several loop windows in one model. ops: list of (a, b, reps, alpha), applied from
    the highest start index down so that earlier indices stay valid while later ones shift.
    Disjoint windows compose; overlapping ones are not checked."""
    m, tok = load()
    inner = m.model
    n0 = len(inner.layers)
    for a, b, reps, alpha in sorted(ops, key=lambda o: -o[0]):
        types = list(inner.config.layer_types)
        chunk = list(inner.layers[a:b + 1])
        for lay in chunk:
            _damp(lay, alpha)
        new = []
        for r in range(reps - 1):
            for j, lay in enumerate(chunk):
                new.append(copy.deepcopy(lay))
        inner.layers = nn.ModuleList(list(inner.layers[:b + 1]) + new + list(inner.layers[b + 1:]))
        inner.config.layer_types = (types[:b + 1]
                                    + [types[a + j] for _ in range(reps - 1) for j in range(len(chunk))]
                                    + types[b + 1:])
        assert len(inner.layers) == len(inner.config.layer_types)
    inner.config.num_hidden_layers = len(inner.layers)
    m.config.num_hidden_layers = inner.config.num_hidden_layers
    m.config.layer_types = inner.config.layer_types
    for pos, lay in enumerate(inner.layers):
        if hasattr(lay, "self_attn"):
            lay.self_attn.layer_idx = pos
        if hasattr(lay, "conv") and hasattr(lay.conv, "layer_idx"):
            lay.conv.layer_idx = pos
    m.eval()
    return m, tok


def build(window=(10, 13), reps=2, alpha=None, gains=None):
    """Return a plain HF model: window [a,b] executed `reps` times, each application
    damped by `alpha` (default 1/reps = K equal sub-steps of the same total update).
    `gains` overrides per-application damping, e.g. [0.5, 1.0] = RK2 midpoint."""
    if gains is not None:
        reps = len(gains)
    alpha = (1.0 / reps) if alpha is None else float(alpha)
    if gains is None:
        gains = [alpha] * reps
    assert len(gains) == reps
    m, tok = load()
    inner = m.model
    a, b = window
    chunk = list(inner.layers[a:b + 1])
    types = list(inner.config.layer_types)
    n0 = len(inner.layers)

    # damp every application, including the original window
    for lay in chunk:
        _damp(lay, gains[0])

    new, new_types = [], []
    for r in range(reps - 1):
        for j, lay in enumerate(chunk):
            c = copy.deepcopy(lay)
            if gains[r + 1] != gains[0]:
                # copy carries the first pass's scale; rescale to this pass's gain
                with torch.no_grad():
                    c.post_operator_norm.weight.mul_(gains[r + 1] / gains[0])
                    c.post_ffn_norm.weight.mul_(gains[r + 1] / gains[0])
            new.append(c)
            new_types.append(types[a + j])

    inner.layers = nn.ModuleList(list(inner.layers[:b + 1]) + new + list(inner.layers[b + 1:]))
    inner.config.layer_types = types[:b + 1] + new_types + types[b + 1:]
    inner.config.num_hidden_layers = n0 + len(new)
    m.config.num_hidden_layers = inner.config.num_hidden_layers
    m.config.layer_types = inner.config.layer_types
    # layer_idx must equal the layer's POSITION: the KV cache and the per-layer
    # metadata arrays are indexed by it, so a mid-stack insertion shifts every
    # later layer and every copy must take its own slot.
    for pos, lay in enumerate(inner.layers):
        if hasattr(lay, "self_attn"):
            lay.self_attn.layer_idx = pos
        if hasattr(lay, "conv") and hasattr(lay.conv, "layer_idx"):
            lay.conv.layer_idx = pos
    m.eval()
    return m, tok


# ---------------------------------------------------------------- reference wrapper
class RefLoop:
    """Independent implementation of the same math without duplicating weights:
    scale the two sandwich-norm outputs, then run the window `reps` times."""

    def __init__(self, model, window, reps, alpha):
        self.model, self.reps, self.alpha = model, reps, alpha
        self.a, self.b = window
        self.handles = []
        for i in range(self.a, self.b + 1):
            lay = model.model.layers[i]
            for mod in (lay.post_operator_norm, lay.post_ffn_norm):
                self.handles.append(mod.register_forward_hook(self._hook))

    def _hook(self, module, args, out):
        return out * self.alpha

    def run(self, model_layer_loop):
        return model_layer_loop(self.reps)

    def remove(self):
        for h in self.handles:
            h.remove()


@torch.no_grad()
def ref_forward(model, ids, window, reps, alpha):
    """Compose pre-loop layers, then the window x reps, then post-loop layers."""
    inner = model.model
    a, b = window
    ref = RefLoop(model, window, reps, alpha)
    h = inner.embed_tokens(ids)
    pos = torch.arange(ids.shape[1], device=ids.device).unsqueeze(0)
    pe = {t: inner.rotary_emb(h, position_ids=pos, layer_type=t) for t in inner.rotary_emb.layer_types}
    modeling = sys.modules[inner.__class__.__module__]
    cm = modeling.create_masks_by_layer_type(config=inner.config, inputs_embeds=h, attention_mask=None,
                                             past_key_values=None, position_ids=pos)
    def run(i):
        nonlocal h
        lt = inner.config.layer_types[i]
        h = inner.layers[i](h, attention_mask=cm[lt], position_embeddings=pe.get(lt),
                            position_ids=pos, past_key_values=None, seq_idx=None)
    for i in range(a):
        run(i)
    for _ in range(reps):
        for i in range(a, b + 1):
            run(i)
    for i in range(b + 1, len(inner.layers)):
        run(i)
    ref.remove()
    return inner.embedding_norm(h)


# ---------------------------------------------------------------- data / metrics
class TextDS(torch.utils.data.Dataset):
    def __init__(self, path, tok, ctx, max_windows=None):
        ids = []
        with open(path, "r", encoding="utf-8", errors="ignore") as f:
            buf = []
            for line in f:
                line = line.strip()
                if not line:
                    continue
                buf.append(line)
                if len(buf) >= 64:
                    ids.extend(tok(" ".join(buf), add_special_tokens=False)["input_ids"])
                    buf = []
                    if max_windows and len(ids) >= max_windows * ctx:
                        break
            if buf:
                ids.extend(tok(" ".join(buf), add_special_tokens=False)["input_ids"])
        self.windows = [ids[i:i + ctx] for i in range(0, len(ids) - ctx - 1, ctx)]
        if max_windows:
            self.windows = self.windows[:max_windows]

    def __len__(self):
        return len(self.windows)

    def __getitem__(self, i):
        w = self.windows[i]
        return {"input_ids": torch.tensor(w), "labels": torch.tensor(w)}


class StreamDS(torch.utils.data.Dataset):
    """Whole-file tokenisation (single stream), the way llama-perplexity reads it.
    TextDS's 64-line joining inflates PPL and is not comparable across models."""

    def __init__(self, path, tok, ctx, n=None, max_windows=None):
        n = n or max_windows
        ids = tok(open(path, "r", encoding="utf-8", errors="ignore").read(), add_special_tokens=False)["input_ids"]
        self.windows = [ids[i:i + ctx] for i in range(0, len(ids) - ctx - 1, ctx)][:n]

    def __len__(self):
        return len(self.windows)

    def __getitem__(self, i):
        w = self.windows[i]
        return {"input_ids": torch.tensor(w), "labels": torch.tensor(w)}


@torch.no_grad()
def ppl(model, ds, n_batches=16, bs=2):
    model.eval()
    dl = torch.utils.data.DataLoader(ds, batch_size=bs, shuffle=False)
    tot, cnt = 0.0, 0
    for i, b in enumerate(dl):
        if i >= n_batches:
            break
        ids = b["input_ids"].cuda()
        with torch.autocast("cuda", dtype=torch.bfloat16):
            out = model(input_ids=ids, labels=ids)
        tot += out.loss.float().item() * ids.numel()
        cnt += ids.numel()
    return math.exp(tot / cnt)


def gsm8k_rows(n=100):
    rows, txt = [], open(os.path.join(DATA, "gsm8k-test.txt")).read()
    for block in txt.split("\n\n"):
        mm = re.search(r"Question: (.*?)\nAnswer: (.*)", block, re.S)
        if not mm:
            continue
        gold = re.search(r"####\s*([\-\d\.,]+)", mm.group(2))
        if gold:
            rows.append((mm.group(1).strip(), gold.group(1).replace(",", "").strip()))
        if len(rows) >= n:
            break
    return rows


def last_number(s):
    nums = re.findall(r"-?\d[\d,]*\.?\d*", s.replace("$", ""))
    return nums[-1].replace(",", "").rstrip(".") if nums else None


@torch.no_grad()
def run_gsm8k(model, tok, rows, max_new=512):
    ok = 0
    for q, gold in rows:
        msgs = [{"role": "user", "content": q + "\nAnswer with the final number on its own line."}]
        text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
        ids = tok(text, return_tensors="pt").input_ids.cuda()
        out = model.generate(ids, max_new_tokens=max_new, do_sample=False, temperature=None,
                            top_p=None, top_k=None, pad_token_id=tok.pad_token_id or tok.eos_token_id)
        pred = last_number(tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True))
        ok += pred is not None and abs(float(pred) - float(gold)) < 0.01
    return ok / len(rows)


def arc_rows(config="ARC-Easy", n=500, shots=0):
    from datasets import load_dataset
    d = load_dataset("allenai/ai2_arc", config, split="test")
    pre = ""
    if shots:
        tr = load_dataset("allenai/ai2_arc", config, split="train")
        for r in tr.select(range(min(shots, len(tr)))):
            ans = r["choices"]["text"][r["choices"]["label"].index(r["answerKey"])]
            pre += f"Question: {r['question']}\nAnswer: {ans}\n\n"
    rows = []
    for r in d:
        lab, txt = r["choices"]["label"], r["choices"]["text"]
        if r["answerKey"] not in lab:
            continue
        rows.append((r["question"], lab, txt, lab.index(r["answerKey"])))
        if len(rows) >= n:
            break
    return rows, pre


@torch.no_grad()
def run_arc(model, tok, rows, pre="", score="mean", dump=False):
    """ARC multiple-choice, base-LM style: score each choice *text* as the continuation
    of "Question: ...\\nAnswer:" and take the argmax of the (optionally length-normalised)
    log-probability."""
    per, alls = [], []
    for q, lab, txt, gold in rows:
        pid = tok(pre + "Question: " + q + "\nAnswer:", return_tensors="pt").input_ids.cuda()
        scores = []
        for t in txt:
            cid = tok(" " + t, add_special_tokens=False, return_tensors="pt").input_ids.cuda()
            out = model(input_ids=torch.cat([pid, cid], dim=1), use_cache=False)
            lp = torch.log_softmax(out.logits[0, pid.shape[1] - 1:pid.shape[1] - 1 + cid.shape[1]].float(), -1)
            s = lp[range(cid.shape[1]), cid[0]]
            scores.append(s.mean().item() if score == "mean" else s.sum().item())
            del out
        per.append(int(max(range(len(txt)), key=lambda i: scores[i]) == gold))
        alls.append(scores)
    return (per, alls) if dump else per


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["identity", "ppl", "grid", "gsm8k", "bake", "arc", "sweep"])
    ap.add_argument("--window", default="10,13")
    ap.add_argument("--base", action="store_true", help="evaluate the unmodified checkpoint")
    ap.add_argument("--reps", type=int, default=2)
    ap.add_argument("--alpha", type=float, default=None)
    ap.add_argument("--n-pll", type=int, default=16)
    ap.add_argument("--gsm", type=int, default=80)
    ap.add_argument("--arc-config", default="ARC-Easy")
    ap.add_argument("--arc-n", type=int, default=400)
    ap.add_argument("--shots", type=int, default=0)
    ap.add_argument("--stream", action="store_true")
    ap.add_argument("--multi", default=None, help="a,b,reps,alpha;... several loop windows")
    ap.add_argument("--gains", default=None, help="comma list, per-pass damping e.g. 0.5,1.0")
    ap.add_argument("--qscale", type=float, default=1.0, help="global query scale = attention temperature")
    ap.add_argument("--postscale", type=float, default=1.0, help="global residual branch gain")
    ap.add_argument("--convloop", default=None, help="a,b,alpha: run only the shortconv sublayer twice inside [a,b]")
    ap.add_argument("--arc-score", default="mean", choices=["mean", "sum"])
    ap.add_argument("--out", default="out-tfl")
    ap.add_argument("--data-dir", default=os.environ.get("LFM3_DATA", "data"),
                    help="dir with wikitext-test.txt / gsm8k-test.txt / gsm8k-train-chat.txt")
    ap.add_argument("--base-model", default=os.environ.get("LFM3_BASE", "base-model"),
                    help="HF dir of the unmodified checkpoint (default $LFM3_BASE)")
    args = ap.parse_args()
    global BASE, DATA
    BASE = args.base_model
    DATA = args.data_dir
    a, b = [int(x) for x in args.window.split(",")]
    window = (a, b)

    if args.cmd == "identity":
        base, tok = load()
        ids = torch.randint(1000, 60000, (1, 128), device="cuda")
        with torch.no_grad():
            ref = base(input_ids=ids).logits.float()
        # same weights, no extra copy -> must be exact
        dup, _ = build(window, reps=1, alpha=1.0)
        with torch.no_grad():
            got = dup(input_ids=ids).logits.float()
        d = (ref - got).abs().max().item()
        print(f"build(window={window}, reps=1, alpha=1) vs base: max|dlogit| = {d:.3e}")
        del dup
        torch.cuda.empty_cache()
        # reference wrapper: run the same window reps times with alpha damping
        for alpha in (1.0, 0.5, 1 / 3):
            h_ref = ref_forward(base, ids, window, args.reps, alpha).float()
            damp, _ = build(window, reps=args.reps, alpha=alpha)
            with torch.no_grad():
                h_dup = damp.model(input_ids=ids).last_hidden_state.float()
            dd = (h_ref - h_dup).abs().max().item()
            print(f"alpha={alpha:.3f}: wrapper vs static dup max|d| = {dd:.3e}")
            del damp
            torch.cuda.empty_cache()
        return

    if args.cmd in ("ppl", "bake", "arc", "gsm8k"):
        if args.base:
            m, tok = load()
            m.eval()
            tag = "base"
        elif args.multi:
            ops = []
            for spec in args.multi.split(";"):
                aa, bb, rr, al = [float(x) for x in spec.split(",")]
                ops.append((int(aa), int(bb), int(rr), al))
            m, tok = build_multi(ops)
            tag = "multi:" + "+".join(f"{o[0]}-{o[1]}x{o[2]}@{o[3]:.2f}" for o in ops)
        else:
            gains = [float(x) for x in args.gains.split(",")] if args.gains else None
            m, tok = build(window, reps=args.reps, alpha=args.alpha, gains=gains)
            tag = (f"{args.window} gains={gains}" if gains
                   else f"{args.window} x{args.reps} alpha={1/args.reps if args.alpha is None else args.alpha}")
        if args.qscale != 1.0:
            scale_q(m, args.qscale)
            tag += f" q*{args.qscale}"
        if args.postscale != 1.0:
            scale_all_post(m, args.postscale)
            tag += f" post*{args.postscale}"
        if args.convloop:
            ca, cb, cal = [float(x) for x in args.convloop.split(",")]
            conv_loop(m, int(ca), int(cb), cal)
            tag += f" convloop{args.convloop}"


    if args.cmd == "ppl":
        DS = StreamDS if args.stream else TextDS
        wt = DS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2)
        ood = StreamDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, args.n_pll * 2) if args.stream else TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2)
        print(json.dumps({"tag": tag, "wikitext": round(ppl(m, wt, args.n_pll), 4),
                          "gsm8k_text": round(ppl(m, ood, args.n_pll), 4)}))
        return

    if args.cmd == "grid":
        cfg = [
            ("base", None, 1, 1.0),
            ("naive K2 @[10-13]", (10, 13), 2, 1.0),
            ("damped K2 @[10-13]", (10, 13), 2, 0.5),
            ("damped K3 @[10-13]", (10, 13), 3, 1 / 3),
            ("step0.75 @[10-13]", (10, 13), 1, 0.75),
            ("damped K2 @[8-11]", (8, 11), 2, 0.5),
            ("damped K2 @[12-15]", (12, 15), 2, 0.5),
            ("damped K2 @[11-12]", (11, 12), 2, 0.5),
            ("damped K2 @[9-12]", (9, 12), 2, 0.5),
        ]
        tok = None
        rows = []
        for tag, w, reps, alpha in cfg:
            t0 = time.time()
            if w is None:
                m, tok = load()
                m.eval()
            else:
                m, tok = build(w, reps=reps, alpha=alpha)
            wt = TextDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2)
            ood = TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2)
            r = {"tag": tag, "layers": m.config.num_hidden_layers,
                 "wikitext": round(ppl(m, wt, args.n_pll), 4),
                 "gsm8k_text": round(ppl(m, ood, args.n_pll), 4), "s": round(time.time() - t0, 1)}
            print(json.dumps(r), flush=True)
            rows.append(r)
            del m
            torch.cuda.empty_cache()
        json.dump(rows, open(os.path.join(args.out, "grid.json"), "w"), indent=1)
        return

    if args.cmd == "sweep":
        m, tok = load()
        m.eval()
        wt = TextDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=args.n_pll * 2)
        ood = TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=args.n_pll * 2)
        names = []
        for i in range(a, b + 1):
            names += [m.model.layers[i].post_operator_norm.weight, m.model.layers[i].post_ffn_norm.weight]
        orig = [t.detach().clone() for t in names]
        for alpha in (1.0, 1.25, 1.5, 0.9, 0.85, 0.75, 0.7, 0.6, 0.5, 0.4, 0.3):
            with torch.no_grad():
                for t, o in zip(names, orig):
                    t.copy_(o).mul_(alpha)
            print(json.dumps({"alpha": alpha, "wikitext": round(ppl(m, wt, args.n_pll), 4),
                              "gsm8k_text": round(ppl(m, ood, args.n_pll), 4)}), flush=True)
        with torch.no_grad():
            for t, o in zip(names, orig):
                t.copy_(o)
        return

    if args.cmd == "bake":
        outdir = os.path.join(args.out, f"baked-{a}_{b}-x{args.reps}@{ (1/args.reps if args.alpha is None else args.alpha):.3f}".replace("/", "") )
        m.save_pretrained(outdir)
        tok.save_pretrained(outdir)
        for f in ("modeling_lfm3.py", "configuration_lfm3.py", "lfm3_conv.py", "chat_template.jinja"):
            src = os.path.join(BASE, f)
            if os.path.exists(src):
                import shutil
                shutil.copy2(src, os.path.join(outdir, f))
        print("baked ->", outdir, "layers:", m.config.num_hidden_layers)
        return

    if args.cmd == "arc":
        rows, pre = arc_rows(args.arc_config, args.arc_n, args.shots)
        t0 = time.time()
        per, lps = run_arc(m, tok, rows, pre, args.arc_score, dump=True)
        acc = sum(per) / len(per)
        print(f"{tag}: {args.arc_config} {args.shots}-shot acc_norm {acc*100:.1f}% over {len(per)} ({time.time()-t0:.0f}s)", flush=True)
        key = f"arc-{args.arc_config}-{args.arc_n}-{args.shots}shot-{args.arc_score}-{tag}".replace(" ", "").replace(",", "_").replace("=", "")
        json.dump({"per": per, "lp": lps, "gold": [r[3] for r in rows], "n_opt": [len(r[2]) for r in rows]},
                  open(os.path.join(args.out, key + ".json"), "w"))
        return

    if args.cmd == "gsm8k":
        rows = gsm8k_rows(args.gsm)
        t0 = time.time()
        acc = run_gsm8k(m, tok, rows)
        print(f"{tag}: GSM8K {acc*100:.1f}% over {len(rows)} ({time.time()-t0:.0f}s)", flush=True)
        return


if __name__ == "__main__":
    main()