BitState / README.md
mktnhr's picture
Upload README.md
42db578 verified
|
Raw History Blame Contribute Delete
10.7 kB
# BitState / HSDR PoC Technical Brief — v0.5
Status: experimental engineering proposal, not a performance claim.
Primary target: low-bit / ternary LLM GEMV, batch-1 decode first.
Suggested first integration target: PrismML llama.cpp fork / Bonsai 2, CPU first.
## 1. Core hypothesis: move reduction into the state domain
BitState/HSDR v0.5 centers the PoC on one implementation question:
> **Move the reduction into the state domain to break the serial arithmetic reduction dependency.**
A conventional accumulator lets every new add depend on the previous partial sum. BitState instead:
1. represents activation/weight products as final LNS8-like `S1|E4|L3` states using integer ADD/XOR;
2. routes each product by `L3` toward one of eight phase aggregates;
3. uses `±(1<<E4)` as the exact dyadic payload for the direct baseline;
4. optionally constructs wide state-set masks / POPCOUNT histograms to reduce many lanes in parallel;
5. reduces only the resulting eight dyadic accumulators or compressed non-zero state set;
6. optionally keeps the population path entirely in fractional-LNS form.
The performance question is now split cleanly: **can K product states be reduced to eight phase aggregates cheaply enough on ordinary CPU/GPU integer/bit hardware?** POPCOUNT is one candidate mechanism, not a mandatory primitive for the direct eight-accumulator path.
## 2. Why Bonsai 2 is a useful first target
Bonsai 2 provides a clean ternary test case:
- weights are ternary: `{-1,0,+1}`;
- PQ2_0 and PTQ1_0 use 128-weight groups with a shared scale;
- the runtime already has a model-specific Hadamard/sign-transform contract;
- one activation tile is reused across many output rows in GEMV;
- the PoC does not require a new GGUF / ggml type.
PQ2_0 or pre-decoded ternary masks are preferred for the first CPU microbenchmark so the BitState cost can be separated from PTQ1_0 dense base-3 unpacking.
References:
- https://github.com/PrismML-Eng/Bonsai-demo
- https://github.com/PrismML-Eng/Bonsai-demo/blob/main/MODEL-FORMATS.md
- https://github.com/PrismML-Eng/llama.cpp
## 3. LNS8 state used by the PoC
```text
code 0 = exact zero
code 1..127 = non-zero magnitude
sign = separate
|x| = 2^((code - 74)/8)
8 codes = exactly x2
code 74 = 1.0
```
For non-zero `k`:
```text
phase = k & 7 // 0..7
band = k >> 3 // 0..15
```
and
```text
|x| = 2^-9 * 2^band * F[phase]
F[p] = 2^((p - 2)/8)
```
The exact power-of-two band axis is what permits cheap relative positioning; only eight phase states remain inside one octave.
## 3.1 Preferred dyadic correctness baseline: direct eight-phase accumulation
After all log-domain terms belonging to a product have been applied, interpret the final product as:
```text
S1 | E4 | L3
```
and reduce each lane as:
```text
phase = L3
payload = sign * (1 << E4)
A[phase] += payload
```
For one GEMV/GEMM output dot, all `K` products (including realistic `K=4096` / `5120`) reduce to only eight signed integer accumulators. Final materialization is:
```text
S = 2^-9 * sum_p A[p] * F[p]
F[p] = 2^((p-2)/8)
```
This is algebraically identical to building `H[phase][band]` first and then computing `A[p] = sum_b H[p][b] << b`.
The correctness reference is the procedure used in `LNS8_base74_8step_zone8_popcount_demo_JA_v0.8_bitslice128_validation.xlsx`: `Inputs_128` is treated as two Tile64 blocks, `L3` creates phase selector masks, `E4` supplies the power-of-two payload, and S1 supplies the sign. Phase masks are intermediate routing values, not final populations.
POPCOUNT is therefore **optional** for the direct dyadic path. It remains a separate implementation candidate when explicit state populations provide a cheaper dependency-breaking reduction.
## 4. Ternary state-domain population reduction
For a 128-weight group:
```text
w_i = d * t_i
t_i in {-1,0,+1}
```
For the factorized ternary variant, the shared scale `d` may remain outside the population reduction. In the generic product-state reference, any scale/log offset that is intended to change the routed product code must be applied before `L3/E4` decomposition. These are separate variants and must not be mixed. Represent each ternary row with:
```text
W_nonzero
W_negative
```
For activation magnitude state `s`:
```text
A_s = lanes with activation magnitude state s
M = A_s & W_nonzero
PNEG = activation_sign XOR W_negative
N = popcount(M)
Nneg = popcount(M & PNEG)
C_s = N - 2*Nneg
```
`C_s` is the signed population of state `s` after ternary selection. The wide masks and POPCOUNTs are independent across active states, which is the dependency-breaking step.
## 5. Two post-POPCOUNT paths
### 5.1 Dyadic reference path
Keep the existing exact/algebraically simple baseline:
```text
signed state histogram
-> per-phase integer shift/add
-> wide fixed-point
-> optional Q9.6
-> scale
-> optional LNS8 re-encode
```
This path is essential for correctness comparison and may itself be competitive.
### 5.2 Pure fractional-LNS candidate
A stronger v0.5 candidate is to avoid a linear accumulator entirely on the population path.
For signed state population `C[k] != 0`, fold repeated identical states first:
```text
bucket_sign = sign(C[k])
bucket_lambda = k + 8*log2(abs(C[k]))
```
For Tile128, `abs(C[k])` is only `1..128`, so the population correction can be a tiny LUT.
The eight phase tables may be normalized around anchor codes `120..127`; code 122 is the exact value 64. The identity
```text
k = 8*band + phase
= (120 + phase) + 8*(band - 15)
```
means band movement is only an integer code offset. The internal coordinate retains fractional code bits; it is not forced back to 8-bit LNS after each add.
Pairwise same-sign add for `a >= b`, `diff=a-b`:
```text
out = a + kappa_plus(diff)
kappa_plus(diff) = 8*log2(1 + 2^(-diff/8))
```
Opposite sign, `diff > 0`:
```text
out = a + kappa_minus(diff)
kappa_minus(diff) = 8*log2(1 - 2^(-diff/8))
```
Equal opposite magnitudes cancel to exact zero. Runtime uses small correction LUTs rather than general log/pow functions.
After each phase is compressed, reduce the eight phase aggregates as a balanced tree:
```text
8 -> 4 -> 2 -> 1
```
This gives only three dependent LNS-add stages for the final eight-state reduction. The same balanced primitive can be used within a phase when multiple octave buckets remain.
A positive shared scale can remain in the log domain:
```text
lambda_scaled = lambda_sum + 8*log2(d)
```
so the pure path can stay logarithmic until the final LNS8 boundary.
## 6. Critical implementation rule: reuse activation state sets
For batch-1 GEMV, the activation tile is common to many weight rows. Separate fixed and repeated costs:
```text
activation encode / state-set construction // once per activation tile
weight-row mask intersection + POPCOUNT // repeated per row
compressed-state reduction // repeated per row/group
```
Useful reuse sweep:
```text
N = 1, 8, 32, 128, 512, 2048+
```
Report the crossover instead of assuming it.
## 7. Minimal PoC sequence
### Phase A — standalone correctness
Implement:
- FP64 direct ternary dot;
- exact LNS8 decode reference;
- scalar direct eight-phase accumulation `A[L3] += ±(1<<E4)`;
- Tile64×2 reference matching the Excel v0.8 128-input procedure;
- signed POPCOUNT histogram;
- histogram-to-`A[0..7]` equivalence;
- dyadic final materialization;
- fractional-LNS pair add/sub reference;
- count-to-log folding for `n=1..128`;
- balanced pure-LNS reduction at several internal fractional precisions.
`direct decode == direct A[8] == histogram-derived A[8]` must be exact. Pure-LNS rounding error is a separate measurement.
### Phase B — synthetic CPU microbenchmark
Compare:
1. direct decoded ternary dot;
2. scalar/direct eight-phase routed accumulator;
3. Tile64 phase-mask + direct eight-accumulator reduction;
4. signed histogram + dyadic reconstruction;
5. signed histogram + pure fractional-LNS reduction.
Sweep state cardinality, ternary zero density, output-row reuse, `K`, and internal LNS precision.
### Phase C — fork integration
First integrated target:
- CPU;
- batch 1;
- one ternary vec-dot / GEMV path;
- post-Hadamard activation domain;
- PQ2_0 first if implementation simplicity matters.
### Phase D — end to end
Measure TG128, decode latency, state-set build cost, POPCOUNT cost, dependent reduction depth, memory traffic, cycles/output, and quality delta from activation LNS8 encoding.
## 8. State-set implementation candidates
- direct eight-phase selector masks from `L2,L1,L0`;
- sparse `(state_id, lane_mask)` pairs for only active states;
- phase-local masks;
- SWAR / AVX2 byte-lane extraction + scalar POPCNT;
- AVX-512 mask/VPOPCNT where available;
- GPU ballot / match-any rather than literal CPU bit transpose.
Record unique states per tile for histogram variants, but also report the direct-path cost separately: product-state generation, phase-mask construction, K→8 weighted reduction, and final eight-phase materialization.
## 9. Metrics that matter
CPU:
- ns / 128-weight group;
- cycles / output row and / weight;
- uops / IPC;
- state-set build cycles;
- POPCNT throughput;
- non-zero state buckets;
- fractional-LNS LUT accesses;
- dependent reduction depth / critical-path LNS stages;
- L1/L2 misses and memory bandwidth;
- reuse crossover vs baseline.
Correctness/quality:
- state histogram exactness;
- pure-LNS error vs FP64 by internal fractional precision;
- cancellation cases;
- LNS8 saturation / underflow;
- model quality / perplexity or task checks.
## 10. Falsification criteria
The PoC should be allowed to fail cleanly. Redesign or stop if:
- state-set construction cannot be amortized;
- real activations have too many unique states;
- mask/POPCOUNT work exceeds the existing ternary path;
- pure-LNS LUT/add stages recreate a long critical path;
- required fractional precision makes the path too expensive;
- activation LNS8 quality loss is unacceptable;
- conversion/scale handling cancels the compute saving.
A negative result is useful if the limiting term is isolated.
## 11. What this PoC is not claiming
- not a new GGUF type;
- not a replacement for all GEMM/GEMV kernels;
- not a claim that POPCOUNT always beats SIMD/Tensor Core MAC;
- not a claim of research novelty;
- not a requirement to use Q9.6 internally;
- not a claim that pure-LNS will necessarily beat the dyadic reference path.
The narrow question is whether **state-domain dependency breaking plus population reduction** has a competitive region in real low-bit / ternary decode workloads, and whether a pure fractional-LNS final reduction improves that region.