File size: 54,146 Bytes
a1aff72
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
1c5db53
 
 
 
a1aff72
 
 
1c5db53
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
1c5db53
a1aff72
1c5db53
 
 
a1aff72
1c5db53
a1aff72
 
 
1c5db53
 
 
 
a1aff72
1c5db53
a1aff72
 
 
1c5db53
 
a1aff72
 
 
 
1c5db53
 
 
 
 
 
 
 
a1aff72
1c5db53
a1aff72
1c5db53
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
1c5db53
 
 
 
 
a1aff72
 
1c5db53
a1aff72
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
a1aff72
1c5db53
a1aff72
1c5db53
 
a1aff72
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
a1aff72
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
1c5db53
a1aff72
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
a1aff72
 
 
1c5db53
a1aff72
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
a1aff72
 
 
 
 
1c5db53
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
1c5db53
a1aff72
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1aff72
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
a1aff72
1c5db53
a1aff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5db53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
"""Progressive quantization layers and adaptive precision router.

Supports both fine-grained per-parameter quantization and neuron-level
homogeneous precision block execution with dynamic block reallocation.
Parameters start at 1 bit and grow along BIT_LADDER up to FP32 (32-bit)
when the PrecisionRouter detects sustained oscillations, followed by
an iterative same-task verification loop.
"""

from __future__ import annotations

import math
from dataclasses import dataclass, field
from typing import Callable, Iterable, Literal, Tuple

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

BIT_LADDER: Tuple[int, ...] = (1, 2, 4, 8, 16, 32)
BIT_LADDER_TERNARY: Tuple[int, ...] = (10, 16, 20, 40, 80, 160, 320)
LOG2_3: float = math.log2(3.0)
_BIT_TO_TIER: dict[int, int] = {b: i for i, b in enumerate(BIT_LADDER)}
_TERNARY_BIT_TO_TIER: dict[int, int] = {b: i for i, b in enumerate(BIT_LADDER_TERNARY)}
Granularity = Literal["element", "neuron"]


def effective_bits_for_code(code: int, precision_tenths: bool = False) -> float:
    """Convert an integer bit code (standard or tenths-encoded ternary ladder) to real bits."""
    if not precision_tenths:
        return float(code)
    if code == 16:
        return LOG2_3
    return float(code) / 10.0


def _channel_reduce_dims(tensor: torch.Tensor) -> Tuple[int, ...]:
    if tensor.ndim <= 1:
        return (0,)
    return tuple(range(1, tensor.ndim))


def effective_group_size(in_dim: int, group_size: int) -> int:
    """Resolve sub-channel group width dividing `in_dim`, or 0 for full-row scaling."""
    if group_size <= 0 or group_size >= in_dim:
        return 0
    if in_dim % group_size == 0:
        return group_size
    g = math.gcd(in_dim, group_size)
    return g if g >= 8 else 0


