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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
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
1484
1485
1486
1487
1488
# BitState / HSDR

## 低ビットLLM推論のための有限状態度数縮約と依存鎖切断型log-domain reduction

**実装提案 v0.5 日本語版**  
**主対象:** 低ビットLLMのGEMV / 小バッチdecode  
**Reference / 検証経路:** LNS8 → finite-state population reduction → wide integer/fixed-point → optional Q9.6 → LNS8  
**最適化候補経路:** LNS8 → state-domain population reduction → relative fractional-LNS → balanced LNS add/sub tree → LNS8

---

## 1. 目的

BitStateは、低ビット推論のreduction問題を、不可避な数値加算より先に有限な **state domain** へ移す計算モデルである。

中心となる考え方は次の一文に集約する。

> **state-domainへ移すことでreduction dependencyを切断する。** wideなstate setを形成し、等価状態を並列に数え、圧縮後に残った小さなstate集合だけを最終reductionへ渡す。

数値実体化を後段へ遅延することは引き続き重要だが、v0.5ではそれをより強い目的――長い逐次数値加算鎖を、並列な集合演算+短い最終reductionへ置換すること――の結果として位置付ける。

主要パイプラインは次のとおり。v0.5では、**最終product stateから8本のphase integer accumulatorへ直接縮約する経路**を、最も単純なcorrectness / implementation baselineとして明示する。full-state POPCOUNT histogramは、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など)
    ↓
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
```

最適化経路では、product生成から最終reductionまでlogarithmic coordinateのまま保持してよく、GEMV reduction内部でFP/linear materializationを必須としない。

主な最適化対象はピークFLOPSではない。対象はdecodeパイプライン全体である。

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

---

### 1.1 前提 — 回転量子化によって狭い数値域が現実的になってきた

BitStateがLNS8やQ9.6のような比較的狭い数値表現を検討できる背景には、近年の低ビットLLMで **回転量子化(rotation-aware quantization)** が実用化され、QuaRotやSpinQuantに代表されるように、WHT / Hadamard rotationなどで外れ値やエネルギー集中を複数次元へ再分配した状態で低ビット化する設計が広がっていることがある。

この前提は、「すべてのモデルでfull-scale dynamic rangeが不要」という意味ではない。重要なのは、推論kernelがBF16/FP16の理論上の全dynamic rangeを無条件に再現するのではなく、**回転後に実際に現れるactivation / weight distributionを測定し、その必要範囲に合わせて内部表現を設計できるモデルが増えている**という点である。

Bonsai2は具体例である。公開されているBonsai2のモデル資料では、language model側のweightはblockwise Hadamard-rotated basisで保存され、runtimeがmatching transformをactivationへ適用することが明記されている。低ビット化の対象にはembedding、attention projection、MLP projection、LM headが含まれる。またMLX版では、通常loaderがactivation transformとinverse embedding lookupを行わない場合に誤った出力になることも明記されている。

したがってBonsai2では、回転は単なるquantizer前処理ではなく、**checkpointとruntimeの間で維持される数値basisの契約**になっている。token embedding / token pathもこの契約に含まれ、embedding lookup境界では対応するinverse transformが必要になる。

multimodalについては区別が必要である。公開資料上、vision tower自体は非回転・非量子化のFP16で保持される構成がある。一方、projected visual tokensがlanguage modelへ入った後は、language model側のrotation-aware activation pathを通る必要がある。したがって **multimodal interfaceもlanguage-model側のbasis contractから独立ではない** が、vision towerそのものがHadamard回転されているという意味ではない。

Bonsai2の公開資料だけからquantization-aware trainingの全recipeを確定することはできない。ただし、配布checkpoint自体がrotated basisを前提とし、activation transformとinverse embedding lookupを必須とすることから、少なくとも **rotation-awareな低ビット最適化を前提にしたモデル / runtime設計** であることは明確である。本書ではこの傾向を、LNS8 / Q9.6の必要dynamic rangeを実測ベースで狭められる可能性を持つ重要な前提とする。

BitState実装では、各モデルについて次を必ず測定する。

- WHT / rotation前後のactivation absolute maximum
- RMSNorm前後、およびlearned gain `gamma` 適用前後のactivation absolute maximum
- RMS / percentile distribution
- layer別の必要dynamic range
- LNS8 saturation / underflow率
- Q9.6 saturation率
- rotationを含むend-to-end quality差

つまり、**回転によってfull-scale保持を機械的に捨てるのではなく、回転後の実測分布を根拠に必要範囲だけを保持する**。

参考:

- 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 前提 — RMSNormの普及により、GEMM直前activationの絶対レンジも管理しやすい

回転量子化とは別に、近年のdecoder-only LLMでは **RMSNorm** が広く採用されている。Qwen3.5、Gemma 3、Llama 4、Mistral系など、主要な新しいモデルfamilyでRMS normalization layerが使われている。したがってBitStateでは、WHT / rotationだけでなく、**RMSNorm後のactivation domainをLNS8へ入れるintegration point**も重要な対象とする。

RMSNormはoutlierを個別にclipする処理ではない。tokenごとのhidden vector `x` 全体を、そのroot-mean-squareで共通にrescaleする。learned gainを掛ける前の正規化値を `u` とすると、概念的には:

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

であり、hidden dimensionを `d` とすれば:

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

したがって各要素には次の理論上限がある:

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

これは「channel-wise outlierが消える」という意味ではない。1つのchannelへエネルギーが極端に集中することは残り得るが、**RMSNorm前に存在した数万~数十万という絶対値そのものは、正規化後にはhidden dimension由来の有限範囲へ押し戻される**。WHT / Hadamard rotationはその次に、残ったchannel-wise concentrationを複数次元へ再分配できる。このためRMSNormとWHTは競合する処理ではなく、BitStateから見ると互いに補完的である。

現在のLNS8基準format `S1E4L3 / base74` は、最大magnitudeが:

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

である。したがって `gamma` 適用前のRMS-normalized activationを直接LNS8へencodeする場合、理論上はおおよそ:

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

まで、RMSNorm由来の最悪1-axis concentrationをsaturationなしで覆える。代表例:

```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
```

したがって5120~9216級では、current base74 / S1E4L3の約±98.7 rangeが **RMSNorm直後の理論上限そのものを包含できる**。12288級では理論最悪値だけが上限を約12%超えるため、次のいずれかを実測で選ぶ:

1. 稀なoverflowだけをLNS8最大値へsaturate / clampする;
2. tensor / model metadataのsystem exponent offsetをわずかに上側へずらす(例: `code 72 = 1.0` なら最大値は約117.38);
3. 実測上wide rangeが本当に必要なtensorだけ、将来のwide-range profile / escape pathを使う。

ただし実際のRMSNormは通常、正規化後にlearned gain `gamma_i` を掛けるため、最終出力は厳密には `sqrt(d)` を超え得る。したがってBitStateは、**RMS normalization後・`gamma` 適用前をencode点にする、`gamma` を後続linear weightへfoldできる箇所ではfoldする、または`gamma`適用後の実測分布でrangeを決める**、のいずれかをmodel/backendごとに選択する。

この前提の目的は、「RMSNormがあるからfull-scale supportは不要」と断定することではない。**WHT / rotation済み、またはRMSNormによって絶対rangeが管理されたactivation pathでは、稀な理論外れ値のために全要素のLNS8 precisionを犠牲にするより、S1E4L3の細かい8-state-per-octave gridを維持できる可能性が高い**、という検証仮説を明示することである。

追加参考:

- 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 と HSDR

### BitState

BitStateは、低ビット数値表現を、小さな有限状態空間として扱い、Boolean演算と整数演算で操作する。

代表的なprimitive:

- 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は、多数の要素単位演算を段階的に小さなstate domainへ縮約し、**domainを移すこと自体を使ってserial reduction dependencyを切断する**。

典型的な階層:

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

本質は次のとおり。

> **state-domain reductionはdependency-breaking transformである。** 等価状態を先に並列集計し、圧縮後の小さなstate集合だけを依存関係を持つ算術reductionへ入れる。

目的は単に「値の個数を減らす」ことではない。scalar bit operation、SIMD mask、GPU ballot、hardware population counterへ自然に写像できる、浅いdependency graphを作ることである。

---

## 3. LNS8 基準フォーマット

現在のLNS8 magnitude gridは次式で定義する。

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

ここで:

- `k = 1..127` : 非zero magnitude code
- `k = 0` : exact zero
- signは別管理
- 8 code進むと正確に×2
- code 74 = 1.0

非zeroの7bit magnitude codeについて:

```text
phase  = k & 0x07     // 下位3bit、intra-octave index 0..7
octave = k >> 3       // 上位4bit、coarse exponent / octave index 0..15
```

本書の用語:

- **phase** = 下位3bit = octave内位置
- **octave** = 上位4bit = coarse exponent
- **state** = 完全な有限状態code。必要に応じてsignを含む

74 = 9×8 + 2 なので:

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

この因数分解はpopulation counting後の数値復元で有効である。ただしhistogram生成方法を制約するものではない。

### 3.1 S1E4L3としての論理分解 — exponent × fractional-log field

同じ8bit表現を、flatな7bit magnitude codeとしてだけでなく、FPに似たfield構造として読むこともできる。非zero stateについての論理分解は次のとおり。

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

ここで `E = octave`、`L = phase`、符号を `s ∈ {-1,+1}` とすると、非zero値は

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

と書ける。したがって各fieldの役割は次のように整理できる。

- **S1** — sign。population reductionではpositive / negative populationへ写像できる。
- **E4** — 4bitのcoarse binary exponent / octave。`E + 1` は厳密に `×2` であり、materializationではSHIFT / dyadic scale軸として扱える。
- **L3** — 3bitのfractional logarithmic field。1 octave内を8分割し、`2^((L-2)/8)` の8状態を表す。

直感的にはL3を **logarithmic mantissa** と呼ぶことができるが、IEEE floating-pointのlinear mantissa / significandではない。数学的には **fractional exponent** である。本書では誤解を避けるため、正式名称を **fractional-log field** または既存用語の **phase** とする。

通常のE4M3風の表現と比較すると構造差は次のようになる。

```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)
```

つまり見た目は `S1 | E4 | L3` だが、下位fieldもlogarithmic coordinateの一部である。このためLNS乗算ではlinear mantissa multiplierを必要とせず、full codeでは従来どおり

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

で処理できる。field分解で見ると、`L3` の加算結果から生じるcarry / borrowがそのまま `E4` へ移る。非zero inputについて、

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

であり、これは `k_product = k_a + k_b - 74` と同じ関係である。高速実装では最終storage rangeへ先にsaturateせず、より広いsigned intermediateを使う。

### 3.2 2-D state-spaceとしての見方

HSDRの観点では、非zero magnitude stateをflatな127状態としてだけでなく、概念的に次の直積として扱える。

```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
```

直感上は、**横方向を `S1 + L3` の4bit signed intra-octave LNS slice、縦方向をE4M0-likeなpure power-of-two scale axis** と見ることができる。ただしこれはalgorithmic / visualization上の分解であり、IEEE E4M0や独立した4bit LNS storage formatを意味しない。`k=0` はexact zeroとして別扱いである。

この見方では、後段のHSDR操作との対応も明確になる。

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

したがって `H[phase][octave]` は単なる便宜的な2-D histogramではなく、S1E4L3論理fieldをそのままstate-domainへ展開した表現として理解できる。BitStateはこの直積構造を利用し、sign、fractional-log phase、power-of-two scaleを別々のcheap primitiveへ写像してから縮約する。

---

## 4. Stage A — Product-state generation

LNSの乗算は指数加算になる。

概念的には:

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

高速pathでは、dynamic rangeが許す限りpacked integer arithmeticを使う。

候補:

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

### Product-state completion rule

`L3` / `E4`へ分解してphase routingまたはbitsliceを開始する前に、**その経路で最終product stateに含める全log-domain offsetを加算し終える**。weight exponent、preconverted scale offset、bias adjustmentなどがproduct codeを変えるなら、それらを先に反映する。

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

shared group scaleを数式上 `d × Σ(...)` として外側にfactorすること自体は可能だが、それは**別のfactorized variant**として扱う。scaleをproduct codeへ含める経路と、reduction後へfactorする経路を同じstate routing説明の中で混同しない。

### Range rule

最初のcorrectness実装では、最終LNS codeより広い中間型を必ず使用する。

測定項目:

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

観測範囲を理解してから、packed INT8のsaturation / wrapping ruleを決める。

---

## 5. Stage B — State Tile

複数のproduct stateを1つのtileとして処理する。

初期候補:

```text
Tile32
Tile64
Tile128
```

CPU reference target:

- Tile64。state-membership maskを64bit integer 1本へ自然に対応させられるため。

Bonsai2 reference target:

- Tile128。ternary weight scale groupが128 weight単位だからである。

State Tileは論理的なグルーピングである。backendはregister、vector lane、warp lane、bitsetなど、任意の物理表現を選んでよい。

---

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

final product stateについて:

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

v0.5のcorrectness baselineでは、full histogramを必須とせず、各productを次の**8本のsigned integer accumulator**へ直接縮約できる。

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

すなわち:

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

最終値は:

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

である。この変形は量子化済みLNS8 stateに対して代数的に厳密であり、`H[phase][octave]`を先に作ってから `Σ H[p][o] << o` する方式と同じ結果になる。

### C1. GEMM / GEMVでの意味

1つのoutput dotで `K=4096` や `K=5120` のproduct stateがある場合、全K項を最終的に **8本のA[0..7]** へ入れる。8本まで縮約できれば、その後に実数係数 `F[p]` を適用して8項だけを加算すればよく、支配的な課題は最終materializationではなく **K項 → 8本へのrouting / weighted reduction** である。

### C2. Excel correctness reference

本書のこの経路は、`LNS8_base74_8step_zone8_popcount_demo_JA_v0.8_bitslice128_validation.xlsx` の `Inputs_128` / `BitSlice128_一致確認` 相当の手順をcorrectness referenceとする。

同Excelでは128項を `Tile64 × 2` として扱い、各項の:

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

から `±(1 << E4)` を作り、`L3`で8本のaccumulatorへrouteする。8本の整数accumulatorから復元した値がdirect decodeと一致することを確認する。

### C3. Histogram / POPCOUNT path remains valid

full-state histogramは不要ではなく、別の正確な実装familyとして残す。

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

direct 8-phase pathはbucket作成とshift/addを融合した形、histogram pathはstate populationを明示的に保持する形である。前者は単純なreference / routed-reduction候補、後者はPOPCOUNTによるdependency breakingやpure-LNS foldingの候補として比較する。

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

Tile64のCPU bitsliceでは、final product stateのfieldを次の64bit bitplaneとして表せる。

```text
L0 L1 L2          // L3の3 bitplane
E0 E1 E2 E3       // E4の4 bitplane
BSIGN              // sign plane, 1 = negative
```

各bit位置は元の同じlaneを保持する。例えばbit 37は、すべてのbitplaneで元のlane 37を指す。

### D1. Phase mask is an intermediate selector

`L2,L1,L0`から、phase `p=0..7`に属するlaneだけが1になる64bit mask `M[p]` をBoolean演算で生成できる。

例:

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

このmaskは**最終値でもpopulationそのものでもなく、中間routing / selector情報**である。必要ならその場で生成し、集計後に捨ててよい。8本を永続保存する必要はない。

`L3`の3bit decoderは、中間2bit groupを共有するtreeとして生成できるため、8個の完全独立比較を行う必要はない。

### D2. Sign handling in bit form

bitset自体は `+1 / -1` を直接保持できないため、signed populationが必要な場合はsign planeを明示的に使う。

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

または同値な:

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

この式はExcelの `(+ POPCOUNT) - (- POPCOUNT)` と同じ母集団を数える。XORを用いる代数的恒等式も存在するが、bucket外のnegative laneを一時的に数えるため、reference実装では上のtable-local式を優先する。

### D3. Important: phase POPCOUNT alone is not enough for the direct 8-accumulator path

`POPCOUNT(M[p])`だけではE4の重み `2^E` を失う。同じphase内でも `E=3` と `E=11` は寄与が異なるため、direct pathでは最終的に:

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

というweighted reductionが必要である。bit transpose / phase maskはそのroutingをwideに処理するための中間表現であり、POPCOUNTの使用自体は必須ではない。

backend equivalent:

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

CPUではTile64、GPUではTile32を最初の理論整合性ターゲットとする。同じBoolean式をword幅だけ変えて検証し、その後に巨大bit配列やよりwideなSIMDへ拡張する。

## 8. Stage E — Two exact reduction families

v0.5では、**direct 8-phase routed accumulation** と **state POPCOUNT histogram** を、どちらもexactなLNS8 reduction familyとして明示的に分ける。

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

各product stateについて:

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

K個のproductを処理し終わった時点で残る数値状態は8本のsigned integer `A[0..7]` だけである。K=4096 / 5120でも最終state数は8本で変わらない。

この経路はPOPCOUNTを必須としない。CPU/GPUでの性能PoCでは、phase mask、masked add、grouped reduction、SWAR、SIMD、ballotなどを比較し、K項を逐次scalar addへ戻さない実装を探す。

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

state `s`についてmembership maskを作る。

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

signed valueなら:

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

または:

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

histogram pathではfloating-point valueを作らず、同一stateをpopulationへ先に畳み込める。これはpure fractional-LNS pathや、state cardinalityが小さいworkloadでのdependency breakingに有利な可能性がある。

### E3. Exact equivalence

2-D histogramを使う場合:

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

であり、E1のdirect accumulationと同じ `A[p]` になる。PoCではこの一致をbit-exactに要求する。

## 9. Intermediate-state organization

full histogramを保持する場合は次の2表現がある。

### Full-state form

```text
H[k]       // k = 1..127、zero/signは必要に応じて別処理
```

### 2-D LNS form

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

一方、direct 8-phase pathではhistogramを永続化せず、直ちに:

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

へfoldするため、最終的なinteger stateは8本だけである。

したがってv0.5では:

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

と区別する。histogramはstate populationを保持するのでpure-LNS foldingに有用、A[8]は最終dyadic materializationへ最短で到達する。

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

direct pathではStage Eの時点で `A[p]` が得られている。histogram pathでは次式で同じ `A[p]` を生成する。

各phase `p`について:

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

これはinteger shift/addだけで実装できる。

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

8個のphase reductionは互いに独立である。

benchmark候補:

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

### Phase coefficients

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

と定義する。

scale前の数値和は:

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

2の冪でないphase係数は8種類しかない。

この8-phase finalizationをdyadic referenceの優先方式とする。direct pathではPOPCOUNT histogramを経由せず、K項から直接 `A[0..7]` を得てもよい。histogram pathではPOPCOUNT + integer shift/addを経由して同じ8本へ到達する。いずれも最終的な非2冪係数処理は最大8項だけである。

---

### F1. POPCOUNTの役割 — reduction dependencyの切断

128要素tileを通常のaccumulatorで処理すると、次の加算は前のpartial sumに依存し、長いproducer/consumer chainができる。BitStateはその前に問題をstate predicateとpopulation countへ変換する。

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

したがって性能仮説は単なる「POPCOUNTが速い」ではない。**state-domain population reductionによって、最終reduction開始前に逐次数値依存の大部分を消せるか**が中心である。

上記のshift/add materializerは代数的に分かりやすく、correctness baselineとして引き続き重要である。ただしv0.5では、dyadic direct pathに加えてpopulation / pure-LNS経路も比較する。

### F2. Relative fractional-LNS path — 一度もlinear値を作らない経路

非zero LNS8 magnitude state `k`について、内部log座標を **LNS8 code単位** で持つ。

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

保存時のLNS8は整数codeだが、reduction内部ではcodeの小数bitを許容する。これは内部accumulator表現であり、新しいstorage formatを要求しない。

signed POPCOUNT後、同一state `k`のsigned populationを `C[k]` とする。`C[k] != 0` なら、同じ大きさの寄与はpairwise加算を始める前に一つのfractional-LNS stateへ畳み込める。

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

Tile128なら `abs(C[k])` は最大128なので、population項は `1..128 -> 8*log2(n)` のtiny LUT(または等価なinteger実装)だけでよい。この処理はlinear値を生成しない。

base74 / 8-code gridでは8つのphase table `000..111` を上位octaveの8 anchor `120..127` 周辺へ正規化できる。code122はexactな64 anchorである。1 octaveが厳密に+8 codeなので、octave位置の移動は整数code offsetで表せる。

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

したがって各tableのstateは、既知の整数octave offsetと小さなfractional correctionだけで同一のrelative fractional-LNS座標系へ持ってこられる。

### F3. LNS add/sub primitive

二つのfractional-LNS magnitude coordinateを `a >= b`、差を `d=a-b`(LNS8 code単位)とする。

同符号:

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

異符号、`d > 0`:

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

出力符号は大きいmagnitude側。magnitudeが同じ異符号入力はexact zeroへ相殺する。

runtimeで一般の`log2()`や`pow()`を呼ぶ必要はない。`kappa_plus` / `kappa_minus`は、選択したfractional-code precisionで量子化した差をindexにするsmall LUTとして実装する。既存のinteger-code threshold加算は、この式を整数LNS8 codeへ直ちに丸める粗粒度special caseである。pure-LNS pathでは中間roundingを避けるためfractional code bitsを保持する。

### F4. Serial accumulatorではなくbalanced tree

population bucketは左から逐次accumulateせずbalanced treeで縮約する。最後の8 phase aggregateなら:

```text
8 states → 4 LNS add/sub を並列
         → 2 LNS add/sub を並列
         → 1 LNS add/sub
