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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
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
# BitState / HSDR

## Finite-State Population Reduction and Dependency-Breaking Log-Domain Reduction for Low-Bit LLM Inference

**Implementation Proposal v0.5**  
**Primary target:** low-bit LLM GEMV / small-batch decode  
**Reference/validation numeric path:** LNS8 → finite-state population reduction → wide integer/fixed-point → optional Q9.6 → LNS8  
**Optimized candidate path:** LNS8 → state-domain population reduction → relative fractional-LNS → balanced LNS add/sub tree → LNS8

---

## 1. Purpose

BitState is a compute model for low-bit inference that moves the reduction problem into a finite **state domain** before performing unavoidable numerical reduction.

The core idea is:

> **Move the reduction into the state domain to break the long numerical reduction dependency.** Form wide state sets, count equivalent states in parallel, and let only the compressed state population enter the remaining arithmetic tree.

Delaying numerical materialization remains important, but it is now a consequence of the stronger objective: replace a long dependent arithmetic chain with parallel set formation / POPCOUNT and a much smaller final reduction.

The main pipeline is below. v0.5 explicitly adds **direct reduction from final product states into eight phase integer accumulators** as the simplest correctness and implementation baseline. A full POPCOUNT histogram remains a separate candidate for stronger dependency breaking.

```text
packed low-bit values
    ↓
packed LNS product-state ADD / sign XOR
    ↓
final product state = S1 | E4 | L3
    ↓
State Tile (CPU Tile64 / GPU Tile32, etc.)
    ↓
phase routing / state-set construction
    ├───────────────────────────────────────────────┐
    │                                               │
    │ Direct 8-phase dyadic path                    │ Population / Pure-LNS path
    ↓                                               ↓
A[L3] += sign × (1 << E4)                  signed state populations
    ↓                                               ↓
8 integer accumulators                     dyadic histogram or fractional-LNS
    ↓                                               ↓
8 phase coefficients + short final sum     balanced κ± add/sub tree
    ↓                                               ↓
optional Q9.6 / LNS8 boundary               LNS8 boundary
```

The optimized path is allowed to remain in logarithmic coordinates from product generation through final reduction. No FP/linear materialization is required inside the GEMV reduction itself.

The primary optimization target is not peak FLOPS. It is the whole decode pipeline:

```text
memory load + low-bit decode + product generation + reduction + re-encoding
```

---

### 1.1 Design premise — rotation-aware quantization makes narrower numeric domains practical

One reason BitState can seriously consider relatively narrow internal formats such as LNS8 and Q9.6 is the increasing use of **rotation-aware quantization** in low-bit LLMs. Work such as QuaRot and SpinQuant illustrates the broader direction: WHT / Hadamard or learned rotations redistribute outliers and concentrated energy across dimensions before low-bit representation, reducing the need for every GEMM stage to preserve rare full-scale values with a conventional BF16/FP16-style dynamic range.

This is not a claim that full-scale dynamic range is unnecessary for every model. The important engineering change is that more models can be designed around the **measured post-rotation activation and weight distributions**, rather than requiring the inference kernel to reproduce the entire theoretical dynamic range of BF16/FP16 unconditionally.

Bonsai2 is a concrete example. Its public model documentation states that language-model weights are stored in a blockwise Hadamard-rotated basis and that the runtime applies the matching transform to activations. Low-bit coverage includes embeddings, attention projections, MLP projections, and the LM head. The MLX package also documents that ordinary loaders produce incorrect output if they omit the activation transform and the inverse embedding lookup.

For Bonsai2, rotation is therefore not merely an offline quantizer preprocessing step. It is a **numeric-basis contract between the checkpoint and the runtime**. The token embedding / token path participates in that contract, with the corresponding inverse transform required at the embedding-lookup boundary.

The multimodal path requires a distinction. Public packaging information shows configurations where the vision tower itself remains unrotated and unquantized in FP16. However, once projected visual tokens enter the language model, they must follow the language model's rotation-aware activation path. Thus the **multimodal interface is not independent of the language-side basis contract**, even though the vision tower itself is not Hadamard-rotated.

The public Bonsai2 materials do not fully disclose the complete quantization-aware training recipe, so this document does not claim a specific training procedure that is not documented. What is clear is that the distributed checkpoint is rotation-native and requires matching activation transforms and inverse embedding handling at runtime. This is sufficient to treat **rotation-aware low-bit model/runtime design** as an important premise when evaluating whether LNS8 / Q9.6 can use a narrower measured dynamic range.

A BitState implementation MUST measure, per target model:

- activation absolute maxima before and after WHT / rotation;
- activation absolute maxima before and after RMSNorm, and before and after learned gain `gamma`;
- RMS and percentile distributions;
- required dynamic range by layer;
- LNS8 saturation / underflow rates;
- Q9.6 saturation rates; and
- end-to-end quality with the rotation path enabled.

In other words, BitState does **not** discard full-scale support merely because a rotation exists. It uses the measured post-rotation distribution to preserve only the range that the model actually requires.

References:

- https://arxiv.org/abs/2404.00456  (QuaRot)
- https://arxiv.org/abs/2405.16406  (SpinQuant)
- https://huggingface.co/prism-ml/Ternary-Bonsai-2-27B-gguf
- https://huggingface.co/prism-ml/Ternary-Bonsai-2-27B-mlx-2bit
- https://github.com/PrismML-Eng/Bonsai-demo

### 1.2 Design premise — widespread RMSNorm makes pre-GEMM absolute activation range easier to bound

Separate from rotation-aware quantization, **RMSNorm** is now widely used in modern decoder-only LLM families. Qwen3.5, Gemma 3, Llama 4, and Mistral-family implementations all use RMS normalization layers. BitState should therefore treat not only post-WHT / post-rotation activations, but also the **post-RMSNorm activation domain** as an important integration point for LNS8.

RMSNorm does not clip individual outliers. It rescales the entire hidden vector for each token by a common root-mean-square factor. Before the learned gain is applied, let the normalized vector be `u`:

```text
u_i = x_i / sqrt(mean_j(x_j^2) + eps)
```

For hidden dimension `d`:

```text
sum_i(u_i^2) <= d
```

and therefore every coordinate has the theoretical bound:

```text
|u_i| <= sqrt(d)
```

This does **not** mean that channel-wise outliers disappear. Energy can still concentrate strongly in one coordinate. What changes is the absolute numeric scale: values that may have reached tens or hundreds of thousands before normalization are forced back into a finite domain determined by the hidden dimension. A subsequent WHT / Hadamard rotation can then redistribute the remaining channel-wise concentration across dimensions. From the BitState perspective, RMSNorm and WHT are therefore complementary rather than competing mechanisms.

The current reference LNS8 format, `S1E4L3 / base74`, has maximum magnitude:

```text
x_max = 2^((127 - 74)/8) ~= 98.7015
```

If LNS8 encoding is placed directly after RMS normalization and before learned `gamma`, the theoretical one-axis worst case fits without saturation for approximately:

```text
d <= x_max^2 ~= 9741.98
```

Representative hidden sizes:

```text
hidden 5120  -> sqrt(d) ~= 71.55
hidden 8192  -> sqrt(d) ~= 90.51
hidden 9216  -> sqrt(d) = 96.00
hidden 12288 -> sqrt(d) ~= 110.85
```

Thus, for hidden sizes in the 5120-9216 range, the current base74 / S1E4L3 range of about +/-98.7 can **cover the RMSNorm theoretical coordinate bound itself**. At hidden size 12288, only the mathematical worst-case coordinate exceeds the range, by roughly 12%. The implementation can then choose, based on measurement, among:

1. saturating / clamping only the rare overflow to the LNS8 maximum;
2. shifting a tensor/model-level system exponent offset slightly upward (for example, `code 72 = 1.0` gives a maximum of about 117.38); or
3. using a future wide-range profile / escape path only for tensors that empirically require it.

Real RMSNorm layers normally apply a learned gain `gamma_i` after normalization, so their final output is not strictly bounded by `sqrt(d)`. BitState must therefore choose per model/backend whether to **encode after RMS normalization but before `gamma`, fold `gamma` into downstream linear weights where valid, or size the LNS8 range from the measured post-`gamma` distribution**.

The purpose of this premise is not to claim that RMSNorm eliminates the need for full-scale support in every model. The engineering hypothesis is narrower: **for activation paths whose absolute range is already controlled by RMSNorm and/or whose channel concentration is reduced by WHT / rotation, preserving the finer 8-states-per-octave S1E4L3 grid may be preferable to sacrificing precision across all elements merely to preserve rare theoretical extremes**.

Additional references:

- https://arxiv.org/abs/1910.07467  (RMSNorm)
- https://huggingface.co/docs/transformers/main/en/model_doc/qwen3_5
- https://huggingface.co/docs/transformers/model_doc/gemma3
- https://huggingface.co/docs/transformers/model_doc/llama4
- https://huggingface.co/docs/transformers/model_doc/mistral

---

## 2. BitState and HSDR

### BitState

BitState treats a low-bit numerical representation as a small finite state space that can be manipulated using Boolean and integer operations.

Typical primitives:

- packed integer ADD
- XOR
- AND / OR / NOT
- SHIFT
- bit transpose / ballot / mask generation
- POPCOUNT
- small integer reduction
- small LUT

### HSDR — Hierarchical State-Domain Reduction

HSDR reduces many element-wise numerical operations through progressively smaller state domains **and uses that domain change to cut the serial reduction dependency**.

Typical hierarchy:

```text
individual elements
    ↓
finite-state IDs
    ↓
wide state sets / masks
    ↓
parallel population counts
    ↓
small set of state-domain aggregates
    ├─ reference: integer/fixed-point realization
    └─ candidate: fractional-LNS reduction tree
```

The essential idea is:

> **State-domain reduction is a dependency-breaking transform.** Count equivalent states in parallel first; only the compressed state set is allowed to enter a dependent arithmetic reduction.

The objective is therefore not merely fewer values. It is a shallower dependency graph that maps naturally to scalar bit operations, SIMD masks, GPU ballots, and hardware population counters.

---

## 3. LNS8 reference format

The current LNS8 magnitude grid is:

```text
|x| = 2^((k - 74) / 8)
```

where:

- `k = 1..127` : non-zero magnitude code
- `k = 0` : exact zero
- sign is stored separately
- 8 codes = exactly ×2
- code 74 = 1.0

For a non-zero 7-bit magnitude code:

```text
phase  = k & 0x07     // lower 3 bits, intra-octave index 0..7
octave = k >> 3       // upper 4 bits, coarse exponent / octave index 0..15
```

Terminology used in this document:

- **phase** = lower 3 bits = intra-octave position
- **octave** = upper 4 bits = coarse exponent
- **state** = the complete finite-state code, optionally including sign

Because 74 = 9×8 + 2:

```text
2^((k - 74)/8)
= 2^(octave - 9) × 2^((phase - 2)/8)
```

This factorization is useful only after population counting. It does not constrain how the histogram itself must be generated.

### 3.1 Logical S1E4L3 decomposition — exponent × fractional-log field

The same 8-bit representation can be read not only as a flat 7-bit magnitude code, but also as an FP-like field structure. For non-zero states, the logical decomposition is:

```text
bit 7          bits 6..3          bits 2..0
+------+-------------------+-------------------+
|  S1  |        E4         |        L3         |
+------+-------------------+-------------------+
| sign | octave / exponent | fractional-log    |
|      |                   | phase             |
+------+-------------------+-------------------+
```

Let `E = octave`, `L = phase`, and `s ∈ {-1,+1}`. A non-zero value is then

```text
x = s × 2^(E - 9) × 2^((L - 2)/8)
  = s × 2^(E - 9 + (L - 2)/8)
```

The fields therefore have the following roles:

- **S1** — sign. In population reduction it maps naturally to positive / negative populations.
- **E4** — a 4-bit coarse binary exponent / octave. `E + 1` is exactly `×2`, so this axis maps to SHIFT / dyadic scaling during materialization.
- **L3** — a 3-bit fractional logarithmic field. It divides one octave into eight states representing `2^((L-2)/8)`.

For intuition, L3 may be described as a **logarithmic mantissa**, but it is not an IEEE-style linear mantissa / significand. Mathematically it is a **fractional exponent**. To avoid ambiguity, this document uses **fractional-log field** or the existing term **phase** as the formal name.

Compared with an ordinary E4M3-like structure:

```text
ordinary FP-like E4M3:
    x ~ sign × 2^E × (linear significand from M3)

BitState LNS8 logical S1E4L3:
    x = sign × 2^E × 2^(fractional-log field)
        (with the base74 bias terms shown above)
```

Thus the visible layout is `S1 | E4 | L3`, but the lower field remains part of the logarithmic coordinate. LNS multiplication therefore requires no linear mantissa multiplier. In full-code form it remains

```text
k_product = k_a + k_b - 74
s_product = s_a XOR s_b
```

In field form, carry / borrow from the `L3` sum flows directly into `E4`. For non-zero inputs:

```text
t   = L_a + L_b - 2
L_p = t mod 8
E_p = E_a + E_b - 9 + floor(t / 8)
```

which is exactly equivalent to `k_product = k_a + k_b - 74`. Fast implementations must keep a wider signed intermediate rather than saturating prematurely to the final storage range.

### 3.2 2-D state-space view

From the HSDR perspective, the non-zero magnitude states can be treated not only as a flat set of 127 values, but conceptually as the product of three small axes:

```text
vertical axis   : E4 = 16 coarse exponent / power-of-two scale positions
horizontal axis : L3 = 8 intra-octave logarithmic positions
sign axis       : S1 = positive / negative
```

For intuition, the **horizontal direction can be viewed as an `S1 + L3` 4-bit signed intra-octave LNS slice, while the vertical direction is an E4M0-like pure power-of-two scale axis**. This is an algorithmic / visualization decomposition, not a claim that the format is IEEE E4M0 or an independent 4-bit LNS storage type. `k=0` remains the separately reserved exact-zero state.

This view maps directly onto the later HSDR operations:

```text
S1  -> sign mask / signed population
L3  -> 8 phase buckets / 8 fixed fractional-log coefficients
E4  -> exact power-of-two position / integer SHIFT axis
```

Accordingly, `H[phase][octave]` is not merely a convenient 2-D histogram. It is the direct state-domain expansion of the logical S1E4L3 fields, with sign folded into signed counts. BitState exploits this product structure by mapping sign, fractional-log phase, and power-of-two scale onto separate cheap primitives before final reduction.

---

## 4. Stage A — Product-state generation

LNS multiplication becomes exponent addition.

Conceptually:

```text
product_exp = weight_exp + activation_exp + bias_adjust
product_sign = weight_sign XOR activation_sign
```

The fast path should use packed integer arithmetic wherever the dynamic range permits it.

Candidate implementations:

- packed INT8 ADD
- packed INT16 reference path
- SWAR lane arithmetic
- SIMD byte arithmetic
- SIMT lane arithmetic

### Product-state completion rule

Before decomposing into `L3` / `E4`, building masks, or bit-slicing, apply **all log-domain offsets that belong to the final product state for that variant**. Weight exponent, preconverted scale offset, and bias adjustment must be included first if they change the routed product code.

```text
activation LNS code
+ weight / scale / bias log offsets
        ↓
final product magnitude code
        ↓
L3 / E4 decomposition, bit transpose, phase routing
```

A mathematically factorable shared group scale may instead be kept outside as `d × Σ(...)`, but that is a **separate factorized variant**. Do not mix “scale included in product-state routing” and “scale factored after reduction” in the same implementation description.

### Range rule

The first correctness implementation MUST use a wider intermediate type than the final LNS code.

Measure:

- minimum product exponent
- maximum product exponent
- overflow frequency
- underflow frequency

Only after the observed range is understood should packed INT8 saturation/wrapping rules be selected.

---

## 5. Stage B — State Tile

Process multiple product states as a tile.

Recommended initial tile sizes:

```text
Tile32
Tile64
Tile128
```

CPU reference target:

- Tile64, because a state-membership mask maps naturally to one 64-bit integer.

Bonsai2 reference target:

- Tile128, because one ternary weight scale group already contains 128 weights.

A State Tile is a logical grouping. The backend is free to keep the values in registers, vector lanes, warp lanes, or bitsets.

---

## 6. Stage C — S1E4L3 decomposition and direct 8-phase reduction

For each final product state:

```text
phase  = state & 0x07     // L3, 0..7
octave = state >> 3       // E4, 0..15
sign   = product sign     // S1
```

The v0.5 correctness baseline does not require a persistent full histogram. Each product can be reduced directly into **eight signed integer phase accumulators**:

```text
payload = sign × (1 << octave)
A[phase] += payload
```

Equivalently:

```text
A[p] = Σ_{i: phase_i=p} sign_i × 2^(octave_i)
```

Final materialization is:

```text
F[p] = 2^((p - 2)/8)
S    = 2^-9 × Σ_{p=0..7} A[p] × F[p]
```

For quantized LNS8 states this decomposition is algebraically exact. It is equivalent to first building `H[phase][octave]` and then computing `Σ H[p][o] << o`.

### C1. GEMM / GEMV interpretation

For one output dot with `K=4096` or `K=5120`, all K product states ultimately feed only **A[0..7]**. Once those eight integers exist, only eight fixed phase coefficients and a short final sum remain. The dominant implementation question is therefore **K products → eight weighted phase accumulators**, not the final materialization.

### C2. Excel correctness reference

This path uses the procedure demonstrated in `LNS8_base74_8step_zone8_popcount_demo_JA_v0.8_bitslice128_validation.xlsx` (`Inputs_128` / `BitSlice128_一致確認`) as a correctness reference.

The workbook treats 128 inputs as `Tile64 × 2`, interprets each product as:

```text
S1 | E4 | L3
```

forms `±(1 << E4)`, routes by `L3`, and verifies that the eight integer accumulators reconstruct the same result as direct decoding.

### C3. Histogram / POPCOUNT remains a valid exact family

A full-state histogram remains a separate exact implementation family:

```text
H[phase][octave]
A[phase] = Σ_o H[phase][o] × 2^o
```

The direct 8-phase path fuses bucket creation with dyadic shift/add. The histogram path preserves state populations explicitly and is still useful for POPCOUNT-based dependency breaking and pure-LNS folding.

## 7. Stage D — Bit transpose / backend-equivalent routing-mask construction

For a CPU Tile64, fields of the final product states can be represented as 64-bit bitplanes:

```text
L0 L1 L2          // three L3 bitplanes
E0 E1 E2 E3       // four E4 bitplanes
BSIGN              // sign plane, 1 = negative
```

The same bit position refers to the same original lane across all planes.

### D1. Phase masks are intermediate selectors

Boolean decode of `L2,L1,L0` produces a 64-bit mask `M[p]` whose set bits are exactly the lanes belonging to phase `p`.

Example:

```text
M[101] = L2 & ~L1 & L0
```

This is an **intermediate routing/selector mask**, not a final population or numerical result. It may be generated on demand and discarded after accumulation. All eight masks need not be stored persistently.

The 3-to-8 decoder should share intermediate 2-bit groups instead of performing eight fully independent 3-bit comparisons.

### D2. Sign handling in bit form

A bitset cannot directly represent `-1` population. For exact signed counts:

```text
Hpos = POPCOUNT(M & ~BSIGN)
Hneg = POPCOUNT(M &  BSIGN)
Hsigned = Hpos - Hneg
```

or equivalently:

```text
N     = POPCOUNT(M)
Nneg  = POPCOUNT(M & BSIGN)
Hsigned = N - 2*Nneg
```

This is exactly the same population as the Excel `(+ POPCOUNT) - (- POPCOUNT)` construction. Algebraic XOR identities also exist, but they temporarily count negative lanes outside the local bucket; the table-local formulas above are preferred for the reference implementation.

### D3. Phase POPCOUNT alone is insufficient for direct 8-accumulator reduction

`POPCOUNT(M[p])` loses E4 weighting. Within one phase, `E=3` and `E=11` contribute different magnitudes, so the direct path must still perform the weighted reduction:

```text
A[p] += ±(1 << E)
```

Bit transpose and phase masks are intermediate wide-routing representations. POPCOUNT is optional, not mandatory, for the direct path.

Backend equivalents:

- scalar 64-bit CPU: `uint64_t` bitplanes and masks
- AVX2 / AVX-512: vector mask extraction, mask logic, optional vector/scalar popcount
- ARM NEON/SVE: predicates / bit operations / count
- CUDA: 32-lane ballot / lane predicates / subgroup reduction
- FPGA/ASIC: 3-to-8 decoder + sign + shifted-payload routing

The first theoretical consistency targets are CPU Tile64 and GPU Tile32. After exact equivalence is established, larger bit arrays and wider SIMD can be explored.

## 8. Stage E — Two exact reduction families

v0.5 separates **direct 8-phase routed accumulation** from the **state POPCOUNT histogram**. Both are exact LNS8 reduction families.

### E1. Direct 8-phase routed accumulation — preferred correctness baseline

For each product state:

```text
p = L3
e = E4
v = (sign ? -1 : +1) × (1 << e)
A[p] += v
```

After K products, the numerical state has been reduced to eight signed integers `A[0..7]`, independent of whether K is 128, 4096, or 5120.

POPCOUNT is not required by this path. CPU/GPU PoCs should compare phase masks, masked/grouped integer reduction, SWAR, SIMD, ballot, and related methods without falling back to K scalar dependent adds.

### E2. State POPCOUNT histogram — dependency-breaking candidate

For state `s`:

```text
M[s] = (state == s)
H[s] = POPCOUNT(M[s])
```

For signed values:

```text
Hpos[s] = POPCOUNT(M[s] & ~negative_mask)
Hneg[s] = POPCOUNT(M[s] &  negative_mask)
Hsigned[s] = Hpos[s] - Hneg[s]
```

or:

```text
N      = POPCOUNT(M[s])
Nneg   = POPCOUNT(M[s] & negative_mask)
Hsigned[s] = N - 2*Nneg
```

The histogram path can collapse identical states before dependent arithmetic, and remains the input for the pure fractional-LNS candidate.

### E3. Exact equivalence

With the 2-D histogram:

```text
H[p][o] = signed population of phase p, octave o
A[p]    = Σ_o H[p][o] × 2^o
```

The result must match E1 bit-exactly. The PoC treats this equivalence as a correctness invariant.

## 9. Intermediate-state organization

If a histogram is kept explicitly, use either:

### Full-state form

```text
H[k]       // k = 1..127, plus optional zero/sign handling
```

### 2-D LNS form

```text
H[phase][octave]   // 8 × 16 signed counts
```

The direct 8-phase path does not persist this histogram. It folds immediately into:

```text
A[phase] = Σ sign × 2^octave
```

so only eight integer states remain.

Therefore v0.5 distinguishes:

```text
full-state / 2-D histogram   = optional intermediate state representation
A[0..7]                      = direct dyadic reduction state
```

The histogram is useful when state populations themselves matter, especially for pure-LNS population folding. `A[0..7]` is the shortest path to the dyadic materializer.

## 10. Stage F — Eight-phase finalization and pure-LNS alternative

In the direct path, `A[p]` already exists at the end of Stage E. In the histogram path, the same `A[p]` is reconstructed as follows.

For each phase `p`:

```text
R[p] = Σ_o H[p][o] × 2^o
```

This is integer shift/add only:

```text
R[p] = H[p][0]
     + (H[p][1]  << 1)
     + (H[p][2]  << 2)
     + ...
     + (H[p][15] << 15)
```

The 8 phase reductions are independent.

Alternative reduction styles to benchmark:

- direct shift/add
- balanced add tree
- Horner form
- SIMD: one lane per phase

### Phase coefficients

Define:

```text
F[p] = 2^((p - 2)/8)
```

Then the unscaled numerical sum is:

```text
S = 2^-9 × Σ_p R[p] × F[p]
```

Only 8 non-power-of-two phase coefficients exist.

This eight-phase finalization is the preferred dyadic reference materializer. The direct path may reach `A[0..7]` without a POPCOUNT histogram; the histogram path reaches the same eight values via POPCOUNT + integer shift/add. In either case, only at most eight non-power-of-two phase coefficients remain at the end.

---

### F1. Dependency-breaking role of POPCOUNT

For a 128-element tile, a conventional accumulator exposes a long producer/consumer chain: the next arithmetic add depends on the previous partial sum. BitState first transforms the problem into independent state predicates and population counts.

```text
many product lanes
    ↓
independent state membership masks
    ↓
independent POPCOUNTs / signed populations
    ↓
small state set
    ↓
short balanced reduction tree
```

The important performance hypothesis is therefore **not** simply that POPCOUNT is fast. The hypothesis is that state-domain population reduction removes most of the serial arithmetic dependency before the final reduction begins.

The reference shift/add materializer above remains useful because it is algebraically simple and gives a strong correctness baseline. However, it is no longer the only post-POPCOUNT path.

### F2. Relative fractional-LNS path — no linear materialization

For a non-zero LNS8 magnitude state `k`, define an internal logarithmic coordinate in **LNS8 code units**:

```text
lambda = k + fractional_code_offset
1.0 code unit = 1/8 octave
```

The stored LNS8 value has an integer `k`, but the internal reduction is allowed to retain fractional code bits, e.g. a signed fixed-point representation of the logarithmic coordinate. This is an internal accumulator format, not a new storage format.

After signed POPCOUNT, let `C[k]` be the signed population of identical state `k`. If `C[k] != 0`, all equal-magnitude contributions in that bucket can be collapsed before any pairwise numerical reduction:

```text
bucket_sign   = sign(C[k])
bucket_lambda = k + 8*log2(abs(C[k]))
```

`abs(C[k])` is bounded by the tile size, so for Tile128 the population term requires only a tiny `1..128 -> 8*log2(n)` LUT (or an equivalent integer implementation). This operation does **not** materialize a linear value.

For the base74 / 8-code grid, the eight phase tables `000..111` may be normalized around the eight top-octave anchors `120..127`; code 122 is the exact power-of-two anchor 64. Because an octave step is exactly +8 code units, moving a state between octave positions is an integer code offset. A convenient identity is:

```text
k = 8*q + phase
  = (120 + phase) + 8*(q - 15)
```

Thus phase-specific entries can be brought to a common relative fractional-LNS coordinate using only known integer octave offsets plus a small fractional correction.

### F3. LNS add/sub primitive

For two positive-magnitude fractional-LNS states with coordinates `a >= b`, let `d = a-b` in LNS8 code units.

Same sign:

```text
out = a + kappa_plus(d)
kappa_plus(d) = 8*log2(1 + 2^(-d/8))
```

Opposite sign, `d > 0`:

```text
out = a + kappa_minus(d)
kappa_minus(d) = 8*log2(1 - 2^(-d/8))
```

The output sign is the sign of the larger magnitude. Equal-magnitude opposite-sign inputs cancel to exact zero.

Runtime does not require general `log2()` or `pow()`. `kappa_plus` and `kappa_minus` are small correction LUTs indexed by a quantized difference in the chosen fractional-code format. The existing integer-code threshold adder is the coarse rounded special case; the pure-LNS path keeps additional fractional bits so that repeated additions do not round to 8-bit LNS after every step.

### F4. Balanced reduction instead of a serial accumulator

The population buckets should be reduced as a balanced tree, not a left-to-right accumulator. For the final eight phase aggregates:

```text
8 states → 4 LNS add/sub operations in parallel
         → 2 LNS add/sub operations in parallel
         → 1 LNS add/sub operation
```

The final eight-state dependency depth is therefore three add/sub stages. If each phase has multiple non-zero octave buckets, the same balanced primitive is used inside the phase. Sparse-state masks reduce the number of leaves further.

Finite internal LUT precision makes reduction order an error source, so PoC correctness MUST compare multiple internal fractional precisions and tree orders against an FP64 reference.

### F5. Shared scale without leaving the log domain

For a positive shared group scale `d_scale`, applying the scale after state reduction can remain logarithmic:

```text
lambda_scaled = lambda_sum + 8*log2(d_scale)
```

The scale offset may be precomputed by the converter or cached once per quantization group. This replaces the final linear multiply in the pure-LNS path with another logarithmic offset ADD.

### F6. Keep the two paths conceptually separate

There are now two post-POPCOUNT implementations to benchmark:

1. **Dyadic reference path:** signed populations → integer shift/add → fixed-point/Q9.6 → optional LNS8 re-encode.
2. **Pure-LNS candidate path:** signed populations → population-log LUT → fractional-LNS add/sub tree → log-scale offset → final LNS8 rounding.

The first is an important correctness and performance baseline. The second tests the stronger hypothesis that the GEMV reduction can remain in state/log coordinates without ever constructing a linear numerical accumulator.

## 11. Fixed-point materialization and Q9.6 — reference / escape path

Do not round individual LNS states directly to Q9.6 before reduction.

Small states may individually be below one Q9.6 LSB but become significant when many occurrences are accumulated.

Use an internal fixed-point precision wider than Q9.6 for the phase-coefficient stage.

Recommended reference implementation:

```text
R[p]             : signed INT32/INT64
F_fixed[p]       : high-precision fixed coefficient, e.g. Q1.15 or Q2.14
phase_product[p] : widened integer multiply
SUM_internal     : INT64
```

Then round once into Q9.6:

```text
Q9.6_raw = rounded_shift(SUM_internal)
```

The exact internal coefficient format is a tuning parameter and must be selected from error measurements, not guessed.

---