def _prepare_group_view(
    weight: torch.Tensor,
    group_size: int,
) -> Tuple[torch.Tensor, Tuple[int, ...], bool]:
    """Reshape weight into (..., n_groups, eff_g) when group scaling applies cleanly."""
    if group_size > 0 and weight.ndim >= 2:
        eff_g = effective_group_size(weight.shape[-1], group_size)
        if eff_g > 0:
            w_view = weight.reshape(*weight.shape[:-1], weight.shape[-1] // eff_g, eff_g)
            return w_view, (-1,), True
    return weight, _channel_reduce_dims(weight), False


def _ste_clip_bound(
    weight: torch.Tensor,
    bits: int,
    reduce_dims: Tuple[int, ...],
    eps: float = 1e-8,
    precision_tenths: bool = False,
) -> torch.Tensor:
    eff = effective_bits_for_code(bits, precision_tenths=precision_tenths)
    if eff < 1.8:
        return 2.0 * weight.detach().abs().mean(dim=reduce_dims, keepdim=True).clamp_min(eps)
    return weight.detach().abs().amax(dim=reduce_dims, keepdim=True).clamp_min(eps)


def _quantize_for_bits(
    weight: torch.Tensor,
    bits: int,
    reduce_dims: Tuple[int, ...],
    eps: float = 1e-8,
    precision_tenths: bool = False,
) -> torch.Tensor:
    """Compute quantized tensor values for a single target bit-width (supports 1.58b ternary)."""
    eff = effective_bits_for_code(bits, precision_tenths=precision_tenths)
    if eff >= 32.0:
        return weight
    if abs(eff - 1.0) < 1e-6:
        alpha = weight.detach().abs().mean(dim=reduce_dims, keepdim=True).clamp_min(eps)
        signs = torch.where(weight >= 0, 1.0, -1.0)
        return alpha * signs
    if eff < 1.8:
        # BitNet b1.58 ternary {-alpha, 0, +alpha} with zero deadzone near origin.
        alpha = weight.detach().abs().mean(dim=reduce_dims, keepdim=True).clamp_min(eps)
        return torch.clamp(torch.round(weight / alpha), -1.0, 1.0) * alpha
    abs_max = weight.detach().abs().amax(dim=reduce_dims, keepdim=True).clamp_min(eps)
    if abs(eff - 2.0) < 1e-6:
        # 4 symmetric non-zero levels {-1, -1/3, +1/3, +1} * abs_max avoid zero-collapsing small weights.
        step = abs_max / 1.5
        return (torch.clamp(torch.round(weight / step - 0.5), -2.0, 1.0) + 0.5) * step
    int_bits = max(2, int(round(eff)))
    qmax = float((1 << (int_bits - 1)) - 1)
    step = abs_max / qmax
    return torch.clamp(torch.round(weight / step), -qmax, qmax) * step


def quantize_uniform_bits(
    weight: torch.Tensor,
    bits: int,
    eps: float = 1e-8,
    ste_clip: bool = False,
    group_size: int = 0,
    precision_tenths: bool = False,
) -> torch.Tensor:
    """Quantize a tensor whose elements all share a single bit-width using STE."""
    if effective_bits_for_code(bits, precision_tenths=precision_tenths) >= 32.0:
        return weight
    w_view, reduce_dims, grouped = _prepare_group_view(weight, group_size)
    q = _quantize_for_bits(w_view, bits, reduce_dims, eps=eps, precision_tenths=precision_tenths)
    if grouped:
        q = q.reshape_as(weight)
    if ste_clip:
        bound = _ste_clip_bound(w_view, bits, reduce_dims, eps=eps, precision_tenths=precision_tenths)
        if grouped:
            bound = bound.expand_as(w_view).reshape_as(weight)
        w_grad = torch.clamp(weight, -bound, bound)
        return w_grad + (q - w_grad).detach()
    return weight + (q - weight).detach()


def quantize_per_element(
    weight: torch.Tensor,
    bit_widths: torch.Tensor,
    eps: float = 1e-8,
    ste_clip: bool = False,
    log_tier_scales: torch.Tensor | None = None,
    group_size: int = 0,
    precision_tenths: bool = False,
    bit_to_tier: dict[int, int] | None = None,
) -> torch.Tensor:
    """Quantize each parameter (or row if broadcastable) according to bit_widths using STE."""
    tier_map = bit_to_tier if bit_to_tier is not None else (_TERNARY_BIT_TO_TIER if precision_tenths else _BIT_TO_TIER)
    if bit_widths.ndim == 1 and weight.ndim > 1:
        view_shape = (weight.shape[0],) + (1,) * (weight.ndim - 1)
        bit_widths_view = bit_widths.view(view_shape)
    else:
        bit_widths_view = bit_widths

    unique_bits = torch.unique(bit_widths_view).tolist()
    if len(unique_bits) == 1:
        bits = int(unique_bits[0])
        out = quantize_uniform_bits(
            weight, bits, eps=eps, ste_clip=ste_clip, group_size=group_size, precision_tenths=precision_tenths
        )
        if log_tier_scales is not None and effective_bits_for_code(bits, precision_tenths=precision_tenths) < 32.0:
            out = out * torch.exp(log_tier_scales[tier_map[bits]].clamp(-1.5, 1.5))
        return out

    w_view, reduce_dims, grouped = _prepare_group_view(weight, group_size)
    quantized = weight.clone()
    clip_bounds = torch.full_like(weight, float("inf")) if ste_clip else None
    scale_map = torch.ones_like(weight) if log_tier_scales is not None else None
    for b in unique_bits:
        bits = int(b)
        mask = bit_widths_view == bits
        if effective_bits_for_code(bits, precision_tenths=precision_tenths) < 32.0:
            q_b = _quantize_for_bits(w_view, bits, reduce_dims, eps=eps, precision_tenths=precision_tenths)
            if grouped:
                q_b = q_b.reshape_as(weight)
            quantized = torch.where(mask, q_b, quantized)
            if clip_bounds is not None:
                b_b = _ste_clip_bound(w_view, bits, reduce_dims, eps=eps, precision_tenths=precision_tenths)
                if grouped:
                    b_b = b_b.expand_as(w_view).reshape_as(weight)
                clip_bounds = torch.where(mask, b_b, clip_bounds)
            if scale_map is not None and log_tier_scales is not None:
                s_b = torch.exp(log_tier_scales[tier_map[bits]].clamp(-1.5, 1.5))
                scale_map = torch.where(mask, s_b, scale_map)

    w_grad = torch.clamp(weight, -clip_bounds, clip_bounds) if clip_bounds is not None else weight
    out = w_grad + (quantized - w_grad).detach()
    return out * scale_map if scale_map is not None else out


class _ProgressiveWeightMixin:
    """Shared progressive quantization state and block reallocation for weight layers."""

    weight: nn.Parameter
    bit_widths: torch.Tensor
    use_quantization: bool
    granularity: Granularity
    use_block_execution: bool
    ste_clip: bool
    use_tier_scales: bool
    bit_cost_scale: float
    group_size: int
    precision_tenths: bool
    min_bits: int
    max_bits: int
    block_perm: torch.Tensor
    block_inv_perm: torch.Tensor
    _block_slices: list[Tuple[int, int, int]]

    def _init_progressive_state(
        self,
        initial_bits: int = 1,
        use_quantization: bool = True,
        granularity: Granularity = "element",
        use_block_execution: bool = True,
        ste_clip: bool = False,
        use_tier_scales: bool = False,
        bit_cost_scale: float = 1.0,
        group_size: int = 0,
        precision_tenths: bool = False,
        max_bits: int | None = None,
    ) -> None:
        if granularity not in ("element", "neuron"):
            raise ValueError(f"Unsupported granularity: {granularity}")
        self.use_quantization = use_quantization
        self.granularity = granularity
        self.use_block_execution = use_block_execution and (granularity == "neuron")
        self.ste_clip = ste_clip
        self.use_tier_scales = use_tier_scales
        self.bit_cost_scale = float(bit_cost_scale)
        self.group_size = int(group_size)
        self.precision_tenths = bool(precision_tenths)
        self.prequantized = False
        self.min_bits = int(initial_bits)

        ladder = BIT_LADDER_TERNARY if self.precision_tenths else BIT_LADDER
        self.max_bits = int(max_bits) if max_bits is not None else int(ladder[-1])
        self._bit_to_tier: dict[int, int] = {b: i for i, b in enumerate(ladder)}

        if use_tier_scales and use_quantization:
            self.register_parameter(
                "log_tier_scales",
                nn.Parameter(torch.zeros(len(ladder), dtype=self.weight.dtype, device=self.weight.device)),
            )

        bw_shape = (self.weight.shape[0],) if granularity == "neuron" else self.weight.shape
        bw_dtype = torch.int16 if self.precision_tenths else torch.int8
        self.register_buffer(
            "bit_widths",
            torch.full(bw_shape, initial_bits, dtype=bw_dtype, device=self.weight.device),
        )
        n_out = self.weight.shape[0]
        self.register_buffer(
            "block_perm",
            torch.arange(n_out, dtype=torch.long, device=self.weight.device),
        )
        self.register_buffer(
            "block_inv_perm",
            torch.arange(n_out, dtype=torch.long, device=self.weight.device),
        )
        self._block_slices = [(initial_bits, 0, n_out)]
        if self.use_block_execution:
            self.reallocate_blocks()

    def _tier_scale(self, bits: int) -> torch.Tensor | float:
        if not self.use_tier_scales or not self.use_quantization:
            return 1.0
        if effective_bits_for_code(bits, precision_tenths=self.precision_tenths) >= 32.0:
            return 1.0
        log_scales = getattr(self, "log_tier_scales", None)
        if log_scales is None:
            return 1.0
        return torch.exp(log_scales[self._bit_to_tier[bits]].clamp(-1.5, 1.5))

    @torch.no_grad()
    def reallocate_blocks(self) -> int:
        """Group neurons into contiguous homogeneous bit-width blocks.

        Returns the number of active precision blocks.
        """
        if self.granularity != "neuron":
            return 1
        perm = torch.argsort(self.bit_widths, stable=True)
        inv_perm = torch.argsort(perm)
        self.block_perm.copy_(perm)
        self.block_inv_perm.copy_(inv_perm)

        sorted_bits = self.bit_widths[perm].tolist()
        slices: list[Tuple[int, int, int]] = []
        if sorted_bits:
            curr_b = int(sorted_bits[0])
            start = 0
            for idx, b in enumerate(sorted_bits[1:], start=1):
                if int(b) != curr_b:
                    slices.append((curr_b, start, idx))
                    curr_b = int(b)
                    start = idx
            slices.append((curr_b, start, len(sorted_bits)))
        self._block_slices = slices
        return len(slices)

    def effective_weight(self) -> torch.Tensor:
        if not self.use_quantization:
            return self.weight
        log_scales = getattr(self, "log_tier_scales", None) if self.use_tier_scales else None
        return quantize_per_element(
            self.weight,
            self.bit_widths,
            ste_clip=self.ste_clip,
            log_tier_scales=log_scales,
            group_size=self.group_size,
            precision_tenths=self.precision_tenths,
            bit_to_tier=self._bit_to_tier,
        )


class ProgressiveLinear(nn.Linear, _ProgressiveWeightMixin):
    """Linear layer supporting classical FP32, per-weight, or neuron-block progressive quantization."""

    def __init__(
        self,
        in_features: int,
        out_features: int,
        bias: bool = True,
        initial_bits: int = 1,
        use_quantization: bool = True,
        granularity: Granularity = "element",
        use_block_execution: bool = True,
        ste_clip: bool = False,
        use_tier_scales: bool = False,
        bit_cost_scale: float = 1.0,
        group_size: int = 0,
        precision_tenths: bool = False,
        max_bits: int | None = None,
        device=None,
        dtype=None,
    ) -> None:
        super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype)
        self._init_progressive_state(
            initial_bits=initial_bits,
            use_quantization=use_quantization,
            granularity=granularity,
            use_block_execution=use_block_execution,
            ste_clip=ste_clip,
            use_tier_scales=use_tier_scales,
            bit_cost_scale=bit_cost_scale,
            group_size=group_size,
            precision_tenths=precision_tenths,
            max_bits=max_bits,
        )

    def forward(self, input: torch.Tensor) -> torch.Tensor:
        if not self.use_quantization or self.prequantized:
            return F.linear(input, self.weight, self.bias)

        if self.use_block_execution:
            if len(self._block_slices) == 1:
                bits = self._block_slices[0][0]
                w_uni = (
                    quantize_uniform_bits(
                        self.weight,
                        bits,
                        ste_clip=self.ste_clip,
                        group_size=self.group_size,
                        precision_tenths=self.precision_tenths,
                    )
                    * self._tier_scale(bits)
                )
                return F.linear(input, w_uni, self.bias)

            w_packed = self.weight.index_select(0, self.block_perm)
            b_packed = self.bias.index_select(0, self.block_perm) if self.bias is not None else None
            w_q_blocks = [
                quantize_uniform_bits(
                    w_packed[start:end],
                    bits,
                    ste_clip=self.ste_clip,
                    group_size=self.group_size,
                    precision_tenths=self.precision_tenths,
                )
                * self._tier_scale(bits)
                for bits, start, end in self._block_slices
            ]
            w_q_packed = torch.cat(w_q_blocks, dim=0)
            return F.linear(input, w_q_packed, b_packed).index_select(-1, self.block_inv_perm)

        return F.linear(input, self.effective_weight(), self.bias)