```

最終8-state reductionのdependency depthは3段。各phase内に複数octave bucketが残る場合も同じprimitiveをbalanced treeで使う。sparse-state maskならleaf数そのものを減らせる。

内部LUT precisionが有限ならreduction orderも誤差要因になるため、PoCでは複数のfractional precisionとtree orderをFP64 referenceに対して測定する。

### F5. shared scaleもlog-domainから出さない

正のshared group scale `d_scale`は、state reduction後にlogarithmic offsetとして適用できる。

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

scale offsetはconverterで事前計算するか、quantization groupごとに1回cacheできる。pure-LNS pathでは最後のlinear multiplyもlog-code ADDへ置換できる。

### F6. 二つの経路を混同しない

POPCOUNT後は少なくとも次を別々にbenchmarkする。

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

前者はcorrectness/performance baselineとして重要。後者は「GEMV reduction全体をlinear accumulator無しでstate/log座標のまま完結できるか」を検証する、より強い仮説である。

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

個々のLNS stateをreduction前に直接Q9.6へ丸めてはならない。

単体ではQ9.6の1 LSB未満の小さなstateでも、多数集まれば有意になるためである。

phase coefficient stageではQ9.6より広い内部fixed-point precisionを使う。

reference実装候補:

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

最後に1回だけQ9.6へ丸める。

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

内部係数formatは推測で決めず、error measurementから選定する。

---

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

標準re-encoding path:

```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
```

汎用`log2()`は不要。

LUTは、実装で使用するQ9.6 input domain全体について、nearest-LNS8 mappingを総当たりで生成する。

以下も比較する。

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

exact nearest-LNS8 conversionとの不一致率を測定する。

---

## 13. Q4_0 weight path

Q4_0 weight storageは4bit packedのまま維持する。

benchmarkで明確な利点が出ない限り、モデルを8bit LNS8 weightへ展開して保存しない。

Q4_0 coefficient:

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

絶対値Q4 coefficientからLNS8 exponent offsetへのtiny LUT:

```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候補:

1. FP reference: `q × d`を復元してからLNS8 encode
2. Preconverted log-scale: `d`を1回LNS codeへ変換し、exponent offsetとして加算
3. Converter-generated custom scale metadata

2、3の追加量子化誤差を1と比較測定する。

---

## 14. Ternary / Bonsai2 fast path

Ternary weight groupはBitStateと特に相性がよい。

### Rotation-aware integration point

Bonsai2 fast pathでは、ternary weightだけを見るのではなく、**対応するHadamard / sign transform適用後のactivation domain**を入力契約とする。primal-basis activationをそのままternary POPCOUNT pathへ入れてはならない。

また、token embedding lookupはrotation-aware runtime contractの境界であり、必要なinverse transformを維持する。multimodal入力についても、vision towerそのものは非回転であり得るが、projected visual tokensがlanguage modelへ入った後は同じlanguage-side basis contractへ従う。

したがってBitState kernelの主integration pointは次のいずれかとする。

1. WHT / sign transform完了後のactivationをLNS8 / state representationへencodeする。
2. WHT / sign transformとstate encodingをfuseし、中間FP materializationを削減する。

後者は性能最適化候補であり、最初のcorrectness実装では1を使用する。

128-weight group:

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

共通scale `d`は128要素のpopulation reduction外に置ける。

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