## 12. Stage G — Q9.6 → LNS8

The default re-encoding path is:

```text
Q9.6
  ↓
zero test
  ↓
sign extraction
  ↓
absolute value
  ↓
MSB / leading-one detection
  ↓
normalization
  ↓
MSB + next 5 bits = 1.xxxxx  (6 significant binary bits)
  ↓
32-entry LUT
  ↓
LNS8 phase + possible octave carry
  ↓
compose LNS8 code
```

No general `log2()` is required.

The LUT MUST be generated by exhaustive nearest-LNS8 mapping over the Q9.6 input domain used by the implementation.

Also test:

- 5 significant bits
- 6 significant bits — default
- 7 significant bits

Measure disagreement against exact nearest-LNS8 conversion.

---

## 13. Q4_0 weight path

Q4_0 weight storage remains 4-bit packed.

Do not expand the model to 8-bit LNS8 weights in memory unless a benchmark shows a benefit.

Q4_0 coefficient values are:

```text
-8 -7 -6 -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5 +6 +7
```

A tiny LUT can map the absolute Q4 coefficient to an LNS8 exponent offset:

```text
|q| : 1  2  3  4  5  6  7  8
Δ   : 0  8 13 16 19 21 22 24    // nearest 1/8-octave approximation
```

Reference path:

```text
Q4 nibble
  ↓
small LUT
  ↓
weight LNS offset + sign
  ↓
packed exponent ADD with activation
  ↓
product state
```

Q4 block scale handling variants:

1. FP reference: reconstruct `q × d`, then encode to LNS8.
2. Preconverted log-scale: encode `d` once and add it as an exponent offset.
3. Converter-generated custom scale metadata.

Measure the additional quantization error of 2 and 3 against 1.

---

## 14. Ternary / Bonsai2 fast path

Ternary weight groups are especially natural for BitState.

### Rotation-aware integration point

The Bonsai2 fast path must treat the **activation domain after the matching Hadamard / sign transform** as part of its input contract. Primal-basis activations MUST NOT be fed directly into the ternary POPCOUNT path.

The token embedding lookup is also a boundary of the rotation-aware runtime contract and must preserve the required inverse transform. For multimodal input, the vision tower itself may remain unrotated, but once projected visual tokens enter the language model they must follow the same language-side basis contract.

The preferred BitState integration point is therefore one of:

1. encode activations into LNS8 / finite-state form after the WHT / sign transform; or
2. fuse the WHT / sign transform with state encoding to reduce intermediate floating-point materialization.

Option 2 is a performance optimization. The first correctness implementation should use option 1.

For a 128-weight group:

```text
w_i = d × t_i
t_i ∈ {-1, 0, +1}
```

The shared scale `d` can remain outside the 128-element population reduction:

```text
Σ_i w_i a_i
= d × Σ_i t_i a_i
```

Weight magnitude processing therefore collapses to Boolean selection:

```text
W_nonzero
W_negative
```

No per-weight magnitude multiplication is required.

### Signed population count

For activation magnitude state `s`:

```text
A_s = mask of activation lanes whose magnitude state == s
M   = A_s & W_nonzero
PNEG = activation_sign XOR W_negative

N    = POPCOUNT(M)
Nneg = POPCOUNT(M & PNEG)
Cs   = N - 2*Nneg
```

`Cs` is the signed population of activation state `s` after ternary weight selection.

The group scale is not applied until the 128-element state reduction is complete.

Two preferred flows must be tested.

Reference / validation flow:

```text
128 activations + ternary masks
    ↓
state-set intersection
    ↓
POPCOUNT signed histogram
    ↓
dyadic integer shift/add
    ↓
wide fixed-point / optional Q9.6
    ↓
apply shared group scale d
```

Pure-LNS flow:

```text
128 activations + ternary masks
    ↓
state-set intersection
    ↓
POPCOUNT signed histogram          ← dependency-breaking reduction
    ↓
non-zero population buckets
    ↓
population count -> fractional-LNS offset
    ↓
balanced signed LNS add/sub tree
    ↓
add shared scale as log-code offset
    ↓
final LNS8 rounding only at the boundary
```

The pure-LNS path remains a stronger v0.5 hypothesis: the inner GEMV reduction does not require FP, Q9.6, or another linear accumulator. The reference path remains mandatory for differential testing.

---

## 15. CPU implementation plan

### Reference 0 — scalar correctness

- explicitly decode each final product state
- execute `A[L3] += sign × (1 << E4)`
- compare against exact FP64 direct decode
- no performance goal

### Reference 1 — scalar histogram equivalence

- build `H[phase][octave]`
- compute `A[p] = Σ_o H[p][o] << o`
- require bit-exact equality with Reference 0 `A[0..7]`

### CPU PoC A — Tile64 bitslice direct 8-phase path

- 64 final product states
- extract / construct `L2,L1,L0,E3..E0,BSIGN` planes or equivalent masks
- 3-bit phase decoder to intermediate selector masks
- reduce `±(1<<E)` weighted contributions into eight phase accumulators
- 64 lanes → eight partial accumulators
- reproduce the Excel v0.8 128-input validation with two Tile64 blocks

### CPU PoC B — Tile64 signed-histogram path

- full-state or phase-local membership masks
- `Hpos/Hneg` or `N-2*Nneg`
- POPCNT64
- histogram → `A[0..7]`

### CPU PoC B2 — pure fractional-LNS reduction

- use signed POPCOUNT histogram as input
- fold non-zero populations with a tiny count-to-log LUT
- keep configurable fractional log coordinates
- balanced `kappa+ / kappa-` add/sub tree
- compare total cycles and dependency depth against the direct 8-phase dyadic path

### CPU PoC C — AVX2 / ordinary 64-bit CPU

Start with standard integer and bit primitives rather than assuming a large custom bit-array layout:

- packed byte ADD for LNS product generation
- 64-bit scalar bitplanes / masks
- AND / OR / XOR / NOT / SHIFT
- POPCNT64 where useful
- `pshufb` / vector mask extraction
- eight independent integer accumulators