class ProgressiveConv2d(nn.Conv2d, _ProgressiveWeightMixin):
    """Conv2d layer supporting classical FP32, per-weight, or channel-neuron progressive quantization."""

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size,
        stride=1,
        padding=0,
        dilation=1,
        groups: int = 1,
        bias: bool = True,
        padding_mode: str = "zeros",
        initial_bits: int = 1,
        use_quantization: bool = True,
        granularity: Granularity = "element",
        use_block_execution: bool = True,
        group_size: int = 0,
        device=None,
        dtype=None,
    ) -> None:
        super().__init__(
            in_channels,
            out_channels,
            kernel_size,
            stride=stride,
            padding=padding,
            dilation=dilation,
            groups=groups,
            bias=bias,
            padding_mode=padding_mode,
            device=device,
            dtype=dtype,
        )
        self._init_progressive_state(
            initial_bits=initial_bits,
            use_quantization=use_quantization,
            granularity=granularity,
            use_block_execution=use_block_execution,
            group_size=group_size,
        )

    def forward(self, input: torch.Tensor) -> torch.Tensor:
        return self._conv_forward(input, self.effective_weight(), self.bias)


def iter_progressive_layers(model: nn.Module) -> Iterable[_ProgressiveWeightMixin]:
    """Yield quantized progressive layers in deterministic module order."""
    for module in model.modules():
        if isinstance(module, _ProgressiveWeightMixin) and module.use_quantization:
            yield module


@dataclass
class RouterConfig:
    """Configuration for oscillation detection, bit promotion, block reallocation, and verification."""

    bit_ladder: Tuple[int, ...] = BIT_LADDER
    oscillation_band: float | None = 0.1
    min_delta: float = 1e-6
    oscillation_patience: float = 1.0
    osc_decay: float = 0.0
    warmup_steps: int = 0
    neuron_osc_threshold: float = 0.15
    max_verify_iters: int = 3
    loss_improvement_tol: float = 1e-4
    target_metric: float | None = None
    grad_clip_norm: float | None = 1.0
    enable_rollback_penalty: bool = False
    rollback_min_loss_gain: float = 1e-3
    rollback_bit_cost_weight: float = 0.01
    rollback_cooldown_steps: int = 12
    rollback_patience_penalty: float = 0.5
    enforce_rollback_in_verify: bool = False
    strict_loss_gain_rollback: bool = False
    track_salience: bool = False
    use_salience_gating: bool = False
    salience_ema_decay: float = 0.88
    salience_min_ratio: float = 0.85
    use_weighted_bit_cost: bool = False
    unit_fraction_penalty: bool = False
    precision_tenths: bool = False


@dataclass
class PromotionStats:
    """Summary of a single router observation, promotion, and block reallocation pass."""

    num_units: int
    num_params: int
    num_oscillating: int
    num_promoted: int
    num_reallocations: int
    avg_bits: float
    bit_counts: dict[int, int] = field(default_factory=dict)


@dataclass
class StepReport:
    """Telemetry from one training step including iterative verification passes."""

    initial_loss: float
    final_loss: float
    initial_metric: float
    final_metric: float
    verify_iters: int
    total_promoted: int
    total_rollbacks: int
    total_reallocations: int
    oscillating_after: int
    avg_bits: float
    bit_counts: dict[int, int]
    metric_improved: bool