したがってweight magnitude処理はBoolean selectionまで単純化できる。

```text
W_nonzero
W_negative
```

weightごとのmagnitude multiplicationは不要。

### Signed population count

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`はternary weight selection適用後のactivation state `s`のsigned populationである。

group scaleは128要素のstate reduction完了後にのみ適用する。

二つの推奨flowを比較する。

Reference / 検証flow:

```text
128 activations + ternary masks
    ↓
state-set intersection
    ↓
POPCOUNT signed histogram
    ↓
dyadic integer shift/add
    ↓
wide fixed-point / optional Q9.6
    ↓
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
    ↓
shared scaleをlog-code offsetとしてADD
    ↓
境界でのみ最終LNS8 rounding
```

pure-LNS pathがv0.5でも残す強い仮説である。GEMV内部reductionではFP、Q9.6、その他linear accumulatorを必須としない。reference pathはdifferential testingのため必ず残す。

---

## 15. CPU implementation plan

### Reference 0 — scalar correctness

- final product stateを各laneで明示decode
- `A[L3] += sign × (1 << E4)` を直接実行
- exact double/FP64 direct decodeと比較
- performance目標なし

### Reference 1 — scalar histogram equivalence

- `H[phase][octave]`生成
- `A[p] = Σ_o H[p][o] << o`
- Reference 0の `A[0..7]` とbit-exact一致を要求

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

- 64 final product states
- `L2,L1,L0,E3..E0,BSIGN` のbitplane / equivalent mask extraction
- 3bit phase decoderから中間selector mask
- E4の `±(1<<E)` weighted contributionを8 phase accumulatorへ縮約
- 64項 → 8 partial accumulators
- two Tile64でExcel v0.8の128項validationを再現

### CPU PoC B — Tile64 signed histogram path

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

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

- signed POPCOUNT histogramを入力
- non-zero bucket populationをtiny count-to-log LUTでfold
- configurable fractional bitsを持つlog coordinate
- balanced `kappa+ / kappa-` LUT add/sub tree
- direct 8-phase dyadic pathとの総cycles / dependency depthを比較

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

最初は特殊巨大bit配列を前提にせず、標準的なinteger / bit primitiveだけで成立性を確認する。

候補primitive:

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

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

correctnessがTile64で確定した後に評価する。

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

## 16. GPU implementation plan

CPUの命令列ではなく、同じalgorithmic abstractionを32-lane warpへ写像する。

最初の整合性ターゲット:

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

CPU Tile64と同じfieldを:

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

の32bit maskとして生成し、同じphase routing / signed-count式を使う。

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
```