### CPU PoC D — AVX-512 / wider bitsets

Evaluate only after Tile64 correctness is fixed:

- mask registers
- VPOPCNT
- wider state-set construction
- multiple output dots in flight
- direct 8-phase masked/grouped reduction

## 16. GPU implementation plan

Preserve the algorithmic abstraction, not the CPU instruction sequence. The first consistency target is:

```text
Tile32 = one 32-bit warp ballot mask
```

Generate the same field masks:

```text
L0 L1 L2
E0 E1 E2 E3
SIGN
```

as 32-bit warp-local bitsets and use the same phase-routing / signed-count identities as the CPU Tile64 reference.

GPU objective:

```text
packed LNS product ADD / sign XOR
    ↓
32-lane final product states
    ↓
ballot / lane predicates
    ↓
8-way phase routing
    ├─ direct ±(1<<E) integer reduction to A[0..7]
    └─ optional signed POPCOUNT histogram
    ↓
8-state finalization or pure-LNS tree
```

Candidates:

- warp ballot
- `__popc` / `__popcll`
- `__match_any_sync`
- warp-level grouping / segmented reduction
- shared-memory eight-accumulator layout
- register-resident partial accumulators

Benchmark at least:

1. scalar/lane reference `A[L3] += ±(1<<E4)`
2. ballot-generated phase masks + direct eight-accumulator reduction
3. phase-local signed histogram
4. full-state histogram / match-any grouping

Do not mechanically port CPU bit transpose. First prove Tile32 and Tile64 produce the same `A[0..7]`; only then explore larger bit arrays, wider subgroups, or custom layouts.

## 17. FPGA / custom logic model

A streaming implementation is straightforward:

```text
packed state generation
    ↓
state-set decoder / bit-vector formation
    ↓
population counters
    ↓
compressed signed state populations
    ├─ reference: shift/add → fixed-point
    └─ pure-LNS: count-log LUT → balanced kappa± tree
                               ↓
                         log-scale offset
                               ↓
                              LNS8
```

For ternary weights:

```text
activation state masks
AND ternary non-zero/sign masks
POPCOUNT
```

can replace most conventional multiplier logic.

---

## 18. Correctness test plan

### Exhaustive micro-tests

1. all LNS8 non-zero code pairs
2. all sign combinations
3. zero × anything
4. saturation boundaries
5. Q9.6 → LNS8 full input range
6. 5-bit / 6-bit / 7-bit re-log LUT comparison
7. exact same-sign fractional-LNS pair add against FP64
8. opposite-sign add/sub including exact cancellation
9. population-count folding: `n` identical states vs `k + 8*log2(n)`, `n=1..128`
10. balanced-tree pure-LNS reduction vs direct FP64 sum at multiple internal fractional precisions

### Dot-product tests

Run random and adversarial vectors for:

```text
K = 32
K = 64
K = 128
K = 256
K = 4096
K = 8192
```

References:

- FP32 original
- ordinary Q4_0 dequantized dot
- exact LNS8→FP64 dot
- BitState histogram path

Separate error into:

1. source quantization error
2. Q4→LNS mapping error
3. histogram arithmetic error
4. fixed-point materialization error
5. Q9.6 rounding error
6. Q9.6→LNS8 re-encoding error

The histogram itself should be exact for the chosen finite-state representation.

---

## 19. Performance test plan

Measure each stage separately and fused.

### Micro-kernels

A. Q4 packed decode / LUT

B. packed product-state ADD

C. state decomposition

D. state-tile packing / bit transpose

E. state mask generation

F. POPCOUNT histogram

G. histogram shift/add reduction

H. eight phase coefficients / dyadic reference finalization

I. population-count → fractional-LNS offset LUT

J. `kappa+ / kappa-` fractional-LNS add/sub primitive

K. balanced 8→4→2→1 LNS reduction

L. Q9.6 → LNS8 reference boundary

M. fully fused dot/GEMV kernel

### Metrics

CPU:

- cycles / output
- cycles / weight
- instructions / weight
- uops
- IPC
- POPCNT throughput
- dependent reduction depth / critical-path stages
- fractional-LNS LUT accesses and add/sub stages
- L1/L2 misses
- effective GB/s
- actual memory GB/s

GPU:

- kernel latency
- weights/s
- effective GB/s
- memory throughput
- registers/thread
- occupancy
- warp stall reason
- ballot/match/popcount instruction cost

The main comparison is end-to-end latency, not nominal FLOPS.

---

## 20. Primary baselines

CPU:

- llama.cpp Q4_0 GEMV / dot path
- scalar Q4_0 dequant + dot
- optimized INT8 dot where available
- T-MAC-like LUT path where practical

GPU:

- existing Q4 dequant + CUDA GEMV/GEMM
- Tensor Core path
- CUDA-core low-bit path

Primary workload:

```text
LLM decode
batch = 1 first
small batch second
prefill later
```

---

## 21. Optimization priorities

Priority order:

1. memory traffic
2. weight unpack / ternary mask load
3. reusable state-set construction
4. bit transpose / ballot / equivalent grouping
5. POPCOUNT throughput and state-domain dependency breaking
6. sparse histogram / non-zero bucket layout
7. fractional-LNS count-folding and `kappa±` LUT cost
8. balanced reduction critical path
9. dyadic shift/add reference materializer
10. Q9.6 / final boundary conversion

Do not over-optimize the final conversion before the state-domain path is competitive. The central measurement is whether POPCOUNT-based state reduction removes enough dependent arithmetic work to compensate for state-set and LUT overhead.

---

## 22. Patent claim review — implementation context, not a design constraint

The technical design above should be optimized on its own merits.

A review of the currently issued U.S. NVIDIA patents in the relevant family does **not** support treating generic software LNS bucket accumulation, generic phase/octave decomposition, or BitState population counting as broadly claimed subject matter.

### US11886980B2

Independent claims 1, 16, and 19 include a combination centered on:

