File size: 39,738 Bytes
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
"""Tests for progressive quantization layers, neuron block reallocation, router, and verification loop."""

import unittest

import torch
import torch.nn as nn
import torch.nn.functional as F

from progressive_quant import (
    PrecisionRouter,
    ProgressiveConv2d,
    ProgressiveLinear,
    RouterConfig,
    quantize_per_element,
)


class TinyMLP(nn.Module):
    def __init__(self, use_quantization: bool, granularity: str = "element") -> None:
        super().__init__()
        self.fc1 = ProgressiveLinear(4, 16, use_quantization=use_quantization, granularity=granularity)
        self.fc2 = ProgressiveLinear(16, 2, use_quantization=use_quantization, granularity=granularity)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.fc2(F.relu(self.fc1(x)))


class ProgressiveQuantTests(unittest.TestCase):
    def test_bit_levels_and_fp32_equivalence(self) -> None:
        w = torch.tensor([[0.05, -0.05, 0.4, -0.8], [0.9, -0.1, 0.02, -0.3]])
        q1 = quantize_per_element(w, torch.ones_like(w, dtype=torch.int8))
        self.assertEqual(torch.unique(q1[0]).numel(), 2)

        q2 = quantize_per_element(w, torch.full_like(w, 2, dtype=torch.int8))
        q4 = quantize_per_element(w, torch.full_like(w, 4, dtype=torch.int8))
        q8 = quantize_per_element(w, torch.full_like(w, 8, dtype=torch.int8))
        q32 = quantize_per_element(w, torch.full_like(w, 32, dtype=torch.int8))

        self.assertLess((w - q8).abs().max().item(), (w - q4).abs().max().item())
        self.assertLess((w - q4).abs().max().item(), (w - q2).abs().max().item())
        self.assertTrue(torch.equal(w, q32))

    def test_classical_mode_matches_standard_linear(self) -> None:
        torch.manual_seed(0)
        x = torch.randn(5, 4)
        prog = ProgressiveLinear(4, 3, use_quantization=False)
        ref = nn.Linear(4, 3)
        ref.load_state_dict({"weight": prog.weight.detach().clone(), "bias": prog.bias.detach().clone()})
        self.assertTrue(torch.allclose(prog(x), ref(x)))

    def test_conv2d_progressive_supported(self) -> None:
        conv = ProgressiveConv2d(3, 4, kernel_size=3, padding=1, use_quantization=True)
        x = torch.randn(2, 3, 8, 8)
        out = conv(x)
        self.assertEqual(out.shape, (2, 4, 8, 8))
        self.assertTrue((conv.bit_widths == 1).all())

    def test_block_execution_matches_elementwise_for_neuron_granularity(self) -> None:
        torch.manual_seed(7)
        x = torch.randn(6, 5)
        layer_blk = ProgressiveLinear(5, 8, use_quantization=True, granularity="neuron", use_block_execution=True)
        layer_ref = ProgressiveLinear(5, 8, use_quantization=True, granularity="neuron", use_block_execution=False)
        layer_ref.load_state_dict(layer_blk.state_dict(), strict=False)
        with torch.no_grad():
            bw = torch.tensor([1, 4, 1, 32, 2, 8, 2, 16], dtype=torch.int8)
            layer_blk.bit_widths.copy_(bw)
            layer_ref.bit_widths.copy_(bw)
        num_blocks = layer_blk.reallocate_blocks()
        self.assertEqual(num_blocks, 6)
        self.assertTrue(torch.allclose(layer_blk(x), layer_ref(x), atol=1e-6))

    def test_router_promotes_only_oscillating_near_zero_weights(self) -> None:
        layer = ProgressiveLinear(3, 1, bias=False, use_quantization=True)
        with torch.no_grad():
            layer.weight.copy_(torch.tensor([[0.02, 0.02, 0.50]]))

        router = PrecisionRouter(RouterConfig(oscillation_band=0.1, min_delta=1e-4))
        router.observe_and_promote(layer)

        with torch.no_grad():
            layer.weight.copy_(torch.tensor([[0.06, 0.05, 0.55]]))
        s1, _ = router.observe_and_promote(layer)
        self.assertEqual(s1.num_promoted, 0)

        with torch.no_grad():
            layer.weight.copy_(torch.tensor([[-0.02, 0.08, 0.48]]))
        s2, _ = router.observe_and_promote(layer)

        self.assertEqual(s2.num_promoted, 1)
        self.assertEqual(layer.bit_widths.tolist(), [[2, 1, 1]])

    def test_neuron_router_reallocates_blocks_and_verifies_same_task(self) -> None:
        torch.manual_seed(42)
        model = TinyMLP(use_quantization=True, granularity="neuron")
        with torch.no_grad():
            model.fc1.weight.uniform_(-0.08, 0.08)
            model.fc2.weight.uniform_(-0.08, 0.08)

        router = PrecisionRouter(
            RouterConfig(
                oscillation_band=0.1,
                min_delta=1e-5,
                neuron_osc_threshold=0.10,
                max_verify_iters=3,
                target_metric=1.0,
            )
        )
        optimizer = torch.optim.SGD(model.parameters(), lr=0.25)

        x = torch.tensor(
            [
                [0.05, 0.05, 0.0, 0.0],
                [-0.05, -0.05, 0.0, 0.0],
                [0.8, 0.8, 0.0, 0.0],
                [-0.8, -0.8, 0.0, 0.0],
            ]
        )
        y = torch.tensor([1, 0, 1, 0])

        def batch_step():
            logits = model(x)
            loss = F.cross_entropy(logits, y)
            acc = float((logits.argmax(dim=-1) == y).float().mean().item())
            return loss, acc

        reports = [router.step_with_verification(model, optimizer, batch_step) for _ in range(12)]
        self.assertTrue(any(r.verify_iters > 0 for r in reports))
        self.assertTrue(any(r.total_reallocations > 0 for r in reports))
        self.assertGreater(reports[-1].avg_bits, 1.0)
        self.assertLess(reports[-1].avg_bits, 32.0)

    def test_rollback_penalty_reverts_unjustified_promotion(self) -> None:
        torch.manual_seed(0)
        layer = ProgressiveLinear(4, 2, bias=False, use_quantization=True, granularity="neuron")
        with torch.no_grad():
            layer.weight.copy_(torch.tensor([[0.05, -0.05, 0.04, -0.04], [0.03, 0.03, -0.03, -0.03]]))

        # High bit_cost_weight guarantees promotion is deemed unjustified on a tiny batch.
        router = PrecisionRouter(
            RouterConfig(
                oscillation_band=0.1,
                min_delta=1e-6,
                oscillation_patience=1.0,
                neuron_osc_threshold=0.25,
                enable_rollback_penalty=True,
                rollback_min_loss_gain=10.0,
                rollback_cooldown_steps=3,
                rollback_patience_penalty=0.5,
            )
        )
        optimizer = torch.optim.SGD(layer.parameters(), lr=0.1)
        x = torch.ones(2, 4)

        def constant_step():
            out = layer(x)
            return (out ** 2).mean(), 1.0

        # Step 0 baseline, force reversal on step 1, verify rollback returns bit_widths to 1.
        router.step_with_verification(layer, optimizer, constant_step)
        with torch.no_grad():
            layer.weight.neg_()
        report = router.step_with_verification(layer, optimizer, constant_step)
        self.assertGreater(report.total_rollbacks, 0)
        self.assertTrue((layer.bit_widths == 1).all())

    def test_v4_attention_and_head_protection_bits(self) -> None:
        from model import BilingualNLIConfig, BilingualNLITransformer

        cfg = BilingualNLIConfig(
            vocab_size=100,
            max_len=16,
            d_model=16,
            n_heads=2,
            n_layers=1,
            d_ff=32,
            protect_attention_and_head=True,
            attn_init_bits=2,
            head_init_bits=4,
        )
        m = BilingualNLITransformer(cfg, use_quantization=True)
        self.assertTrue((m.blocks[0].q_proj.bit_widths == 2).all())
        self.assertTrue((m.blocks[0].ffn_in.bit_widths == 1).all())
        self.assertTrue((m.head_out.bit_widths == 4).all())

        from train_experiment import load_shared_init_state

        ref_cfg = BilingualNLIConfig(
            vocab_size=100,
            max_len=16,
            d_model=16,
            n_heads=2,
            n_layers=1,
            d_ff=32,
            protect_attention_and_head=False,
        )
        ref = BilingualNLITransformer(ref_cfg, use_quantization=False)
        init_state = {k: v.detach().clone() for k, v in ref.state_dict().items()}
        load_shared_init_state(m, init_state)
        self.assertTrue(torch.equal(m.blocks[0].q_proj.weight, ref.blocks[0].q_proj.weight))
        self.assertTrue((m.blocks[0].q_proj.bit_widths == 2).all())
        self.assertTrue((m.blocks[0].ffn_in.bit_widths == 1).all())
        self.assertTrue((m.head_out.bit_widths == 4).all())

    def test_v5_strict_loss_gain_rollback_ignores_metric_blip(self) -> None:
        layer = ProgressiveLinear(4, 2, bias=False, use_quantization=True, granularity="neuron")
        with torch.no_grad():
            layer.weight.copy_(torch.tensor([[0.05, -0.05, 0.04, -0.04], [0.03, 0.03, -0.03, -0.03]]))

        router = PrecisionRouter(
            RouterConfig(
                oscillation_band=0.1,
                min_delta=1e-6,
                oscillation_patience=1.0,
                neuron_osc_threshold=0.25,
                enable_rollback_penalty=True,
                rollback_min_loss_gain=10.0,
                strict_loss_gain_rollback=True,
            )
        )
        optimizer = torch.optim.SGD(layer.parameters(), lr=0.1)
        x = torch.ones(2, 4)

        def metric_blip_step():
            out = layer(x)
            # Even with higher accuracy on promoted bit-width, huge min_loss_gain must force rollback.
            metric = 1.0 if (layer.bit_widths > 1).any() else 0.0
            return (out ** 2).mean(), metric

        router.step_with_verification(layer, optimizer, metric_blip_step)
        with torch.no_grad():
            layer.weight.neg_()
        report = router.step_with_verification(layer, optimizer, metric_blip_step)
        self.assertGreater(report.total_rollbacks, 0)
        self.assertTrue((layer.bit_widths == 1).all())

    def test_v5_enforce_rollback_in_verify_blocks_secondary_cascade(self) -> None:
        def run_case(enforce_verify: bool):
            torch.manual_seed(0)
            layer = ProgressiveLinear(4, 1, bias=False, use_quantization=True, granularity="neuron")
            with torch.no_grad():
                layer.weight.copy_(torch.tensor([[0.02, -0.02, 0.02, -0.02]]))

            router = PrecisionRouter(
                RouterConfig(
                    oscillation_band=0.1,
                    min_delta=1e-6,
                    oscillation_patience=1.0,
                    neuron_osc_threshold=0.5,
                    max_verify_iters=2,
                    enable_rollback_penalty=True,
                    enforce_rollback_in_verify=enforce_verify,
                    strict_loss_gain_rollback=True,
                    rollback_min_loss_gain=0.0,
                    rollback_bit_cost_weight=0.01,
                )
            )
            optimizer = torch.optim.SGD(layer.parameters(), lr=0.07)
            x = torch.tensor([[2.0, -2.0, 2.0, -2.0]])

            def cascade_step():
                out = layer(x)
                max_b = int(layer.bit_widths.max().item())
                # First upgrade (1->2 bits) lowers loss sharply; verify upgrades (>2 bits) hurt loss.
                penalty = 1.0 if max_b == 1 else (0.0 if max_b == 2 else 5.0)
                return (out ** 2).mean() + penalty, 0.0

            router.step_with_verification(layer, optimizer, cascade_step)
            rep = router.step_with_verification(layer, optimizer, cascade_step)
            return int(layer.bit_widths.max().item()), rep

        max_b_unchecked, _ = run_case(False)
        max_b_checked, rep_checked = run_case(True)
        self.assertGreater(max_b_unchecked, 2)
        self.assertEqual(max_b_checked, 2)
        self.assertGreater(rep_checked.total_rollbacks, 0)

    def test_detailed_validation_metrics_and_disjoint_guard(self) -> None:
        from torch.utils.data import DataLoader, TensorDataset
        from validate_fp32_vs_v5 import evaluate_detailed, prepare_disjoint_xnli_splits

        class ToyClassifier(nn.Module):
            def __init__(self) -> None:
                super().__init__()
                self.logits = torch.tensor(
                    [
                        [10.0, 0.0, 0.0],
                        [0.0, 10.0, 0.0],
                        [0.0, 0.0, 10.0],
                        [10.0, 0.0, 0.0],
                    ]
                )

            def forward(self, input_ids, token_type_ids, attention_mask):
                return self.logits[: input_ids.size(0)]

        ds = TensorDataset(
            torch.zeros((4, 16), dtype=torch.long),
            torch.zeros((4, 16), dtype=torch.long),
            torch.ones((4, 16), dtype=torch.bool),
            torch.tensor([0, 1, 2, 1], dtype=torch.long),
            torch.tensor([0, 1, 0, 1], dtype=torch.long),
        )
        res = evaluate_detailed(ToyClassifier(), DataLoader(ds, batch_size=4), torch.device("cpu"))
        self.assertAlmostEqual(res["acc"], 0.75, places=5)
        self.assertGreater(res["ece_10bin"], 0.2)
        self.assertGreater(res["brier_score"], 0.4)
        self.assertGreater(res["macro_f1"], 0.6)
        with self.assertRaises(ValueError):
            prepare_disjoint_xnli_splits(train_offset=25_000, train_per_lang=30_000, stress_offset=50_000)

    def test_stratified_sample_rows_balance(self) -> None:
        from experiment_100m import stratified_sample_rows

        rows = (
            [{"premise": f"p0_{i}", "hypothesis": "h", "label": 0, "lang": "ru"} for i in range(40)]
            + [{"premise": f"p1_{i}", "hypothesis": "h", "label": 1, "lang": "ru"} for i in range(15)]
            + [{"premise": f"p2_{i}", "hypothesis": "h", "label": 2, "lang": "ru"} for i in range(15)]
        )
        picked = stratified_sample_rows(rows, 30, seed=42)
        self.assertEqual(len(picked), 30)
        counts = {lbl: sum(1 for r in picked if r["label"] == lbl) for lbl in (0, 1, 2)}
        self.assertEqual(counts, {0: 10, 1: 10, 2: 10})

    def test_resume_classical_and_v5_parity(self) -> None:
        import tempfile
        from pathlib import Path
        from torch.utils.data import DataLoader, TensorDataset
        from model import BilingualNLIConfig, BilingualNLITransformer
        from train_experiment import run_adaptive_v5, run_classical, set_seed

        set_seed(7)
        cfg = BilingualNLIConfig(
            vocab_size=12, max_len=8, d_model=16, n_heads=2, n_layers=1, d_ff=32,
            protect_attention_and_head=True, attn_init_bits=2, head_init_bits=4,
        )
        ref = BilingualNLITransformer(cfg, use_quantization=False)
        init_state = {k: v.detach().clone() for k, v in ref.state_dict().items()}
        ds = TensorDataset(
            torch.randint(1, 12, (8, 8)),
            torch.zeros((8, 8), dtype=torch.long),
            torch.ones((8, 8), dtype=torch.bool),
            torch.randint(0, 3, (8,)),
            torch.tensor([0, 1, 0, 1, 0, 1, 0, 1], dtype=torch.long),
        )
        loader = DataLoader(ds, batch_size=4, shuffle=False)
        r_cfg = RouterConfig(
            oscillation_band=0.1, min_delta=1e-6, oscillation_patience=1.0,
            warmup_steps=0, neuron_osc_threshold=0.1, max_verify_iters=1,
            enable_rollback_penalty=True, enforce_rollback_in_verify=True, strict_loss_gain_rollback=True,
        )
        dev = torch.device("cpu")

        class CrashOnNthValLoader:
            def __init__(self, base, fail_on_call: int) -> None:
                self.base = base
                self.fail_on_call = fail_on_call
                self.calls = 0

            def __iter__(self):
                self.calls += 1
                if self.calls == self.fail_on_call:
                    raise RuntimeError("simulated mid-run interruption")
                return iter(self.base)

        with tempfile.TemporaryDirectory() as tmp:
            p = Path(tmp)
            cls_full = run_classical(cfg, init_state, ds, loader, loader, loader, dev, 2, 4, 1e-3, 7)
            with self.assertRaises(RuntimeError):
                run_classical(
                    cfg, init_state, ds, CrashOnNthValLoader(loader, 2), loader, loader, dev, 2, 4, 1e-3, 7,
                    resume_file=p / "cls.pt",
                )
            cls_resumed = run_classical(cfg, init_state, ds, loader, loader, loader, dev, 2, 4, 1e-3, 7, resume_file=p / "cls.pt")
            self.assertAlmostEqual(cls_full["test"]["loss"], cls_resumed["test"]["loss"], places=5)

            v5_full = run_adaptive_v5(cfg, r_cfg, init_state, ds, loader, loader, loader, dev, 3, 2, 1, 4, 1e-3, 5e-4, 0.1, 0.01, 0.0, 0.99, 7)
            with self.assertRaises(RuntimeError):
                run_adaptive_v5(
                    cfg, r_cfg, init_state, ds, CrashOnNthValLoader(loader, 3), loader, loader, dev, 3, 2, 1, 4, 1e-3, 5e-4, 0.1, 0.01, 0.0, 0.99, 7,
                    resume_file=p / "v5.pt",
                )
            v5_resumed = run_adaptive_v5(cfg, r_cfg, init_state, ds, loader, loader, loader, dev, 3, 2, 1, 4, 1e-3, 5e-4, 0.1, 0.01, 0.0, 0.99, 7, resume_file=p / "v5.pt")
            self.assertEqual(v5_full["final_bit_counts"], v5_resumed["final_bit_counts"])
            self.assertAlmostEqual(v5_full["test"]["loss"], v5_resumed["test"]["loss"], places=5)

    def test_v5x_ste_clip_tier_scales_and_consolidate_down(self) -> None:
        torch.manual_seed(0)
        layer = ProgressiveLinear(
            6, 4, bias=True, initial_bits=1, use_quantization=True,
            granularity="neuron", use_block_execution=True, ste_clip=True, use_tier_scales=True,
        )
        with torch.no_grad():
            layer.bit_widths.copy_(torch.tensor([1, 2, 4, 8], dtype=torch.int8))
            layer.log_tier_scales[0] = 0.25
            layer.log_tier_scales[2] = -0.2
            layer.reallocate_blocks()
        x = torch.randn(3, 6)
        out_blk = layer(x)
        layer.use_block_execution = False
        out_elem = layer(x)
        self.assertTrue(torch.allclose(out_blk, out_elem, atol=1e-5))
        loss = (out_elem ** 2).sum()
        loss.backward()
        self.assertIsNotNone(layer.log_tier_scales.grad)
        self.assertGreater(float(layer.log_tier_scales.grad.abs().sum().item()), 0.0)

        # Verify consolidate_down safely steps down promoted units above min_bits when loss permits.
        router = PrecisionRouter(RouterConfig(track_salience=True))
        layer.use_block_execution = True
        layer.min_bits = 1
        st = router._get_or_init_state(layer)
        st["salience"].copy_(torch.tensor([10.0, 0.1, 0.2, 5.0]))
        rep = router.consolidate_down(layer, lambda: (0.5, 0.8), fractions=(0.5,), max_loss_increase=0.05)
        self.assertGreater(rep["num_pruned"], 0)
        self.assertLess(rep["bits_after"], rep["bits_before"])

        from model import BilingualNLIConfig, BilingualNLITransformer
        from adaptive_v5_series import composite_val_score, compute_tier_bit_breakdown, make_variant_specs

        specs = make_variant_specs(100)
        self.assertTrue({"v5_base", "v5_1", "v5_2", "v5_3", "v5_4", "v5_5", "v5_6", "v5_7", "v5_8"}.issubset(set(specs.keys())))
        self.assertGreater(
            composite_val_score({"acc": 0.48, "loss": 1.00}, 0.15),
            composite_val_score({"acc": 0.482, "loss": 1.15}, 0.15),
        )
        m_v53 = BilingualNLITransformer(
            BilingualNLIConfig(
                vocab_size=100, max_len=16, d_model=16, n_heads=2, n_layers=1, d_ff=32,
                protect_attention_and_head=True, use_tier_scales=True, ste_clip=True,
            ),
            use_quantization=True,
        )
        bd = compute_tier_bit_breakdown(m_v53)
        self.assertAlmostEqual(bd["attention"]["avg_bits"], 2.0)
        self.assertAlmostEqual(bd["ffn"]["avg_bits"], 1.0)

        from torch.utils.data import DataLoader, TensorDataset
        from adaptive_v5_series import run_adaptive_v5x

        torch.manual_seed(3)
        tiny_ds = TensorDataset(
            torch.randint(1, 50, (8, 8)),
            torch.zeros((8, 8), dtype=torch.long),
            torch.ones((8, 8), dtype=torch.bool),
            torch.randint(0, 3, (8,)),
            torch.tensor([0, 1, 0, 1, 0, 1, 0, 1], dtype=torch.long),
        )
        tiny_loader = DataLoader(tiny_ds, batch_size=4, shuffle=False)
        tiny_cfg = BilingualNLIConfig(
            vocab_size=50, max_len=8, d_model=16, n_heads=2, n_layers=1, d_ff=32,
            protect_attention_and_head=True, ste_clip=True, use_tier_scales=True,
        )
        ref_t = BilingualNLITransformer(tiny_cfg, use_quantization=False)
        tiny_init = {k: v.detach().clone() for k, v in ref_t.state_dict().items()}
        tiny_rcfg = RouterConfig(
            oscillation_band=0.1, min_delta=1e-6, oscillation_patience=1.0,
            warmup_steps=0, neuron_osc_threshold=0.1, max_verify_iters=1,
            enable_rollback_penalty=True, enforce_rollback_in_verify=True,
            strict_loss_gain_rollback=True, track_salience=True, use_salience_gating=True,
        )
        distill_res = run_adaptive_v5x(
            variant_name="test_v55",
            cfg=tiny_cfg,
            router_cfg=tiny_rcfg,
            init_state=tiny_init,
            train_ds=tiny_ds,
            val_loader=tiny_loader,
            seen_loader=tiny_loader,
            test_loader=tiny_loader,
            stress_loader=tiny_loader,
            device=torch.device("cpu"),
            epochs=2,
            min_stage1_epochs=1,
            max_stage1_epochs=1,
            batch_size=4,
            stage2_ema_distill_weight=0.30,
            seed=3,
        )
        self.assertEqual(len(distill_res["history"]), 2)

    def test_safetensors_adaptive_checkpoint_roundtrip(self) -> None:
        import tempfile
        from pathlib import Path
        from safetensors.torch import save_file
        from tokenizers import Tokenizer, models, pre_tokenizers
        from inference import load_nli_model, predict_nli
        from model import BilingualNLIConfig, BilingualNLITransformer

        tok = Tokenizer(models.WordLevel(vocab={"[PAD]": 0, "[UNK]": 1, "[CLS]": 2, "[SEP]": 3, "hi": 4}, unk_token="[UNK]"))
        tok.pre_tokenizer = pre_tokenizers.Whitespace()
        cfg = BilingualNLIConfig(
            vocab_size=5, max_len=16, d_model=16, n_heads=2, n_layers=1, d_ff=32,
            protect_attention_and_head=True, attn_init_bits=2, head_init_bits=4,
        )
        m = BilingualNLITransformer(cfg, use_quantization=True)
        with torch.no_grad():
            m.blocks[0].ffn_in.bit_widths[0] = 8
            m.blocks[0].ffn_in.reallocate_blocks()
        m.eval()

        with tempfile.TemporaryDirectory() as tmp:
            p = Path(tmp)
            tok_path = p / "tok.json"
            ckpt_path = p / "v5.safetensors"
            tok.save(str(tok_path))
            save_file({k: v.detach().contiguous() for k, v in m.state_dict().items()}, str(ckpt_path))
            loaded, ltok = load_nli_model(ckpt_path, tok_path, use_quantization=True, device="cpu", cfg=cfg)
            self.assertEqual(int(loaded.blocks[0].ffn_in.bit_widths[0].item()), 8)
            out = predict_nli(loaded, ltok, "hi", "hi", device="cpu", max_len=16)
            self.assertIn(out["label"], {"entailment", "neutral", "contradiction"})

    def test_v56_group_quant_and_modern_arch(self) -> None:
        from progressive_quant import ProgressiveLinear, effective_group_size
        from model import BilingualNLIConfig, BilingualNLITransformer, count_parameters
        from train_experiment import load_shared_init_state

        self.assertEqual(effective_group_size(320, 64), 64)
        self.assertEqual(effective_group_size(864, 64), 32)
        self.assertEqual(effective_group_size(3424, 64), 32)

        torch.manual_seed(11)
        layer = ProgressiveLinear(
            128, 6, granularity="neuron", use_block_execution=True, ste_clip=True, use_tier_scales=True, group_size=64
        )
        with torch.no_grad():
            layer.bit_widths.copy_(torch.tensor([1, 2, 1, 4, 2, 8], dtype=torch.int8))
            layer.log_tier_scales.copy_(torch.tensor([0.1, -0.1, 0.05, 0.0, 0.0, 0.0]))
            layer.reallocate_blocks()

        x = torch.randn(5, 128)
        out_blk = layer(x)
        layer.use_block_execution = False
        out_elem = layer(x)
        self.assertTrue(torch.allclose(out_blk, out_elem, atol=1e-5))
        (out_elem ** 2).sum().backward()
        self.assertGreater(float(layer.weight.grad.abs().sum().item()), 0.0)

        cfg_v56 = BilingualNLIConfig(
            vocab_size=64, max_len=16, d_model=32, n_heads=2, n_layers=1, d_ff=84,
            protect_attention_and_head=True, ste_clip=True, use_tier_scales=True,
            group_size=16, use_rms_norm=True, use_rope=True, use_qk_norm=True, use_swiglu=True,
        )
        m_v56 = BilingualNLITransformer(cfg_v56, use_quantization=True)
        # Ensure load_shared_init_state handles architecture differences cleanly without shape errors.
        m_base = BilingualNLITransformer(
            BilingualNLIConfig(vocab_size=64, max_len=16, d_model=32, n_heads=2, n_layers=1, d_ff=128),
            use_quantization=False,
        )
        load_shared_init_state(m_v56, {k: v.detach().clone() for k, v in m_base.state_dict().items()})
        ids = torch.randint(1, 64, (3, 12))
        segs = torch.zeros((3, 12), dtype=torch.long)
        mask = torch.ones((3, 12), dtype=torch.bool)
        logits = m_v56(ids, segs, mask)
        self.assertEqual(logits.shape, (3, 3))
        logits.sum().backward()
        self.assertLessEqual(count_parameters(m_v56)["total_params"], count_parameters(m_base)["total_params"])

    def test_v57_ternary_158_and_curriculum_verify(self) -> None:
        from progressive_quant import (
            BIT_LADDER_TERNARY,
            LOG2_3,
            PrecisionRouter,
            ProgressiveLinear,
            RouterConfig,
            effective_bits_for_code,
        )
        from model import BilingualNLIConfig, BilingualNLITransformer
        from adaptive_v5_series import compute_tier_bit_breakdown

        self.assertAlmostEqual(effective_bits_for_code(10, precision_tenths=True), 1.0)
        self.assertAlmostEqual(effective_bits_for_code(16, precision_tenths=True), LOG2_3)
        self.assertAlmostEqual(effective_bits_for_code(40, precision_tenths=True), 4.0)

        torch.manual_seed(21)
        layer = ProgressiveLinear(
            128,
            6,
            initial_bits=10,
            granularity="neuron",
            use_block_execution=True,
            ste_clip=True,
            use_tier_scales=True,
            group_size=64,
            precision_tenths=True,
        )
        self.assertEqual(layer.bit_widths.dtype, torch.int16)
        self.assertEqual(layer.log_tier_scales.numel(), len(BIT_LADDER_TERNARY))
        with torch.no_grad():
            layer.bit_widths.copy_(torch.tensor([10, 16, 20, 16, 40, 10], dtype=torch.int16))
            layer.log_tier_scales.copy_(torch.tensor([0.1, -0.1, 0.05, 0.0, 0.0, 0.0, 0.0]))
            layer.reallocate_blocks()

        # Verify exact ternary levels {-alpha, 0, +alpha} inside ternary slice.
        eff_w = layer.effective_weight()
        uniq_ternary_row = torch.unique(eff_w[1].abs()).numel()
        self.assertLessEqual(uniq_ternary_row, 3)

        x = torch.randn(4, 128)
        out_blk = layer(x)
        layer.use_block_execution = False
        out_elem = layer(x)
        self.assertTrue(torch.allclose(out_blk, out_elem, atol=1e-5))
        (out_elem ** 2).sum().backward()
        self.assertGreater(float(layer.log_tier_scales.grad.abs().sum().item()), 0.0)

        cfg_v57 = BilingualNLIConfig(
            vocab_size=64, max_len=16, d_model=32, n_heads=2, n_layers=1, d_ff=84,
            initial_bits=10, protect_attention_and_head=True, attn_init_bits=16, head_init_bits=40,
            ste_clip=True, use_tier_scales=True, group_size=16, precision_tenths=True,
            use_rms_norm=True, use_rope=True, use_qk_norm=True, use_swiglu=True,
        )
        m = BilingualNLITransformer(cfg_v57, use_quantization=True)
        router = PrecisionRouter(RouterConfig(bit_ladder=BIT_LADDER_TERNARY, precision_tenths=True))
        snap = router.snapshot_stats(m)
        bd = compute_tier_bit_breakdown(m)
        self.assertAlmostEqual(bd["attention"]["avg_bits"], LOG2_3, places=4)
        self.assertAlmostEqual(bd["attention"]["ternary_pct"], 100.0, places=2)
        self.assertAlmostEqual(bd["ffn"]["avg_bits"], 1.0, places=4)
        self.assertAlmostEqual(bd["head"]["avg_bits"], 1.6931, places=3)
        self.assertGreater(snap.avg_bits, 1.0)
        self.assertLess(snap.avg_bits, 2.0)

        from torch.utils.data import DataLoader, TensorDataset
        from adaptive_v5_series import run_adaptive_v5x

        tiny_ds = TensorDataset(
            torch.randint(1, 64, (8, 12)),
            torch.zeros((8, 12), dtype=torch.long),
            torch.ones((8, 12), dtype=torch.bool),
            torch.randint(0, 3, (8,)),
            torch.tensor([0, 1, 0, 1, 0, 1, 0, 1], dtype=torch.long),
        )
        tiny_loader = DataLoader(tiny_ds, batch_size=4, shuffle=False)
        tiny_init = {k: v.detach().clone() for k, v in m.state_dict().items()}
        tiny_rcfg = RouterConfig(
            bit_ladder=BIT_LADDER_TERNARY, precision_tenths=True,
            oscillation_band=0.1, min_delta=1e-6, oscillation_patience=1.0,
            warmup_steps=0, neuron_osc_threshold=0.1, max_verify_iters=1,
            enable_rollback_penalty=True, enforce_rollback_in_verify=True,
            strict_loss_gain_rollback=True, track_salience=True, use_salience_gating=True,
        )
        res57 = run_adaptive_v5x(
            variant_name="test_v57",
            cfg=cfg_v57,
            router_cfg=tiny_rcfg,
            init_state=tiny_init,
            train_ds=tiny_ds,
            val_loader=tiny_loader,
            seen_loader=tiny_loader,
            test_loader=tiny_loader,
            stress_loader=tiny_loader,
            device=torch.device("cpu"),
            epochs=2,
            min_stage1_epochs=1,
            max_stage1_epochs=1,
            batch_size=4,
            select_best_in_stage2=True,
            bit_cost_curriculum=(0.65, 1.45),
            verify_eval_batches=2,
            seed=7,
        )
        self.assertEqual(len(res57["history"]), 2)
        self.assertLess(res57["final_avg_bits"], 8.0)

        # Verify V5.8 max_bits cap + SAM + embedding regularization group.
        cfg_v58 = BilingualNLIConfig(
            vocab_size=64, max_len=16, d_model=32, n_heads=2, n_layers=1, d_ff=84,
            initial_bits=10, protect_attention_and_head=True, attn_init_bits=16, head_init_bits=40,
            ste_clip=True, use_tier_scales=True, group_size=16, precision_tenths=True,
            backbone_max_bits=20, head_max_bits=40,
            use_rms_norm=True, use_rope=True, use_qk_norm=True, use_swiglu=True,
        )
        m58 = BilingualNLITransformer(cfg_v58, use_quantization=True)
        self.assertEqual(m58.blocks[0].q_proj.max_bits, 20)
        self.assertEqual(m58.head_out.max_bits, 40)
        res58 = run_adaptive_v5x(
            variant_name="test_v58",
            cfg=cfg_v58,
            router_cfg=tiny_rcfg,
            init_state=tiny_init,
            train_ds=tiny_ds,
            val_loader=tiny_loader,
            seen_loader=tiny_loader,
            test_loader=tiny_loader,
            stress_loader=tiny_loader,
            device=torch.device("cpu"),
            epochs=2,
            min_stage1_epochs=1,
            max_stage1_epochs=1,
            batch_size=4,
            select_best_in_stage2=True,
            bit_cost_curriculum=(0.65, 1.45),
            verify_eval_batches=2,
            stage1_label_smoothing=0.05,
            stage1_emb_lr_mult=0.7,
            stage1_emb_weight_decay=0.03,
            sam_rho=0.03,
            emb_lr_mult=0.35,
            emb_weight_decay=0.08,
            seed=9,
        )
        self.assertEqual(len(res58["history"]), 2)
        for max_b in res58["final_bit_counts"]:
            self.assertLessEqual(int(max_b), 40)

    def test_v6_100m_spec_and_v5x_resume_parity(self) -> None:
        import argparse
        import tempfile
        from pathlib import Path
        from torch.utils.data import DataLoader, TensorDataset
        from adaptive_v5_series import run_adaptive_v5x
        from experiment_100m import make_100m_v6_spec
        from model import BilingualNLIConfig, BilingualNLITransformer, count_parameters
        from progressive_quant import BIT_LADDER_TERNARY, RouterConfig

        ns = argparse.Namespace(
            warmup_steps=250,
            epochs=4,
            min_stage1_epochs=2,
            max_stage1_epochs=2,
            batch_size=64,
            v6_lr=3.2e-4,
            v6_sam_rho=0.025,
            v6_sam_interval=2,
        )
        v6_cfg, v6_rcfg, v6_kw = make_100m_v6_spec(10_000, ns)
        pinfo = count_parameters(BilingualNLITransformer(v6_cfg, use_quantization=True))
        self.assertGreater(pinfo["total_params"], 95_000_000)
        self.assertLess(pinfo["total_params"], 100_600_000)
        self.assertTrue(v6_cfg.use_rms_norm and v6_cfg.use_rope and v6_cfg.use_qk_norm and v6_cfg.use_swiglu)
        self.assertEqual(v6_cfg.backbone_max_bits, 80)

        torch.manual_seed(17)
        tiny_ds = TensorDataset(
            torch.randint(1, 64, (8, 12)),
            torch.zeros((8, 12), dtype=torch.long),
            torch.ones((8, 12), dtype=torch.bool),
            torch.randint(0, 3, (8,)),
            torch.tensor([0, 1, 0, 1, 0, 1, 0, 1], dtype=torch.long),
        )
        tiny_loader = DataLoader(tiny_ds, batch_size=4, shuffle=False)
        tiny_cfg = BilingualNLIConfig(
            vocab_size=64, max_len=16, d_model=32, n_heads=2, n_layers=1, d_ff=84,
            initial_bits=10, protect_attention_and_head=True, attn_init_bits=16, head_init_bits=40,
            ste_clip=True, use_tier_scales=True, group_size=16, precision_tenths=True,
            backbone_max_bits=40, head_max_bits=80,
            use_rms_norm=True, use_rope=True, use_qk_norm=True, use_swiglu=True,
        )
        ref = BilingualNLITransformer(tiny_cfg, use_quantization=True)
        init_state = {k: v.detach().clone() for k, v in ref.state_dict().items()}
        rcfg = RouterConfig(
            bit_ladder=BIT_LADDER_TERNARY, precision_tenths=True,
            oscillation_band=0.1, min_delta=1e-6, oscillation_patience=1.0,
            warmup_steps=0, neuron_osc_threshold=0.1, max_verify_iters=1,
            enable_rollback_penalty=True, enforce_rollback_in_verify=True,
            strict_loss_gain_rollback=True, track_salience=True, use_salience_gating=True,
        )
        kw = dict(
            cfg=tiny_cfg, router_cfg=rcfg, init_state=init_state,
            train_ds=tiny_ds, val_loader=tiny_loader, seen_loader=tiny_loader,
            test_loader=tiny_loader, stress_loader=tiny_loader, device=torch.device("cpu"),
            min_stage1_epochs=1, max_stage1_epochs=1, batch_size=4,
            select_best_in_stage2=True, bit_cost_curriculum=(0.65, 1.40),
            verify_eval_batches=2, sam_rho=0.025, sam_interval=2,
            emb_lr_mult=0.5, emb_weight_decay=0.06, seed=17,
        )
        full = run_adaptive_v5x(variant_name="full_v6", epochs=3, **kw)

        class CrashAfterEp2:
            def __init__(self, base) -> None:
                self.base = base
                self.calls = 0

            def __iter__(self):
                self.calls += 1
                # Calls: Ep1 val (1), post-S1 val (2), Ep2 raw val (3), Ep2 ema val (4) -> fail on Ep3 raw val (5).
                if self.calls >= 5:
                    raise RuntimeError("Simulated mid-Stage-2 interruption")
                return iter(self.base)

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

        with tempfile.TemporaryDirectory() as tmp:
            ckpt_p = Path(tmp) / "v6.pt"
            kw_crash = {**kw, "val_loader": CrashAfterEp2(tiny_loader)}
            with self.assertRaises(RuntimeError):
                run_adaptive_v5x(variant_name="p1_v6", epochs=3, resume_file=ckpt_p, **kw_crash)
            resumed = run_adaptive_v5x(variant_name="p2_v6", epochs=3, resume_file=ckpt_p, **kw)
        self.assertAlmostEqual(full["test"]["acc"], resumed["test"]["acc"], places=6)
        self.assertAlmostEqual(full["final_avg_bits"], resumed["final_avg_bits"], places=6)
        self.assertEqual(full["best_val_epoch"], resumed["best_val_epoch"])
        for h_f, h_r in zip(full["history"], resumed["history"]):
            self.assertAlmostEqual(h_f["val_loss"], h_r["val_loss"], places=5)

    def test_bit_packed_safetensors_roundtrip(self) -> None:
        import tempfile
        from pathlib import Path
        from safetensors.torch import save_file
        from tokenizers import Tokenizer, models, pre_tokenizers
        from inference import load_nli_model, predict_nli
        from model import BilingualNLIConfig, BilingualNLITransformer
        from progressive_quant import (
            PrecisionRouter,
            RouterConfig,
            BIT_LADDER_TERNARY,
            pack_quantized_state_dict,
        )

        tok = Tokenizer(models.WordLevel(vocab={"[PAD]": 0, "[UNK]": 1, "[CLS]": 2, "[SEP]": 3, "hi": 4}, unk_token="[UNK]"))
        tok.pre_tokenizer = pre_tokenizers.Whitespace()
        cfg = BilingualNLIConfig(
            vocab_size=5, max_len=16, d_model=32, n_heads=2, n_layers=1, d_ff=84,
            initial_bits=10, protect_attention_and_head=True, attn_init_bits=16, head_init_bits=40,
            ste_clip=True, use_tier_scales=True, group_size=16, precision_tenths=True,
            backbone_max_bits=80, head_max_bits=160,
            use_rms_norm=True, use_rope=True, use_qk_norm=True, use_swiglu=True,
        )
        m = BilingualNLITransformer(cfg, use_quantization=True)
        with torch.no_grad():
            # Exercise all 5 bit tiers simultaneously (1b, 1.585b, 2b, 4b, 8b) across rows.
            m.blocks[0].ffn_in.bit_widths[:16] = 10
            m.blocks[0].ffn_in.bit_widths[16:32] = 16
            m.blocks[0].ffn_in.bit_widths[32:48] = 20
            m.blocks[0].ffn_in.bit_widths[48:64] = 40
            m.blocks[0].ffn_in.bit_widths[64:] = 80
            m.blocks[0].ffn_in.log_tier_scales.copy_(torch.tensor([0.1, -0.05, 0.08, -0.04, 0.02, 0.0, 0.0]))
            m.blocks[0].ffn_in.reallocate_blocks()
        m.eval()

        ids = torch.randint(1, 5, (3, 8))
        segs = torch.zeros((3, 8), dtype=torch.long)
        mask = torch.ones((3, 8), dtype=torch.bool)
        with torch.no_grad():
            orig_logits = m(ids, segs, mask)

        packed = pack_quantized_state_dict(m)
        self.assertIn("__odpe_packed_version__", packed)
        with tempfile.TemporaryDirectory() as tmp:
            p = Path(tmp)
            tok_p = p / "tok.json"
            ckpt_p = p / "v6_packed.safetensors"
            tok.save(str(tok_p))
            save_file(packed, str(ckpt_p))
            loaded, ltok = load_nli_model(ckpt_p, tok_p, use_quantization=True, device="cpu", cfg=cfg)
            self.assertTrue(loaded.blocks[0].ffn_in.prequantized)
            with torch.no_grad():
                rec_logits = loaded(ids, segs, mask)
            self.assertTrue(torch.allclose(orig_logits, rec_logits, atol=2e-2))
            snap = PrecisionRouter(RouterConfig(bit_ladder=BIT_LADDER_TERNARY, precision_tenths=True)).snapshot_stats(loaded)
            self.assertLess(snap.avg_bits, 4.0)
            out = predict_nli(loaded, ltok, "hi", "hi", device="cpu", max_len=16)
            self.assertIn(out["label"], {"entailment", "neutral", "contradiction"})


if __name__ == "__main__":
    unittest.main()