候補:

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

最低限benchmarkするもの:

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

CPU風bit transposeを機械的に移植しない。最初にTile32とTile64で数学的等価性を確定し、その後にlarge bitset / wider subgroup / custom layoutを検討する。

## 17. FPGA / custom logic model

streaming implementationは素直に構成できる。

```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
```

ternary weightでは:

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

によって通常のmultiplier logicの大部分を置換できる。

---

## 18. Correctness test plan

### Exhaustive micro-tests

1. 全LNS8 non-zero code pair
2. 全sign combination
3. zero × anything
4. saturation boundary
5. Q9.6 → LNS8 full input range
6. 5-bit / 6-bit / 7-bit re-log LUT comparison
7. same-sign fractional-LNS pair addとFP64の一致
8. 異符号add/subとexact cancellation
9. population count folding: `n`個の同一state vs `k + 8*log2(n)`、`n=1..128`
10. 複数internal fractional precisionでbalanced-tree pure-LNS reductionとdirect FP64を比較

### Dot-product tests

randomおよびadversarial vectorで:

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

reference:

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

誤差を次の要因へ分離する。

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

選んだfinite-state representationに対してhistogram自体はexactであるべき。

---

## 19. Performance test plan

各stageを個別および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 access数とadd/sub stage数
- 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