class PrecisionRouter:
    """Monitors weight/neuron oscillations, upgrades precision, reallocates blocks, and re-verifies."""

    def __init__(self, config: RouterConfig | None = None) -> None:
        self.config = config or RouterConfig()
        if self.config.precision_tenths and tuple(self.config.bit_ladder) == BIT_LADDER:
            self.config.bit_ladder = BIT_LADDER_TERNARY
        if tuple(sorted(self.config.bit_ladder)) != tuple(self.config.bit_ladder):
            raise ValueError("bit_ladder must be sorted in ascending order")
        self._next_bits_map = {
            curr: nxt for curr, nxt in zip(self.config.bit_ladder[:-1], self.config.bit_ladder[1:])
        }
        self._prev_bits_map = {
            nxt: curr for curr, nxt in zip(self.config.bit_ladder[:-1], self.config.bit_ladder[1:])
        }
        self._max_bits = self.config.bit_ladder[-1]
        self._state: dict[int, dict[str, torch.Tensor]] = {}
        self._step_count = 0

    def _get_or_init_state(self, layer: _ProgressiveWeightMixin) -> dict[str, torch.Tensor]:
        key = id(layer)
        if key not in self._state:
            w = layer.weight.detach()
            streak_shape = (w.shape[0],) if layer.granularity == "neuron" else w.shape
            self._state[key] = {
                "prev_w": w.clone(),
                "prev_delta": torch.zeros_like(w),
                "has_prev_delta": torch.zeros((), dtype=torch.bool, device=w.device),
                "osc_streak": torch.zeros(streak_shape, dtype=torch.float32, device=w.device),
                "cooldown": torch.zeros(streak_shape, dtype=torch.int32, device=w.device),
                "penalty_boost": torch.zeros(streak_shape, dtype=torch.float32, device=w.device),
                "salience": torch.zeros(streak_shape, dtype=torch.float32, device=w.device),
            }
        return self._state[key]

    @torch.no_grad()
    def _update_salience(self, model: nn.Module) -> None:
        cfg = self.config
        if not (cfg.track_salience or cfg.use_salience_gating):
            return
        decay = float(cfg.salience_ema_decay)
        for layer in iter_progressive_layers(model):
            grad = layer.weight.grad
            if grad is None:
                continue
            state = self._get_or_init_state(layer)
            raw_sal = (grad.detach().float() * layer.weight.detach().float()).abs()
            if layer.granularity == "neuron":
                unit_sal = raw_sal.mean(dim=_channel_reduce_dims(raw_sal))
            else:
                unit_sal = raw_sal
            state["salience"].mul_(decay).add_(unit_sal, alpha=1.0 - decay)

    @torch.no_grad()
    def snapshot_stats(self, model: nn.Module) -> PromotionStats:
        """Collect current bit-width distribution across progressive layers without mutating state."""
        total_units = 0
        total_params = 0
        weighted_bits = 0.0
        bit_counts: dict[int, int] = {b: 0 for b in self.config.bit_ladder}
        tenths = self.config.precision_tenths

        for layer in iter_progressive_layers(model):
            bw = layer.bit_widths
            unit_param_mul = layer.weight[0].numel() if layer.granularity == "neuron" else 1
            total_units += bw.numel()
            total_params += layer.weight.numel()
            for b in self.config.bit_ladder:
                count = int((bw == b).sum().item()) * unit_param_mul
                if count:
                    bit_counts[b] = bit_counts.get(b, 0) + count
                    weighted_bits += float(count) * effective_bits_for_code(b, precision_tenths=tenths)

        avg_bits = weighted_bits / total_params if total_params > 0 else 32.0
        return PromotionStats(
            num_units=total_units,
            num_params=total_params,
            num_oscillating=0,
            num_promoted=0,
            num_reallocations=0,
            avg_bits=avg_bits,
            bit_counts={b: c for b, c in bit_counts.items() if c > 0},
        )

    @torch.no_grad()
    def observe_and_promote(
        self,
        model: nn.Module,
        verify_masks: dict[int, torch.Tensor] | None = None,
    ) -> tuple[PromotionStats, dict[int, torch.Tensor]]:
        """Detect oscillating weights/neurons, promote precision, and reallocate homogeneous blocks.

        When `verify_masks` is provided (inside the same-task verification loop), units that were
        just promoted and continue oscillating on the re-run are promoted immediately without
        waiting for `oscillation_patience` again.
        """
        cfg = self.config
        if verify_masks is None:
            self._step_count += 1
        in_warmup = (verify_masks is None) and (self._step_count <= cfg.warmup_steps)

        total_units = 0
        total_params = 0
        total_oscillating = 0
        total_promoted = 0
        total_reallocations = 0
        weighted_bits = 0.0
        bit_counts: dict[int, int] = {b: 0 for b in cfg.bit_ladder}
        promoted_masks: dict[int, torch.Tensor] = {}

        for layer in iter_progressive_layers(model):
            state = self._get_or_init_state(layer)
            curr_w = layer.weight.detach()
            prev_w = state["prev_w"]
            prev_delta = state["prev_delta"]
            curr_delta = curr_w - prev_w

            reversed_dir = (
                state["has_prev_delta"]
                & (prev_delta * curr_delta < 0)
                & (prev_delta.abs() > cfg.min_delta)
                & (curr_delta.abs() > cfg.min_delta)
            )
            sign_flipped = (prev_w * curr_w < 0) & (curr_delta.abs() > cfg.min_delta)
            oscillating_elem = reversed_dir | sign_flipped

            if cfg.oscillation_band is not None:
                in_band = (curr_w.abs() <= cfg.oscillation_band) | (
                    prev_w.abs() <= cfg.oscillation_band
                )
                oscillating_elem = oscillating_elem & in_band

            if layer.granularity == "neuron":
                reduce_dims = _channel_reduce_dims(curr_w)
                osc_fraction = oscillating_elem.float().mean(dim=reduce_dims)
                oscillating_unit = osc_fraction >= cfg.neuron_osc_threshold
                unit_param_mul = curr_w[0].numel()
            else:
                oscillating_unit = oscillating_elem
                unit_param_mul = 1

            osc_streak = state["osc_streak"]
            cooldown = state["cooldown"]
            if verify_masks is None and cooldown.any():
                cooldown = (cooldown - 1).clamp_min(0)
                state["cooldown"].copy_(cooldown)

            if in_warmup:
                osc_streak.zero_()
                promote_mask = torch.zeros_like(oscillating_unit, dtype=torch.bool)
                osc_count_for_report = 0
            else:
                if cfg.osc_decay > 0.0:
                    osc_streak = osc_streak * cfg.osc_decay + oscillating_unit.float()
                else:
                    osc_streak = torch.where(
                        oscillating_unit, osc_streak + 1.0, torch.zeros_like(osc_streak)
                    )

                layer_cap = min(self._max_bits, int(getattr(layer, "max_bits", self._max_bits)))
                can_upgrade = (layer.bit_widths < layer_cap) & (cooldown == 0)
                if cfg.use_salience_gating:
                    sal = state["salience"]
                    sal_mean = float(sal.mean().item())
                    if sal_mean > 0.0:
                        can_upgrade = can_upgrade & (sal >= cfg.salience_min_ratio * sal_mean)
                req_patience = cfg.oscillation_patience + state["penalty_boost"]
                patience_hit = osc_streak >= req_patience
                if verify_masks is not None and id(layer) in verify_masks:
                    v_mask = verify_masks[id(layer)]
                    promote_mask = (patience_hit | (oscillating_unit & v_mask)) & can_upgrade
                    osc_count_for_report = int((oscillating_unit & v_mask).sum().item())
                else:
                    promote_mask = patience_hit & can_upgrade
                    osc_count_for_report = int(oscillating_unit.sum().item())

                if promote_mask.any():
                    new_bw = layer.bit_widths.clone()
                    for curr_b, next_b in self._next_bits_map.items():
                        level_mask = promote_mask & (layer.bit_widths == curr_b)
                        if level_mask.any():
                            new_bw[level_mask] = next_b
                    layer.bit_widths.copy_(new_bw)
                    osc_streak = torch.where(promote_mask, torch.zeros_like(osc_streak), osc_streak)
                    if layer.granularity == "neuron":
                        layer.reallocate_blocks()
                        total_reallocations += 1

            promoted_masks[id(layer)] = promote_mask

            state["prev_w"].copy_(curr_w)
            state["prev_delta"].copy_(curr_delta)
            state["has_prev_delta"].fill_(True)
            state["osc_streak"].copy_(osc_streak)

            total_units += layer.bit_widths.numel()
            total_params += curr_w.numel()
            total_oscillating += osc_count_for_report
            total_promoted += int(promote_mask.sum().item())
            for b in cfg.bit_ladder:
                count = int((layer.bit_widths == b).sum().item()) * unit_param_mul
                if count:
                    bit_counts[b] = bit_counts.get(b, 0) + count
                    weighted_bits += float(count) * effective_bits_for_code(
                        b, precision_tenths=cfg.precision_tenths
                    )

        avg_bits = weighted_bits / total_params if total_params > 0 else 32.0
        stats = PromotionStats(
            num_units=total_units,
            num_params=total_params,
            num_oscillating=total_oscillating,
            num_promoted=total_promoted,
            num_reallocations=total_reallocations,
            avg_bits=avg_bits,
            bit_counts={b: c for b, c in bit_counts.items() if c > 0},
        )
        return stats, promoted_masks

    @torch.no_grad()
    def _rollback_promotions(
        self,
        model: nn.Module,
        old_bits_snap: dict[int, torch.Tensor],
        promoted_masks: dict[int, torch.Tensor],
    ) -> int:
        """Revert unjustified promotions, reallocate blocks, and apply cooldown/patience penalty."""
        cfg = self.config
        reverted = 0
        for layer in iter_progressive_layers(model):
            lid = id(layer)
            pmask = promoted_masks.get(lid)
            if pmask is not None and pmask.any():
                reverted += int(pmask.sum().item())
                layer.bit_widths.copy_(old_bits_snap[lid])
                if layer.granularity == "neuron":
                    layer.reallocate_blocks()
                state = self._get_or_init_state(layer)
                state["cooldown"] = torch.where(
                    pmask,
                    torch.full_like(state["cooldown"], cfg.rollback_cooldown_steps),
                    state["cooldown"],
                )
                state["penalty_boost"] = torch.where(
                    pmask,
                    (state["penalty_boost"] + cfg.rollback_patience_penalty).clamp_max(3.0),
                    state["penalty_boost"],
                )
        return reverted

    def _should_keep_promotion(
        self,
        model: nn.Module,
        batch_step_fn: Callable[[], Tuple[torch.Tensor, float]],
        old_bits_snap: dict[int, torch.Tensor],
        avg_bits_before: float,
        new_bits_snap: dict[int, torch.Tensor],
        stats_after: PromotionStats,
    ) -> Tuple[bool, float, float]:
        """Deterministically compare old vs. new bit-widths on current batch in eval mode."""
        cfg = self.config
        was_training = model.training
        model.eval()
        try:
            with torch.no_grad():
                post_loss_t, post_metric_val = batch_step_fn()
                post_loss = float(post_loss_t.item())
                post_metric = float(post_metric_val)

                for layer in iter_progressive_layers(model):
                    if id(layer) in new_bits_snap:
                        layer.bit_widths.copy_(old_bits_snap[id(layer)])
                        if layer.granularity == "neuron":
                            layer.reallocate_blocks()
                pre_loss_t, pre_metric_val = batch_step_fn()
                pre_loss = float(pre_loss_t.item())
                pre_metric = float(pre_metric_val)

                for layer in iter_progressive_layers(model):
                    if id(layer) in new_bits_snap:
                        layer.bit_widths.copy_(new_bits_snap[id(layer)])
                        if layer.granularity == "neuron":
                            layer.reallocate_blocks()
        finally:
            model.train(was_training)

        if cfg.use_weighted_bit_cost or cfg.unit_fraction_penalty:
            weighted_delta = 0.0
            total_params = 0
            upgraded_units = 0
            total_units = 0
            for layer in iter_progressive_layers(model):
                lid = id(layer)
                unit_mul = layer.weight[0].numel() if layer.granularity == "neuron" else 1
                total_params += layer.weight.numel()
                total_units += layer.bit_widths.numel()
                if lid in new_bits_snap:
                    if cfg.precision_tenths:
                        def _to_eff(t: torch.Tensor) -> torch.Tensor:
                            out_t = t.to(torch.float32) / 10.0
                            return torch.where(t == 16, torch.full_like(out_t, LOG2_3), out_t)

                        diff = (_to_eff(new_bits_snap[lid]) - _to_eff(old_bits_snap[lid])).clamp_min(0.0)
                    else:
                        diff = (
                            new_bits_snap[lid].to(torch.float32) - old_bits_snap[lid].to(torch.float32)
                        ).clamp_min(0.0)
                    upgraded_units += int((diff > 0).sum().item())
                    cost_scale = float(getattr(layer, "bit_cost_scale", 1.0)) if cfg.use_weighted_bit_cost else 1.0
                    weighted_delta += float(diff.sum().item()) * unit_mul * cost_scale
            delta_bits_norm = weighted_delta / (31.0 * max(1, total_params))
            if cfg.unit_fraction_penalty:
                # Preserve sensitivity across widths (10M -> 100M+): blend fractional param delta with unit fraction.
                unit_frac = upgraded_units / max(1, total_units)
                delta_bits_norm = 0.5 * delta_bits_norm + 0.5 * (unit_frac / 31.0)
        else:
            delta_bits_norm = max(0.0, (stats_after.avg_bits - avg_bits_before) / 31.0)
        required_gain = cfg.rollback_min_loss_gain + cfg.rollback_bit_cost_weight * delta_bits_norm
        loss_gain = pre_loss - post_loss
        metric_gain = post_metric - pre_metric

        if cfg.strict_loss_gain_rollback:
            keep = loss_gain >= required_gain
        else:
            keep = (loss_gain >= required_gain) or (metric_gain > 0.0)
        return keep, pre_loss, pre_metric

    @torch.no_grad()
    def consolidate_down(
        self,
        model: nn.Module,
        eval_fn: Callable[[], Tuple[float, float]],
        fractions: Tuple[float, ...] = (0.15, 0.30, 0.45),
        max_loss_increase: float = 0.005,
        max_metric_drop: float = 0.002,
    ) -> dict[str, float | int]:
        """Step down lowest-salience promoted units if validation loss stays within tolerance."""
        was_training = model.training
        model.eval()
        bits_before = self.snapshot_stats(model).avg_bits
        base_loss, base_metric = eval_fn()

        candidates: list[Tuple[float, _ProgressiveWeightMixin, int, int, int]] = []
        for layer in iter_progressive_layers(model):
            floor_b = int(getattr(layer, "min_bits", 1))
            sal = self._get_or_init_state(layer)["salience"]
            sal_mean = max(1e-12, float(sal.mean().item())) if sal.numel() > 0 else 1.0
            bw_list = layer.bit_widths.view(-1).tolist()
            sal_list = sal.view(-1).tolist()
            for idx, (b_raw, s_raw) in enumerate(zip(bw_list, sal_list)):
                b = int(b_raw)
                if b > floor_b and b in self._prev_bits_map:
                    prev_b = max(floor_b, self._prev_bits_map[b])
                    if prev_b < b:
                        cost_scale = float(getattr(layer, "bit_cost_scale", 1.0))
                        # Prefer pruning high bit-cost / lowest-salience neurons first.
                        score = float(s_raw / sal_mean) / max(0.1, cost_scale)
                        candidates.append((score, layer, idx, b, prev_b))

        if not candidates:
            model.train(was_training)
            return {"num_pruned": 0, "bits_before": bits_before, "bits_after": bits_before, "loss_delta": 0.0}

        candidates.sort(key=lambda item: item[0])
        snap_orig = {id(layer): layer.bit_widths.detach().clone() for layer in iter_progressive_layers(model)}
        best_frac_snap = None
        best_pruned = 0
        best_loss_delta = 0.0
        best_bits_after = bits_before

        for frac in sorted(fractions):
            k = max(1, int(round(frac * len(candidates))))
            for layer in iter_progressive_layers(model):
                layer.bit_widths.copy_(snap_orig[id(layer)])
            affected_layers = set()
            for _, layer, idx, _, prev_b in candidates[:k]:
                layer.bit_widths.view(-1)[idx] = prev_b
                affected_layers.add(layer)
            for layer in affected_layers:
                if layer.granularity == "neuron":
                    layer.reallocate_blocks()

            new_loss, new_metric = eval_fn()
            loss_delta = new_loss - base_loss
            metric_delta = new_metric - base_metric
            if loss_delta <= max_loss_increase and metric_delta >= -max_metric_drop:
                best_frac_snap = {id(layer): layer.bit_widths.detach().clone() for layer in iter_progressive_layers(model)}
                best_pruned = k
                best_loss_delta = loss_delta
                best_bits_after = self.snapshot_stats(model).avg_bits
            else:
                break

        if best_frac_snap is not None:
            for layer in iter_progressive_layers(model):
                layer.bit_widths.copy_(best_frac_snap[id(layer)])
                if layer.granularity == "neuron":
                    layer.reallocate_blocks()
        else:
            for layer in iter_progressive_layers(model):
                layer.bit_widths.copy_(snap_orig[id(layer)])
                if layer.granularity == "neuron":
                    layer.reallocate_blocks()

        model.train(was_training)
        return {
            "num_pruned": best_pruned,
            "bits_before": bits_before,
            "bits_after": best_bits_after,
            "loss_delta": best_loss_delta,
        }

    def step_with_verification(
        self,
        model: nn.Module,
        optimizer: torch.optim.Optimizer,
        batch_step_fn: Callable[[], Tuple[torch.Tensor, float]],
        verify_eval_fn: Callable[[], Tuple[torch.Tensor, float]] | None = None,
    ) -> StepReport:
        """Run one training step, promote oscillating units, reallocate blocks, and re-verify."""
        cfg = self.config

        optimizer.zero_grad(set_to_none=True)
        loss, metric = batch_step_fn()
        loss.backward()
        if cfg.grad_clip_norm is not None:
            torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip_norm)
        self._update_salience(model)
        optimizer.step()

        initial_loss = float(loss.detach().item())
        initial_metric = float(metric)
        prev_loss = initial_loss
        final_loss = initial_loss
        final_metric = initial_metric

        old_bits_snap = None
        avg_bits_before = 0.0
        if cfg.enable_rollback_penalty:
            old_bits_snap = {
                id(layer): layer.bit_widths.detach().clone()
                for layer in iter_progressive_layers(model)
            }
            avg_bits_before = self.snapshot_stats(model).avg_bits

        stats, active_verify_masks = self.observe_and_promote(model)
        total_promoted = stats.num_promoted
        total_rollbacks = 0
        total_reallocations = stats.num_reallocations
        oscillating_after = stats.num_oscillating
        verify_iters = 0

        if cfg.enable_rollback_penalty and stats.num_promoted > 0 and old_bits_snap is not None:
            new_bits_snap = {
                id(layer): layer.bit_widths.detach().clone()
                for layer in iter_progressive_layers(model)
                if active_verify_masks.get(id(layer)) is not None and active_verify_masks[id(layer)].any()
            }
            eval_fn = verify_eval_fn if verify_eval_fn is not None else batch_step_fn
            keep, pre_loss, pre_metric = self._should_keep_promotion(
                model, eval_fn, old_bits_snap, avg_bits_before, new_bits_snap, stats
            )
            if not keep:
                reverted = self._rollback_promotions(model, old_bits_snap, active_verify_masks)
                total_rollbacks += reverted
                total_promoted -= reverted
                stats = self.snapshot_stats(model)
                oscillating_after = 0
                return StepReport(
                    initial_loss=initial_loss,
                    final_loss=pre_loss,
                    initial_metric=initial_metric,
                    final_metric=pre_metric,
                    verify_iters=1,
                    total_promoted=max(0, total_promoted),
                    total_rollbacks=total_rollbacks,
                    total_reallocations=total_reallocations,
                    oscillating_after=oscillating_after,
                    avg_bits=stats.avg_bits,
                    bit_counts=stats.bit_counts,
                    metric_improved=False,
                )

        while verify_iters < cfg.max_verify_iters and stats.num_promoted > 0:
            optimizer.zero_grad(set_to_none=True)
            loss_v, metric_v = batch_step_fn()
            loss_v.backward()
            if cfg.grad_clip_norm is not None:
                torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip_norm)
            self._update_salience(model)
            optimizer.step()
            verify_iters += 1

            final_loss = float(loss_v.detach().item())
            final_metric = float(metric_v)

            iter_old_bits = None
            iter_avg_bits_before = 0.0
            if cfg.enable_rollback_penalty and cfg.enforce_rollback_in_verify:
                iter_old_bits = {
                    id(layer): layer.bit_widths.detach().clone()
                    for layer in iter_progressive_layers(model)
                }
                iter_avg_bits_before = self.snapshot_stats(model).avg_bits

            stats, next_masks = self.observe_and_promote(model, verify_masks=active_verify_masks)
            total_reallocations += stats.num_reallocations

            if (
                cfg.enable_rollback_penalty
                and cfg.enforce_rollback_in_verify
                and stats.num_promoted > 0
                and iter_old_bits is not None
            ):
                iter_new_bits = {
                    id(layer): layer.bit_widths.detach().clone()
                    for layer in iter_progressive_layers(model)
                    if next_masks.get(id(layer)) is not None and next_masks[id(layer)].any()
                }
                eval_fn_v = verify_eval_fn if verify_eval_fn is not None else batch_step_fn
                keep_v, _, _ = self._should_keep_promotion(
                    model, eval_fn_v, iter_old_bits, iter_avg_bits_before, iter_new_bits, stats
                )
                if not keep_v:
                    reverted_v = self._rollback_promotions(model, iter_old_bits, next_masks)
                    total_rollbacks += reverted_v
                    stats = self.snapshot_stats(model)
                    oscillating_after = 0
                    break

            active_verify_masks = {
                k: active_verify_masks[k] | next_masks[k] for k in next_masks
            }
            total_promoted += stats.num_promoted
            oscillating_after = stats.num_oscillating

            loss_delta = abs(final_loss - prev_loss)
            prev_loss = final_loss

            if stats.num_oscillating == 0:
                break
            target_met = cfg.target_metric is None or final_metric >= cfg.target_metric
            if loss_delta <= cfg.loss_improvement_tol and target_met:
                break

        return StepReport(
            initial_loss=initial_loss,
            final_loss=final_loss,
            initial_metric=initial_metric,
            final_metric=final_metric,
            verify_iters=verify_iters,
            total_promoted=max(0, total_promoted),
            total_rollbacks=total_rollbacks,
            total_reallocations=total_reallocations,
            oscillating_after=oscillating_after,
            avg_bits=stats.avg_bits,
            bit_counts=stats.bit_counts,
            metric_improved=(final_metric > initial_metric)
            or (final_loss < initial_loss - cfg.loss_improvement_tol),
        )