- image or sound data
- a tensor core
- at least one neural-network layer
- logarithmic values expressed as sign / quotient / remainder
- generating partial sums by sorting quotient components according to remainder components
- a specified neural-network result

Dependent claims add separate accumulators, shifted binary-one quotient contributions, scaling, and re-log conversion.

### US12118454B2

The continuation retains a similarly specific independent-claim structure:

- image or sound data
- tensor core / neural-network layer
- quotient/remainder sorting into partial sums
- specified downstream application use

Dependent claims add separate accumulators and shifted-one contributions.

### US12033060B2

The independent claims are directed much more specifically to an **asynchronous accumulator** architecture, including:

- a bit-selection input specifying bit position `j`
- adding `2^j` to the asynchronous accumulator output
- paired positive/negative asynchronous accumulators in claim 1
- toggle flip-flop accumulator-cell implementations in other independent claims
- quotient-derived one-hot bit selection in claim 7
- an array of asynchronous accumulators in system claim 16

BitState's ordinary CPU/GPU Boolean masks + POPCOUNT histogram are not this accumulator architecture.

### US12141225B2

Independent claim 1 requires, among other things:

- an array of asynchronous accumulators
- one accumulator corresponding to each remainder value
- incrementing or decrementing a single accumulator bit selected by the quotient
- paired toggle flip-flops used to compute partial-sum bits

Again, a software state-set / POPCOUNT histogram does not use this structure.

### Engineering conclusion

The BitState design should therefore **not** be artificially weakened merely to avoid generic operations such as:

- phase/octave extraction
- state grouping
- shift/add reconstruction
- fixed coefficients
- leading-one re-encoding

Those are useful numerical techniques and are not, by themselves, the issued independent claims summarized above.

The issued NVIDIA family also contains quotient/remainder bucket accumulation concepts that are mathematically close to an 8-phase decomposition. That similarity should be acknowledged when comparing implementations. The v0.5 software hypothesis, however, specifically emphasizes **wide reusable state sets + POPCOUNT as a dependency-breaking reduction**, followed optionally by a **pure fractional-LNS reduction tree instead of linear partial-sum materialization**. This is an engineering distinction, not a legal conclusion.

BitState's implementation focus is now:

```text
finite states
    ↓
wide reusable state-set representation
    ↓
parallel population counting
    ↓
dependency-broken compressed state domain
    ├─ dyadic reference materialization
    └─ pure fractional-LNS reduction tree
```

This section is an engineering claim review, not a legal non-infringement opinion.

### Pending applications

A pending published U.S. application should not be treated as though it were already an issued patent with a final enforceable claim set.

It can still be monitored for future claim changes. U.S. law also provides limited provisional-rights conditions for published applications if, among other requirements, a later-issued claim is substantially identical and the accused party had actual notice.

Therefore:

- do not present a pending application as a current issued-patent boundary;
- do not ignore it completely if a formal FTO review is required;
- keep pending applications in a separate monitoring section, not in the core implementation restrictions.

---

## 23. Coding-agent workflow

The coding agent should proceed experimentally rather than assuming one layout is optimal.

### Phase 1 — correctness

Implement:

```text
exact LNS8 / FP64 reference
scalar signed histogram
shift/add reference materializer
fractional-LNS pair add/sub reference
population-count -> log-offset LUT
balanced pure-LNS reduction
optional Q9.6 boundary
```

Require bit-exact histogram agreement with the reference state counts. Separately measure pure-LNS internal-rounding error; do not conflate it with state-counting correctness.

### Phase 2 — CPU Tile64 routing / state counting

Implement and compare:

- Tile64 direct 8-phase routed accumulator
- Tile32 word-width-equivalent reference
- phase-mask generation cost
- phase-local signed histogram
- direct full-state masks
- SWAR transpose / mask extraction
- AVX2 LUT/unpack

Report stage-by-stage cycles, separating `product ADD`, `state-set/phase-mask build`, `K→8 weighted reduction`, and `final eight-state materialization`.

### Phase 3 — ternary 128-group path

Implement:

```text
W_nonzero
W_negative
activation state masks
POPCOUNT signed histogram
one scale application per 128-weight group
```

Compare directly against the existing Bonsai2 kernel path.

### Phase 3B — dependency-breaking pure-LNS CPU path

Compare the existing dyadic materializer against a path that never creates a linear accumulator:

- signed population buckets;
- count-to-log folding;
- relative fractional-LNS normalization;
- balanced `kappa±` reduction;
- shared scale as a log offset;
- final LNS8 rounding only at the output boundary.

Report both total cycles and critical-path/dependency depth.

### Phase 4 — GPU

Implement independent CUDA approaches:

- Tile32 ballot phase masks
- direct eight-way integer accumulation
- match-any
- shared / register histogram

Do not mechanically port CPU bit transpose. First verify Tile32 produces the same `A[0..7]` as the CPU Tile64 reference.

### Phase 5 — fused optimization

Only after profiling, fuse the stages that reduce actual traffic or instruction overhead.

The agent must preserve a slow, clear reference implementation for differential testing.

---

## 24. Success criteria

BitState is successful if at least one practical backend shows a useful end-to-end advantage while keeping model quality acceptable.

The strongest initial success case would be:

```text
low-bit / ternary model
+ batch-1 decode
+ bandwidth-sensitive hardware
+ state counting cheaper than dequantize + MAC
```

A useful result does not require beating Tensor Core peak throughput in dense prefill.

A CPU-only win, ternary-only win, or batch-1 decode win is already technically meaningful.

---

## 25. One-sentence definition

> **BitState/HSDR moves reduction into a finite state domain to break serial arithmetic dependencies: wide state sets and POPCOUNT compress many low-bit contributions in parallel, after which only a small state set is reduced—optionally entirely in fractional-LNS form without linear materialization.**

---

## References used for the patent-claim review

- https://patents.google.com/patent/US11886980B2/en
- https://patents.google.com/patent/US12033060B2/en
- https://patents.google.com/patent/US12141225B2/en
- https://patents.google.com/patent/US12118454B2/en
- https://www.law.cornell.edu/uscode/text/35/154