主要比較指標はnominal FLOPSではなくend-to-end latencyとする。

---

## 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

主workload:

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

---

## 21. Optimization priorities

優先順位:

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

最終変換を先に過剰最適化しない。中心測定は、POPCOUNT-based state reductionが、state-set/LUT overheadを上回るだけのdependent arithmeticを消せるかどうかである。

---

## 22. Patent claim review — 実装文脈の確認であり、設計制約ではない

上記の技術設計は、まず技術的合理性と性能に基づいて最適化する。

関連familyのうち、現在成立している米国NVIDIA特許の請求項を確認した範囲では、一般的なsoftware LNS bucket accumulation、一般的なphase/octave decomposition、あるいはBitStateのpopulation countingを、広く一般概念として請求しているとは読めない。

### US11886980B2

独立請求項1、16、19は、概ね次の組合せを中心とする。

- image or sound data
- tensor core
- 少なくとも1つのneural-network layer
- sign / quotient / remainderとして表現されたlogarithmic value
- remainder componentに従ってquotient componentをsortingし、partial sumsを生成
- 指定されたneural-network result

従属請求項では、別accumulator、shifted binary-one quotient contribution、scaling、re-log conversion等が追加される。

### US12118454B2

continuationも、独立請求項では同様に具体的な組合せを維持する。

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