def _pack_bits_per_byte(values: torch.Tensor, bits_per_val: int) -> torch.Tensor:
    """Pack small unsigned integers (`bits_per_val` in {1, 2, 4}) cleanly into uint8."""
    per_byte = 8 // bits_per_val
    flat = values.reshape(-1).to(torch.uint8)
    rem = flat.numel() % per_byte
    if rem != 0:
        flat = F.pad(flat, (0, per_byte - rem))
    reshaped = flat.view(-1, per_byte)
    shifts = torch.arange(0, 8, bits_per_val, dtype=torch.uint8, device=flat.device)
    return (reshaped << shifts).sum(dim=-1).to(torch.uint8)


def _unpack_bits_per_byte(packed: torch.Tensor, total_elems: int, bits_per_val: int) -> torch.Tensor:
    per_byte = 8 // bits_per_val
    mask = (1 << bits_per_val) - 1
    shifts = torch.arange(0, 8, bits_per_val, dtype=torch.uint8, device=packed.device)
    expanded = (packed.to(torch.uint8).unsqueeze(-1) >> shifts) & mask
    return expanded.reshape(-1)[:total_elems]


def _pack_ternary_base3(values: torch.Tensor) -> torch.Tensor:
    """Pack ternary digits {0, 1, 2} cleanly 5-per-byte in base 3 (3^5 = 243 <= 255)."""
    flat = values.reshape(-1).to(torch.int16)
    rem = flat.numel() % 5
    if rem != 0:
        flat = F.pad(flat, (0, 5 - rem))
    weights = torch.tensor([1, 3, 9, 27, 81], dtype=torch.int16, device=flat.device)
    return (flat.view(-1, 5) * weights).sum(dim=-1).to(torch.uint8)


