|
Download Bitstate/BitState_HSDR_v0.5_en_WHT-RMSNorm-premise.md from mktnhr/BitState: direct link, hf CLI and curl.
- Browser
- Download file 50.4 kB
-
https://huggingface.co/datasets/mktnhr/BitState/resolve/main/Bitstate/BitState_HSDR_v0.5_en_WHT-RMSNorm-premise.md
- Command line
-
hf download hf://datasets/mktnhr/BitState/Bitstate/BitState_HSDR_v0.5_en_WHT-RMSNorm-premise.md
-
curl -L -o BitState_HSDR_v0.5_en_WHT-RMSNorm-premise.md https://huggingface.co/datasets/mktnhr/BitState/resolve/main/Bitstate/BitState_HSDR_v0.5_en_WHT-RMSNorm-premise.md
50.4 kB
# 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
# 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)
```