従属請求項でseparate accumulatorやshifted-one contribution等が追加される。

### US12033060B2

独立請求項は、より具体的に **asynchronous accumulator** architectureへ向けられている。例:

- bit position `j`を指定するbit-selection input
- asynchronous accumulator outputへ`2^j`を加える
- claim 1におけるpositive/negative paired asynchronous accumulators
- 他の独立請求項におけるtoggle flip-flop accumulator-cell implementation
- claim 7におけるquotient-derived one-hot bit selection
- system claim 16におけるasynchronous accumulator array

BitStateの通常CPU/GPU上のBoolean mask + POPCOUNT histogramは、このaccumulator architectureとは異なる。

### US12141225B2

独立請求項1は、特に次を要求する。

- asynchronous accumulator array
- remainder valueごとに対応するaccumulator
- quotientが選択したsingle accumulator bitをincrement / decrement
- partial-sum bitを計算するpaired toggle flip-flops

software state-set / POPCOUNT histogramは、この構造を用いない。

### Engineering conclusion

したがってBitState設計を、次の一般的な数値技法を避けるためだけに人工的に弱くする必要はない。

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

これらは有用な一般的数値技法であり、それ自体が上記成立済み独立請求項の内容ではない。

NVIDIAのissued familyにもquotient/remainder bucket accumulationが含まれ、8-phase decompositionと数学的に近い部分がある。この類似は実装比較では明記する。一方v0.5のsoftware仮説は、**wide reusable state set + POPCOUNTをdependency-breaking reductionとして使うこと**、さらに任意で **linear partial-sum materializationをせずpure fractional-LNS reduction treeへ接続すること**を中心に置く。これはengineering上の区別であり、法的結論ではない。