def _unpack_ternary_base3(packed: torch.Tensor, total_elems: int) -> torch.Tensor:
    pows = torch.tensor([1, 3, 9, 27, 81], dtype=torch.int16, device=packed.device)
    digits = (packed.to(torch.int16).unsqueeze(-1) // pows) % 3
    return digits.reshape(-1)[:total_elems]


@torch.no_grad()
def pack_quantized_state_dict(model: nn.Module, eps: float = 1e-8) -> dict[str, torch.Tensor]:
    """Export a quantized model into a compact sub-byte bit-packed state dict (safetensors-safe)."""
    packed_out: dict[str, torch.Tensor] = {
        "__odpe_packed_version__": torch.tensor([1], dtype=torch.int8),
    }
    quant_layers: dict[str, ProgressiveLinear] = {
        name: mod
        for name, mod in model.named_modules()
        if isinstance(mod, ProgressiveLinear) and mod.use_quantization
    }

    for key, val in model.state_dict().items():
        # Skip non-quantized weights belonging to quantized ProgressiveLinear layers (we bit-pack them below).
        layer_match = None
        for lname in quant_layers:
            if key.startswith(f"{lname}."):
                layer_match = (lname, key[len(lname) + 1 :])
                break
        if layer_match is not None:
            lname, attr = layer_match
            if attr in ("weight", "block_perm", "block_inv_perm"):
                continue
            packed_out[key] = val.detach().cpu().contiguous()
        else:
            t_cpu = val.detach().cpu().contiguous()
            if t_cpu.ndim >= 2 and "emb" in key and t_cpu.is_floating_point():
                t_cpu = t_cpu.half()
            packed_out[key] = t_cpu

    for lname, layer in quant_layers.items():
        w = layer.weight.detach().cpu().float()
        bw = layer.bit_widths.detach().cpu()
        tenths = bool(getattr(layer, "precision_tenths", False))
        gsize = int(getattr(layer, "group_size", 0))
        in_dim = int(w.shape[-1])
        eff_g = effective_group_size(in_dim, gsize) if w.ndim >= 2 else 0
        codes = torch.unique(bw).tolist()

        for c_raw in codes:
            c = int(c_raw)
            eff = effective_bits_for_code(c, precision_tenths=tenths)
            if layer.granularity == "neuron":
                rows_idx = (bw == c).nonzero(as_tuple=False).squeeze(-1)
                w_sub = w[rows_idx]
            else:
                w_sub = w
            n_rows = int(w_sub.shape[0])
            if eff_g > 0:
                w_g = w_sub.reshape(n_rows, in_dim // eff_g, eff_g)
                rdims: Tuple[int, ...] = (-1,)
            else:
                w_g = w_sub
                rdims = (1,)

            prefix = f"{lname}.__q_{c}__"
            if eff >= 32.0:
                packed_out[f"{prefix}fp32"] = w_sub.contiguous()
            elif abs(eff - 1.0) < 1e-6:
                scale = w_g.abs().mean(dim=rdims, keepdim=True).clamp_min(eps).half()
                signs = (w_g >= 0).to(torch.uint8)
                packed_out[f"{prefix}data"] = _pack_bits_per_byte(signs, 1).contiguous()
                packed_out[f"{prefix}scale"] = scale.contiguous()
            elif eff < 1.8:
                scale = w_g.abs().mean(dim=rdims, keepdim=True).clamp_min(eps).half()
                trits = (torch.clamp(torch.round(w_g / scale.float()), -1.0, 1.0) + 1.0).to(torch.uint8)
                packed_out[f"{prefix}data"] = _pack_ternary_base3(trits).contiguous()
                packed_out[f"{prefix}scale"] = scale.contiguous()
            elif abs(eff - 2.0) < 1e-6:
                abs_max = w_g.abs().amax(dim=rdims, keepdim=True).clamp_min(eps).half()
                step = abs_max.float() / 1.5
                q_idx = (torch.clamp(torch.round(w_g / step - 0.5), -2.0, 1.0) + 2.0).to(torch.uint8)
                packed_out[f"{prefix}data"] = _pack_bits_per_byte(q_idx, 2).contiguous()
                packed_out[f"{prefix}scale"] = abs_max.contiguous()
            elif abs(eff - 4.0) < 1e-6:
                abs_max = w_g.abs().amax(dim=rdims, keepdim=True).clamp_min(eps).half()
                step = abs_max.float() / 7.0
                q_idx = (torch.clamp(torch.round(w_g / step), -7.0, 7.0) + 7.0).to(torch.uint8)
                packed_out[f"{prefix}data"] = _pack_bits_per_byte(q_idx, 4).contiguous()
                packed_out[f"{prefix}scale"] = abs_max.contiguous()
            elif abs(eff - 8.0) < 1e-6:
                abs_max = w_g.abs().amax(dim=rdims, keepdim=True).clamp_min(eps).half()
                step = abs_max.float() / 127.0
                q_i8 = torch.clamp(torch.round(w_g / step), -127.0, 127.0).to(torch.int8)
                packed_out[f"{prefix}data"] = q_i8.contiguous()
                packed_out[f"{prefix}scale"] = abs_max.contiguous()
            else:
                packed_out[f"{prefix}fp16"] = w_sub.half().contiguous()

    return packed_out


@torch.no_grad()
def unpack_quantized_state_dict(model: nn.Module, packed_state: dict[str, torch.Tensor]) -> None:
    """Load a bit-packed ODPE state dict into `model`, baking quantized values + tier scales."""
    direct_state = {}
    for k, v in packed_state.items():
        if k == "__odpe_packed_version__" or ".__q_" in k:
            continue
        if v.is_floating_point() and k in model.state_dict():
            direct_state[k] = v.to(model.state_dict()[k].dtype)
        else:
            direct_state[k] = v
    model.load_state_dict(direct_state, strict=False)

    for lname, layer in model.named_modules():
        if not (isinstance(layer, ProgressiveLinear) and layer.use_quantization):
            continue
        dev = layer.weight.device
        dtype = layer.weight.dtype
        bw = layer.bit_widths.detach()
        tenths = bool(getattr(layer, "precision_tenths", False))
        gsize = int(getattr(layer, "group_size", 0))
        in_dim = int(layer.weight.shape[-1])
        eff_g = effective_group_size(in_dim, gsize) if layer.weight.ndim >= 2 else 0
        codes = torch.unique(bw).tolist()
        recon_w = torch.zeros_like(layer.weight, dtype=torch.float32, device="cpu")

        for c_raw in codes:
            c = int(c_raw)
            eff = effective_bits_for_code(c, precision_tenths=tenths)
            rows_idx = (bw.cpu() == c).nonzero(as_tuple=False).squeeze(-1)
            n_rows = int(rows_idx.numel())
            total_elems = n_rows * in_dim
            g_shape = (n_rows, in_dim // eff_g, eff_g) if eff_g > 0 else (n_rows, in_dim)
            prefix = f"{lname}.__q_{c}__"
            tier_scale = float(layer._tier_scale(c))

            if eff >= 32.0:
                w_sub = packed_state[f"{prefix}fp32"].float()
            elif abs(eff - 1.0) < 1e-6:
                scale = packed_state[f"{prefix}scale"].float()
                bits = _unpack_bits_per_byte(packed_state[f"{prefix}data"], total_elems, 1).float()
                signs = torch.where(bits > 0.5, 1.0, -1.0).view(g_shape)
                w_sub = (signs * scale).reshape(n_rows, in_dim) * tier_scale
            elif eff < 1.8:
                scale = packed_state[f"{prefix}scale"].float()
                trits = _unpack_ternary_base3(packed_state[f"{prefix}data"], total_elems).float() - 1.0
                w_sub = (trits.view(g_shape) * scale).reshape(n_rows, in_dim) * tier_scale
            elif abs(eff - 2.0) < 1e-6:
                abs_max = packed_state[f"{prefix}scale"].float()
                q_idx = _unpack_bits_per_byte(packed_state[f"{prefix}data"], total_elems, 2).float()
                w_sub = ((q_idx.view(g_shape) - 1.5) * (abs_max / 1.5)).reshape(n_rows, in_dim) * tier_scale
            elif abs(eff - 4.0) < 1e-6:
                abs_max = packed_state[f"{prefix}scale"].float()
                q_idx = _unpack_bits_per_byte(packed_state[f"{prefix}data"], total_elems, 4).float()
                w_sub = ((q_idx.view(g_shape) - 7.0) * (abs_max / 7.0)).reshape(n_rows, in_dim) * tier_scale
            elif abs(eff - 8.0) < 1e-6:
                abs_max = packed_state[f"{prefix}scale"].float()
                q_i8 = packed_state[f"{prefix}data"].float().view(g_shape)
                w_sub = (q_i8 * (abs_max / 127.0)).reshape(n_rows, in_dim) * tier_scale
            else:
                w_sub = packed_state[f"{prefix}fp16"].float() * tier_scale

            recon_w[rows_idx] = w_sub

        layer.weight.copy_(recon_w.to(device=dev, dtype=dtype))
        layer.prequantized = True
        if layer.granularity == "neuron":
            layer.reallocate_blocks()