BitStateの実装焦点は次へ更新する。

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

本節はengineering claim reviewであり、法的なnon-infringement opinionではない。

### Pending applications

米国の公開済みpending applicationは、final enforceable claim setを持つ成立特許と同列には扱わない。

将来のclaim changeをmonitorする意味はある。米国法上、公開後に成立したclaimがsubstantially identicalであり、actual notice等の要件を満たす場合には、限定的なprovisional-rightsの問題が生じ得る。

したがって:

- pending applicationを現在のissued-patent boundaryとして表現しない
- formal FTOが必要なら完全に無視もしない
- core implementation restrictionとは分離し、monitoring sectionとして扱う

---

## 23. Coding-agent workflow

coding agentは、単一layoutを最初から正解と仮定せず、実験的に進める。

### Phase 1 — correctness

実装:

```text
exact LNS8 / FP64 direct decode
scalar direct 8-phase accumulation: A[L3] += sign × (1<<E4)
Tile64 ×2 bitslice-style reference equivalent to Excel v0.8
scalar signed histogram
histogram -> A[0..7] equivalence
fractional-LNS pair add/sub reference
population-count -> log-offset LUT
balanced pure-LNS reduction
optional Q9.6 boundary
```

`direct decode == direct A[8] == histogram-derived A[8]` をexact一致させる。pure-LNSのinternal rounding errorは別項目として測り、state/routing correctnessと混同しない。

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

比較実装:

- 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

stageごとのcycleを報告し、特に `product ADD`, `state-set/phase-mask build`, `K→8 weighted reduction`, `final 8-state materialization` を分離する。

### Phase 3 — ternary 128-group path

実装:

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

既存Bonsai2 kernel pathと直接比較する。

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

既存dyadic materializerと、linear accumulatorを一度も作らない経路を比較する。

- signed population buckets
- count-to-log folding
- relative fractional-LNS normalization
- balanced `kappa±` reduction
- shared scale as log offset
- output境界でのみLNS8 rounding

総cyclesとcritical-path/dependency depthを別々に報告する。

### Phase 4 — GPU

独立したCUDA方式を実装:

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

CPU bit-transpose実装を機械的に移植しない。Tile32でCPU Tile64と同じ `A[0..7]` が得られることを先に確認する。

### Phase 5 — fused optimization

profiling後にのみ、実際にtrafficまたはinstruction overheadを削減できるstageをfuseする。

slowで明快なreference implementationはdifferential testing用に保持する。

---

## 24. Success criteria

BitStateは、少なくとも1つの実用backendで、model qualityを許容範囲に維持しながらend-to-end advantageを示せれば成功である。

最も期待する初期成功例:

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

dense prefillにおけるTensor Coreのpeak throughputへ勝つ必要はない。

CPU-only win、ternary-only win、batch-1 decode winのいずれでも、技術的には十分意味がある。

---

## 25. 一文定義

> **BitState/HSDRは、reductionを有限state domainへ移して逐次数値依存を切断する。wide state setとPOPCOUNTで多数の低bit寄与を並列圧縮し、残った小さなstate集合だけを縮約する。必要なら、その最終縮約もlinear実数化せずfractional-LNSのまま完結させる。**

---

## 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