CompressedGemma commited on
Commit
4654109
·
verified ·
1 Parent(s): ae547e6

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +609 -248
README.md CHANGED
@@ -2,374 +2,735 @@
2
  license: mit
3
  ---
4
 
5
- # HPC Quantizer — Shor-Optimized
6
 
7
- **GGUF quantization powered by Shor's algorithm.**
8
 
9
- HPC is probably a breakthrough in model compression, utilizing a quantization pipeline derived from Shor's factoring algorithm. It compresses large language models (like Gemma 4) by mapping quantization candidates to a quantum-inspired state space.
10
 
11
- Instead of independently rounding each weight block or running iterative belief propagation, HPC encodes scale candidates as Z₆ complex amplitudes on a constraint graph and applies the **Griffiths-Niu sequential measurement protocol**. This uses the same IDFT + feed-forward + collapse/back-action loop that extracts periods in Shor's algorithm — finding globally optimal scale configurations where quantization noise is rotated away from the transformer's reasoning dimensions.
12
 
 
13
 
 
14
 
15
- ## 1. Why Shor's Algorithm?
16
 
17
- The previous HPC engine used iterative **belief propagation (BP)** to find optimal scale configurations. BP converges to the element-wise MSE minimum — the scale configuration that minimizes total `Σ (w_original - w_quantized)²`. This produces the lowest possible RMSE, but at 2 bits per weight, the noise floor still slightly bleeds into reasoning-critical dimensions.
18
 
19
- Shor's Griffiths-Niu measurement protocol replaces BP with a fundamentally different optimization strategy:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- | Feature | Belief Propagation (v2) | Shor's Measurement (v3) |
22
- |---|---|---|
23
- | **Mechanism** | Iterative message-passing (200+ rounds) | Single-pass sequential measurement |
24
- | **Convergence** | May oscillate or get stuck | Exact marginals, no iteration |
25
- | **Inter-block coordination** | Local messages only | Global conditioning via collapse back-action |
26
- | **Error metric** | Element-wise MSE (isotropic) | D₆ vesica gate (anisotropic) |
27
- | **RMSE** | Lower | Slightly higher |
28
- | **Reasoning fidelity** | Good | **Significantly better** |
29
 
30
- The key insight: **RMSE measures the wrong thing.** Standard RMSE treats every weight dimension equally. But during matrix multiplication, some error dimensions propagate through the computation graph and destroy reasoning, while others cancel out and are invisible. Shor's measurement finds configurations where block-to-block errors are anti-correlated along the computation path — they cancel during matmul even though each individual block has slightly higher error.
31
 
 
32
 
 
 
 
33
 
34
- ## 2. Performance & Benchmarks
35
 
36
- ### Gemma 4 26B-A4B-it MoE (25.8B params)
37
 
38
- | Quantization | Size | Fits 12 GB? | Method |
39
- |-------------|------|:-----------:|--------|
40
- | BF16 | 48.5 GB | ❌ | — |
41
- | Q8_0 | ~27 GB | ❌ | Round-to-nearest |
42
- | Q4_K_M | 16.8 GB | ❌ | Round-to-nearest |
43
- | IQ3_K_XXS | ~12 GB | ⚠️ | Unsloth |
44
- | **HPC·Shor** | **10.2 GB** | **✅** | **Griffiths-Niu measurement** |
45
 
46
- ### Gemma 4 E2B-it (4.65B params)
47
 
48
- | Model | Size | BPW | PPL | Speed |
49
- |-------|------|-----|-----|-------|
50
- | BF16 (original) | 8.67 GB | 16.00 | 154.0 | 4.2 t/s |
51
- | ggml Q2_K + iMatrix | 2.77 GB | 5.12 | 89.1 | 14.0 t/s |
52
- | **HPC Q2_K + Q4_0·Shor** | **1.44 GB** | **~3.0** | **129.6** | **18.1 t/s** |
53
 
54
- ### Reasoning Benchmarks (Gemma 4 31B, Q2_K·Shor, 12.5 GB)
55
- - **25 Horses combinatorial proof:** ✅ (7 races, complete elimination)
56
- - **Hindley-Milner type inference:** ✅ (correct let-polymorphism)
57
- - **Arto Inkala "World's Hardest Sudoku":** ✅ (AC-3 + backtracking)
58
- - **Diagnose 3 non-obvious bugs in C:** ✅ (first attempt)
59
- - **Tarjan's bridge-finding algorithm:** ✅ (correct `>` vs `>=` distinction)
60
 
 
 
 
61
 
 
62
 
63
- ## 3. Quantum-Inspired Mechanics (Shor Pipeline)
64
 
65
- Standard quantization picks scales independently per block. Shor-powered quantization treats scale selection as a **global optimization problem** where the measurement of each block conditions all remaining blocks through quantum-inspired back-action.
 
 
66
 
67
- The domain mapping from Shor's integer factoring to HPC Quantization:
68
 
69
- | Shor's Factoring | HPC Quantization |
70
- |---|---|
71
- | Oracle phase `2π × d × cₖ / N` | Boltzmann amplitude from candidate error |
72
- | Period `r` | Optimal scale configuration |
73
- | QFT interference peaks at `r` | IDFT6 interference peaks at optimal RMSE |
74
- | Semi-classical feed-forward | Phase correction from measured blocks |
75
- | Born measurement → period bits | Born measurement → scale candidate selection |
76
- | Collapse + entanglement | Collapse + back-action into neighbor amplitudes |
77
 
78
- By utilizing the **IDFT6** inside the coherent sum, the algorithm creates constructive interference at the optimal RMSE configuration, similarly to how Shor's QFT creates interference at the correct period.
79
 
 
 
 
80
 
 
81
 
82
- ## 4. Q2_K and Q4_0 Promotion Strategies
 
 
83
 
84
- The quantizer automatically assigns precision tiers:
85
- - **Q4_0·Shor** — Attention projections (Q/K/V/O) — 16 candidate scales, 24-beam search.
86
- - **Q2_K·Shor** — FFN, MLP, expert weights — 36 candidate (d, dmin) pairs, dual-quhit graph, 24-beam search.
87
- - **Preserved** — Embeddings, norms, router/gate weights (kept as-is in high precision).
88
 
89
- ### Tied Embeddings
90
- If no separate output weight tensor exists, `token_embd.weight` doubles as the LM head. HPC automatically detects tied embeddings and promotes them to Q4_0 to preserve generation logic, ensuring that output tokens remain accurate despite the extreme compression of the feed-forward layers.
 
 
 
 
 
 
 
 
 
91
 
 
92
 
 
93
 
94
- ## 5. Sub-Block Refinement and Beam Search
95
 
96
- The HPC process executes in multiple phases to guarantee globally coherent scaling parameters:
97
- 1. **Phase 1: Greedy Seed & WLS Refinement**: Computes reference scale and min per 256-weight superblock.
98
- 2. **Phase 2: Candidate Generation via D₆ Vesica Scoring**: Instead of MSE, weights are scored with the D₆ Vesica gate (penalizing DC/summed errors 4x more than AC/wave errors).
99
- 3. **Phase 3: Sequential Measurement**: Builds an HPCGraph encoding candidates as Boltzmann amplitudes. Connects blocks via CZ phase gates and runs Griffiths-Niu measurement (IDFT6, Born Rule, Collapse).
100
- 4. **Phase 4: 24-Beam Hensel Search**: Maintains 24 parallel configuration beams across the tensor, branching candidates evaluated via triality-weighted scoring.
101
- 5. **Phase 5: Sub-Block Shor Refinement**: A second, smaller Shor sequential measurement over a 16-node graph corresponding to the 16 sub-blocks within each 256-weight superblock.
102
 
103
- ## 6. Prerequisites and Build Instructions
 
 
 
 
 
104
 
105
- Before you can quantize models, you must build the Shor-optimized HPC C engine.
106
 
107
- ### Dependencies (Ubuntu/Debian)
108
- ```bash
109
- sudo apt install gcc libgmp-dev libmpfr-dev python3 python3-numpy
110
- ```
 
 
111
 
112
- You will also need `llama.cpp` built from source for iMatrix generation:
113
- ```bash
114
- git clone https://github.com/ggerganov/llama.cpp
115
- cd llama.cpp && cmake -B build && cmake --build build --target llama-imatrix -j$(nproc)
116
- ```
117
 
118
- ### Build the HPC Engine
119
- Navigate to the `LLM-distributed` directory and compile:
120
- ```bash
121
- make -f makefile.quantize
122
- ```
123
- Verify the build generated `libhexstate_q2k.so`. The Python requantizer (`hexstate_requantize.py`) auto-detects this library to enable Shor optimization.
124
 
 
125
 
 
126
 
127
- ## 7. The Quantization Pipeline (End-to-End)
128
 
129
- **Step A: Convert Model to BF16 GGUF**
130
- Use `llama.cpp` to convert your source HuggingFace model to BF16.
131
- ```bash
132
- python3 llama.cpp/convert_hf_to_gguf.py /path/to/model/ --outfile Model-BF16.gguf --outtype bf16
133
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
- **Step B: Generate Importance Matrix (iMatrix)**
 
 
136
 
137
- HPC includes a native C engine for generating importance matrices (imatrix) used in aggressive LLM weight quantization (Q2_K and below). The engine replaces the standard `llama.cpp` calibration pipeline with an HPC-graph-accelerated tokenizer and forward pass that produces structurally superior importance data.
138
 
139
- **Component files:**
140
- | File | Description |
141
- |:---|:---|
142
- | `LLM/hexstate_quantize.c` | C engine: HPC BPE tokenizer, graph-based forward pass, quantization kernels |
143
- | `LLM/generate_imatrix.py` | Orchestrator: GGUF loading, weight dequantization, C-bridge, imatrix output |
144
- | `LLM/calibration_data.txt` | Calibration corpus (~12.8M characters) |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  ---
147
 
148
- #### Why It Works: Global Geometric Tokenization
149
 
150
- The core innovation is the **HPC BPE tokenizer** — a byte-pair encoding engine that operates on the HPCGraph substrate without regex word boundaries. This seemingly simple architectural choice has profound consequences for quantization quality.
151
 
152
- ##### The Standard Approach: Artificial Isolation
 
 
153
 
154
- Standard tokenizers (tiktoken, SentencePiece, HuggingFace) apply a **regex pre-split** before BPE:
155
 
156
- ```
157
- "Hello world" → regex → ["Hello", " world"] → BPE per word → [15496, 1917]
158
- ```
159
 
160
- The regex fence means:
161
- - **Merges cannot cross word boundaries.** The characters `"o "` (letter-o + space) can never form a token.
162
- - **Each word is tokenized in isolation.** The token for `"Hello"` at position 0 is mathematically independent of any text at position 10,000.
163
- - **Token boundaries are locally determined.** Changing text on page 500 cannot affect how page 1 is tokenized.
164
 
165
- When a standard tokenizer produces 4,096 tokens for imatrix calibration, those tokens are a **shallow, context-free sample** — an arbitrary window of generic subwords that exercises only the activation patterns present in that one fragment of text.
166
 
167
- ##### The HPC Approach: Unrestricted Graph Contraction
 
 
168
 
169
- The HPC BPE tokenizer treats the **entire calibration corpus as a single, continuous phase graph**:
170
 
171
- ```
172
- "Hello world" → 11 sites, each CZ-coupled to its neighbor → global merge competition
173
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
- 1. **Graph Construction** — Each character becomes a site in an `HPCGraph`. Adjacent sites are connected by CZ edges, encoding pair structure as phase entanglement. For a 12.8M character corpus, this creates a graph with 12,799,706 sites and 12,799,705 CZ edges.
176
 
177
- 2. **Global Merge Competition** — Each BPE pass scans every alive position across the entire graph, finds the lowest-rank merge pair that exists *anywhere* in the 12.8M character sequence, and contracts *all* instances simultaneously. This is not local — a merge decision at position 10,000,000 competes with and can preempt merge decisions at position 100.
178
 
179
- 3. **Cascade Propagation** — When a merge at position `i` contracts sites `i` and `i+1` into a single token, site `i`'s neighbor changes. The new adjacent pair `(merged_token, next_neighbor)` may have a very low rank, causing it to fire in the next pass — which creates *another* new pair, propagating further. Without regex boundaries, these cascades propagate freely across spaces, punctuation, and line breaks, threading through the entire document's character geometry.
180
 
181
- 4. **Phase Contraction** — Each merge is simultaneously a **graph contraction** on the HPCGraph. The merged site's local quhit amplitude is updated to a sharp basis state encoding the new token ID (`best_merged % D`), which mathematically severs the entanglement from the consumed CZ edge. The graph tracks the full contraction history.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
- After 21,576 passes (Mistral) or 24,447 passes (Qwen), the 12.8M character graph contracts to ~3.5M–5.2M surviving sites. Each surviving token is not a generic subword — it is **the fixed point of a global contraction** over the entire document's character geometry.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
- ##### Tokens as Global Geometric Frequencies
186
 
187
- In standard NLP, a token represents a word. In the HPC tokenizer, a token represents a **global geometric frequency** — a structural alignment that was carved out by 20,000+ rounds of competition across the full corpus.
188
 
189
- The key consequence: **the first 4,096 tokens of the output already contain the structural dependencies of the entire 12.8M character document.** This is because:
190
 
191
- - The merge rules (pre-trained vocabulary) act as a fixed **geometric frame** — a coordinate system for projecting character sequences into token space.
192
- - The absence of regex boundaries means the projection is **unrestricted** — merges resolve cross-word, cross-line, and cross-paragraph structures that regex-split tokenizers are blind to.
193
- - The specific token IDs and their boundary placements at *any* position are determined by 20,000+ passes of global competition where *every* merge decision was influenced by *every* position in the 12.8M character sequence.
194
- - **You cannot know how the first 500 characters will be tokenized until you have evaluated the last 500 characters.** The tokenization of position 0 is a function of the entire document.
195
 
196
- ##### The Result: Surgical Quantization at 2 Bits
197
 
198
- When these globally-informed tokens are fed through the HPC forward pass for importance collection, the resulting E[x²] statistics are **structurally representative** of the full corpus — even from a single 4,096-token chunk. The cross-layer Belief Propagation then smooths these statistics via residual stream coupling, producing an importance matrix that precisely identifies the load-bearing weights.
 
 
199
 
200
- **Empirical validation:** Mistral-7B-Instruct-v0.3 quantized to Q2_K (87.5% weight compression, 14.5 GB → 3 GB) using a single HPC-calibrated chunk produces:
201
- - Flawless English grammar and complex vocabulary
202
- - Correct factual retrieval from context ("What color was John's suit?" → "Neon green.")
203
- - Coherent multi-sentence reasoning structure
204
 
205
- Standard `llama.cpp` imatrix calibration at Q2_K typically requires hundreds of chunks (500K+ tokens) to avoid catastrophic degradation. The HPC pipeline achieves superior results with **one chunk** because the tokenizer has already done the work of compressing the entire document's structure into that chunk.
 
206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
  ```bash
209
- # Generate HPC importance matrix
210
  python3 LLM/generate_imatrix.py \
211
- model.gguf calibration_data.txt \
212
- -o imatrix.dat --chunks 5 --verbose
 
 
 
213
  ```
214
 
215
- 5 Chunks is the 'sweet spot' for retaining most model intelligence I've found.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
 
217
 
218
- **Step C: Quantize with HPC**
219
- Execute the re-quantizer with your newly generated BF16 GGUF and iMatrix.
220
  ```bash
221
- python3 hexstate_requantize.py Model-BF16.gguf Model-Q2_K-HexState.gguf --keep-metadata --imatrix imatrix.gguf
 
 
 
 
 
 
222
  ```
223
- This automatically routes the attention layers to Q4_0 and FFN/MLP layers to Q2_K using the Shor measurement graph.
224
 
 
225
 
 
226
 
227
- ## 8. Inference & Runtime Configuration
228
 
229
- For correct operation, it is highly recommended to use appropriate chat templates and specific configuration flags in llama.cpp to prevent context length bugs.
 
 
 
 
 
 
 
230
 
231
- **Download Correct Chat Template:**
232
  ```bash
233
- curl -L -o chat_template.jinja "https://huggingface.co/google/gemma-4-26B-A4B-it/raw/main/chat_template.jinja"
 
 
 
 
 
234
  ```
235
 
236
- **Run llama-server:**
 
237
  ```bash
238
- llama-server -m Model-Q2_K-HexState.gguf -ngl 0 -c 4096 --host 0.0.0.0 --port 8989 --jinja --chat-template-file chat_template.jinja --cache-ram 0 -ctxcp 1
 
 
 
 
239
  ```
240
 
241
- **Recommended Sampling Settings:**
242
- - **Temperature:** 0.3–0.4 (Lower reduces sampling noise at low BPW)
243
- - **Top_k:** 20–30 (Narrow sampling for coherence)
244
- - **Top_p:** 0.8–0.85 (Cuts noisy long tail)
245
- - **Repeat_penalty:** 1.15–1.2 (Prevents self-correction loops)
246
 
 
247
 
 
248
 
249
- ## 9. Fidelity Classification & Troubleshooting
 
 
 
 
 
 
 
250
 
251
- The quantizer reports a fidelity rating based on total RMSE across all quantized tensors:
252
 
253
- | Rating | RMSE Threshold | Icon |
254
- |--------|:-:|:-:|
255
- | ULTRA | ≤ 1e-04 | ★★★★ |
256
- | HIGH | ≤ 3e-04 | ★★★☆ |
257
- | GOOD | ≤ 1e-03 | ★★☆☆ |
258
- | STANDARD | > 1e-03 | ★☆☆☆ |
259
 
260
- *Note: Due to anisotropic error shaping, a "GOOD" Shor-quantized model will typically outperform a "HIGH" BP-quantized model on reasoning tasks.*
261
 
262
- ### Common Issues
263
- - **Arabic/Korean characters in output:** The embedded chat template is broken. Use `--chat-template-file` with the correct Jinja template.
264
- - **RAM usage keeps growing:** Use `--cache-ram 0 -ctxcp 1` with llama.cpp to manage sliding window attention.
265
- - **RMSE is higher than standard Q2_K:** This is intentional. The D₆ vesica gate trades total RMSE for computation-aligned error minimization.
266
- - **libhexstate_q2k.so not found:** Make sure to compile the C engine using `make -f makefile.quantize`.
267
 
268
- # How the HPC Engine Makes Global Error Decisions
 
269
 
270
- The HPC (Holographic Phase Contraction) engine takes a fundamentally different approach to LLM weight quantization. Instead of minimizing local error block-by-block, it frames scale selection as a **global quantum-inspired optimization problem**. It maps quantization candidates to a constraint graph and evaluates them using the **Griffiths-Niu Sequential Measurement** protocol derived from Shor's factoring algorithm.
 
 
 
 
 
 
 
 
 
 
271
 
272
- Here is a step-by-step breakdown of how the engine makes global error decisions, directly referencing the implementation in `hexstate_quantize.c`.
273
 
274
- ---
275
 
276
- ## 1. Candidate Generation and D₆ Vesica Scoring
277
- Before any global optimization occurs, the engine needs candidates. For each block of weights, it generates candidate scales (`d` and `dmin`) around a baseline least-squares optimum.
278
-
279
- Instead of scoring these candidates using standard Mean Squared Error (MSE), it uses the **D₆ Vesica Gate**.
280
-
281
- ### Code Citation (`hexstate_quantize.c`, lines ~1420–1432)
282
- ```c
283
- /* Decompose into vesica (DC) and wave (AC) components */
284
- float vesica_err = 0.0f, wave_err = 0.0f;
285
- for (int p = 0; p < half_g; p++) {
286
- float v = e_cur[p] + e_cur[p + half_g];
287
- float w_wave = e_cur[p] - e_cur[p + half_g];
288
- float w_avg = (w_cur[p] + w_cur[p + half_g]) * 0.5f;
289
- vesica_err += v * v * w_avg;
290
- wave_err += w_wave * w_wave * w_avg;
291
- }
292
- /* Triality weighting: penalize vesica 4×, wave 1×. */
293
- err += 0.5f * (4.0f * vesica_err + 1.0f * wave_err);
294
  ```
295
- **Why this matters:** `vesica_err` represents errors that sum together during matrix multiplication, propagating through the network and destroying reasoning. `wave_err` represents errors that naturally cancel out. By penalizing `vesica_err` by 4x, the engine heavily biases towards candidates whose errors cancel out during inference, even if their total Euclidean distance (MSE) from the original weights is larger.
296
 
297
- ## 2. Graph Construction and Boltzmann Amplitudes
298
- The selected candidates and their Vesica errors are grouped into 6 bins (representing the 6 states of a $Z_6$ "quhit" or quantum digit). The engine constructs an `HPCGraph` mapping each block to one or more quhits.
299
 
300
- The errors are transformed into "Boltzmann amplitudes"—representing the likelihood of selecting each state.
301
 
302
- ### Code Citation (`hexstate_quantize.c`, lines ~1502–1506)
303
- ```c
304
- for (int ci = 0; ci < Q4_N_CAND; ci++) {
305
- int qi = Q4_CAND_TO_QUHIT[ci];
306
- amp_re[qi] += exp(-(double)(agg_errors[ci] - min_err) /
307
- (2.0 * (double)temperature));
308
- }
309
- ```
310
 
311
- ## 3. The Griffiths-Niu Sequential Measurement
312
- This is where the global coordination happens. The function `shor_measure_graph` (lines 1166–1314) executes a sequential measurement MSB to LSB. This replaces standard Belief Propagation with a deterministic evaluation that creates massive global correlation.
313
 
314
- For each block $k$ being measured:
315
 
316
- ### A. Neighbor Contribution (Entanglement)
317
- It evaluates how neighboring blocks influence block $k$ by projecting their current amplitudes across the graph edges.
318
- ```c
319
- // hexstate_quantize.c: lines 1217-1221
320
- sr += lr*wr - li*wi;
321
- si += lr*wi + li*wr;
322
- ```
323
 
324
- ### B. Feed-Forward Phase Correction
325
- It applies a phase shift based on the outcomes of all blocks measured before it, a signature trait of the semi-classical QFT used in Shor's algorithm.
326
- ```c
327
- // hexstate_quantize.c: lines 1181-1184
328
- double power = 36.0;
329
- for (int64_t j = k + 1; j < n_sites; j++) {
330
- theta_k += (double)measured_out[j] / power;
331
- power *= 6.0;
332
- }
333
- ```
334
 
335
- ### C. IDFT6 and Constructive Interference
336
- It runs an Inverse Discrete Fourier Transform (IDFT6). Because the neighbor influence ($C_k$) was baked into the amplitudes *before* the IDFT, the IDFT acts as a coherence filter. **It produces constructive interference peaks precisely at the scale candidate that creates the best global configuration.**
337
- ```c
338
- // hexstate_quantize.c: lines 1256-1261
339
- double angle = 2.0 * 3.14159265358979323846 * d * v / 6.0;
340
- double er = cos(angle), ei = sin(angle);
341
- sum_re += alpha_re[d]*er - alpha_im[d]*ei;
342
- sum_im += alpha_re[d]*ei + alpha_im[d]*er;
343
- ```
344
 
345
- ### D. Measurement and Back-Action (The "Magic Pointer")
346
- Once an optimal state is selected (using `argmax` on the squared amplitudes via the Born Rule), the engine calls `shor_collapse_site`.
347
 
348
- This function creates the **global error decision**. It doesn't just lock in block $k$'s choice; it propagates the decision to all unmeasured neighbors.
349
- ```c
350
- // hexstate_quantize.c: lines 1120-1121
351
- double old_re = pq->edge_re[d], old_im = pq->edge_im[d];
352
- pq->edge_re[d] = old_re * w_re - old_im * w_im;
353
- pq->edge_im[d] = old_re * w_im + old_im * w_re;
354
- ```
355
- This back-action fundamentally alters the amplitudes of adjacent blocks, *conditioning* their future quantization choices on the choice just made for block $k$. This creates anti-correlated quantization noise across the entire tensor, ensuring that when the matrix is multiplied against an activation vector, the localized errors cancel each other out.
356
 
357
- ## 4. Beam Search Refinement
358
- Because the measurement is performed left-to-right (MSB to LSB), the sequence is prone to greedy failure. The HPC engine circumvents this using a **24-Beam Hensel Search**.
359
 
360
- Instead of accepting the single path created by the graph collapse, it maintains 24 parallel quantization paths (`Q4_N_BEAMS`). It evaluates candidate extensions by dividing the Shor probability (from the graph marginals) by the local normalized error, advancing the 24 best global configurations simultaneously.
361
 
362
- ### Code Citation (`hexstate_quantize.c`, lines ~1581–1582)
363
- ```c
364
- double ext_err = beams[b].acc_error + cand_errors[blk][c];
365
- extensions[n_ext].score = cand_score[c] / (ext_err + 1e-15);
366
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
 
368
- ## Summary
369
- The global error decision is not an iterative smoothing process (like BP). It is an exact evaluation of quantum interference. By encoding quantization errors into complex amplitudes, passing them through an IDFT6, and forcing neighbors to condition their subsequent scale selections via wave-collapse back-action, the engine ensures that the chosen scales globally cancel each other's destructive matrix-multiplication errors.
 
 
 
370
 
 
371
 
 
372
 
373
- ## 10. License
374
- The quantizer code is part of the HPC project (MIT). Quantized models inherit the license of the base model (e.g., Gemma Terms of Use).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
 
 
 
2
  license: mit
3
  ---
4
 
5
+ # HPC-Quantize
6
 
7
+ ### Holographic Phase Contraction for Ultra-Low-Bit LLM Quantization
8
 
9
+ **HPC-Quantize** is an MIT-licensed research quantization engine for aggressively compressing large language models while preserving inference behavior at extremely low bitrates.
10
 
11
+ HPC was originally developed around a quantum-inspired Shor/Griffiths–Niu measurement formulation. The current engine has evolved beyond that approach: the production quantization path uses a **sequential Sieve**, bounded state back-action, and a **36-state Viterbi optimizer** for Q2 quantization.
12
 
13
+ The central idea remains the same:
14
 
15
+ > **Quantization error is not merely a collection of independent scalar errors. Its structure matters.**
16
 
17
+ Rather than optimizing every block independently, HPC treats quantization as a structured discrete-state optimization problem.
18
 
19
+ ---
20
 
21
+ # What makes HPC different?
22
+
23
+ Conventional low-bit quantization generally asks:
24
+
25
+ $$
26
+ \hat W_i =
27
+ \arg\min_{\hat W}
28
+ \|W_i-\hat W\|^2
29
+ $$
30
+
31
+ for each block independently.
32
+
33
+ HPC instead introduces an explicit state space for quantization candidates and considers:
34
+
35
+ * candidate reconstruction error
36
+ * anisotropic error structure
37
+ * neighboring quantization states
38
+ * state diversity
39
+ * candidate probability
40
+ * cross-block state transitions
41
+ * global sequence coherence
42
+
43
+ The resulting optimization is closer to a graphical-model / sequence-decoding problem than conventional round-to-nearest quantization.
44
+
45
+ Conceptually:
46
+
47
+ ```text
48
+ Original weights
49
+ │
50
+ ▼
51
+ Candidate generation
52
+ │
53
+ ▼
54
+ Error-aware scoring
55
+ │
56
+ ▼
57
+ Six-state HPC representation
58
+ │
59
+ ▼
60
+ Sequential Sieve
61
+ │
62
+ ┌─────────┴─────────┐
63
+ │ │
64
+ state selection neighbor back-action
65
+ │ │
66
+ └─────────┬─────────┘
67
+ ▼
68
+ Q2 state lattice
69
+ │
70
+ ▼
71
+ 36-state Viterbi
72
+ │
73
+ ▼
74
+ Candidate reconstruction
75
+ │
76
+ ▼
77
+ GGUF output
78
+ ```
79
 
80
+ ---
 
 
 
 
 
 
 
81
 
82
+ # The HPC state space
83
 
84
+ HPC represents quantization candidates using a six-state symbolic space:
85
 
86
+ $$
87
+ d\in\{0,1,2,3,4,5\}.
88
+ $$
89
 
90
+ The six states form the basic HPC **quhit**.
91
 
92
+ Candidate parameters are mapped into these six symbolic states through the candidate-to-quhit mapping.
93
 
94
+ This provides a compact representation of the candidate landscape while retaining multiple competing possibilities rather than immediately selecting the local minimum.
 
 
 
 
 
 
95
 
96
+ ---
97
 
98
+ # Q2: the 36-state space
 
 
 
 
99
 
100
+ Q2 quantization has two coupled parameters:
 
 
 
 
 
101
 
102
+ $$
103
+ (d,d_{\min})
104
+ $$
105
 
106
+ Each parameter is projected into six HPC states.
107
 
108
+ Consequently, the joint state is
109
 
110
+ $$
111
+ (q_D,q_M)
112
+ $$
113
 
114
+ with
115
 
116
+ $$
117
+ q_D,q_M\in\{0,\ldots,5\}.
118
+ $$
 
 
 
 
 
119
 
120
+ The complete symbolic Q2 state space is therefore:
121
 
122
+ $$
123
+ 6\times6=36.
124
+ $$
125
 
126
+ The state index is:
127
 
128
+ $$
129
+ s=6q_D+q_M.
130
+ $$
131
 
132
+ Thus:
 
 
 
133
 
134
+ ```text
135
+ dmin
136
+ 0 1 2 3 4 5
137
+ ┌───────────────────
138
+ 0 │ 0 1 2 3 4 5
139
+ 1 │ 6 7 8 9 10 11
140
+ d 2 │12 13 14 15 16 17
141
+ 3 │18 19 20 21 22 23
142
+ 4 │24 25 26 27 28 29
143
+ 5 │30 31 32 33 34 35
144
+ ```
145
 
146
+ Each symbolic state corresponds to the best physical Q2 candidate belonging to that state.
147
 
148
+ ---
149
 
150
+ # Error → probability
151
 
152
+ HPC converts candidate error into a Boltzmann-like amplitude:
 
 
 
 
 
153
 
154
+ $$
155
+ A_i =
156
+ \exp\left(
157
+ -\frac{E_i-E_{\min}}{2T}
158
+ \right).
159
+ $$
160
 
161
+ Squaring gives the corresponding probability:
162
 
163
+ $$
164
+ P_i\propto
165
+ \exp\left(
166
+ -\frac{E_i-E_{\min}}{T}
167
+ \right).
168
+ $$
169
 
170
+ This means the quantizer retains information about the *relative quality* of candidates rather than immediately discarding everything except the MSE winner.
 
 
 
 
171
 
172
+ ---
 
 
 
 
 
173
 
174
+ # The Sieve
175
 
176
+ The current HPC engine replaces the original Shor/Griffiths–Niu measurement path with a classical sequential Sieve.
177
 
178
+ For a state \(d\), its initial probability is:
179
 
180
+ $$
181
+ p_0(d)=|\alpha(d)|^2.
182
+ $$
183
+
184
+ Each neighboring state contributes a compatibility factor.
185
+
186
+ For neighbor \(j\):
187
+
188
+ $$
189
+ B_j(d)
190
+ =
191
+ \sum_w p_j(w)
192
+ \begin{cases}
193
+ 0.85,&w=d\\
194
+ 1,&w\ne d.
195
+ \end{cases}
196
+ $$
197
+
198
+ Because the probabilities sum to one:
199
 
200
+ $$
201
+ B_j(d)=1-0.15p_j(d).
202
+ $$
203
 
204
+ The resulting score is therefore:
205
 
206
+ $$
207
+ S(d)=
208
+ p_0(d)
209
+ \prod_{j\in N}
210
+ \left(1-0.15p_j(d)\right).
211
+ $$
212
+
213
+ The implementation evaluates this in logarithmic form:
214
+
215
+ $$
216
+ \ell(d)=
217
+ \log p_0(d)
218
+ +
219
+ \sum_{j\in N}
220
+ \log\left(1-0.15p_j(d)\right).
221
+ $$
222
+
223
+ This gives the Sieve a simple interpretation:
224
+
225
+ > **A locally strong state remains strong, but states already strongly represented by neighboring blocks are gently penalized.**
226
 
227
  ---
228
 
229
+ # Why 0.85?
230
 
231
+ The factor:
232
 
233
+ $$
234
+ 0.85
235
+ $$
236
 
237
+ controls the strength of the local anti-correlation.
238
 
239
+ If a neighboring site is completely concentrated on state \(d\),
 
 
240
 
241
+ $$
242
+ p_j(d)=1,
243
+ $$
 
244
 
245
+ then:
246
 
247
+ $$
248
+ B_j(d)=0.85.
249
+ $$
250
 
251
+ In log space this is:
252
 
253
+ $$
254
+ \log(0.85)\approx-0.1625.
255
+ $$
256
+
257
+ The Sieve therefore discourages repeated neighboring states without making them impossible.
258
+
259
+ This is intentional.
260
+
261
+ HPC does **not** attempt to force an artificial alternating pattern. It merely introduces a preference for diverse state assignments when alternative candidates remain competitive.
262
+
263
+ ---
264
+
265
+ # The 1.5 Sieve slack
266
+
267
+ After calculating the six state scores, HPC finds:
268
+
269
+ $$
270
+ \ell_{\max}=\max_d\ell(d).
271
+ $$
272
+
273
+ A state survives if:
274
+
275
+ $$
276
+ \ell(d)\geq\ell_{\max}-1.5.
277
+ $$
278
+
279
+ Equivalently:
280
+
281
+ $$
282
+ \frac{S(d)}{S_{\max}}
283
+ \geq e^{-1.5}
284
+ \approx0.2231.
285
+ $$
286
 
287
+ Thus alternatives whose score is at least approximately **22.3% of the best candidate** remain eligible.
288
 
289
+ This prevents premature collapse of the candidate landscape.
290
 
291
+ The Sieve therefore acts as a **soft constraint**, not a hard nearest-neighbor rule.
292
 
293
+ ---
294
+
295
+ # Sequential collapse and back-action
296
+
297
+ Once the current state is selected:
298
+
299
+ $$
300
+ d_k=\arg\max_d S_k(d),
301
+ $$
302
+
303
+ that state is collapsed.
304
+
305
+ The selected state is then propagated into its remaining neighbors.
306
+
307
+ For every live neighbor:
308
+
309
+ $$
310
+ \alpha_j(d_k)
311
+ \leftarrow
312
+ 0.85\alpha_j(d_k).
313
+ $$
314
+
315
+ The neighbor is then renormalized.
316
+
317
+ This creates sequential conditioning:
318
+
319
+ $$
320
+ P(d_1)
321
+ \rightarrow
322
+ P(d_2\mid d_1)
323
+ \rightarrow
324
+ P(d_3\mid d_1,d_2)
325
+ \rightarrow\cdots
326
+ $$
327
+
328
+ The graph therefore does not make independent decisions.
329
+
330
+ Earlier decisions influence later decisions.
331
+
332
+ ---
333
+
334
+ # Q2 Viterbi optimization
335
+
336
+ After the Sieve produces the six-state distributions, Q2 reconstructs the full 36-state lattice.
337
+
338
+ For each symbolic state:
339
+
340
+ $$
341
+ s=(q_D,q_M),
342
+ $$
343
+
344
+ HPC retains the lowest-error physical candidate associated with that state.
345
 
346
+ The Sieve distributions provide a prior:
347
+
348
+ $$
349
+ P(s)
350
+ \approx
351
+ P_D(q_D)P_M(q_M).
352
+ $$
353
+
354
+ The local Viterbi cost is:
355
+
356
+ $$
357
+ C_i(s)=
358
+ E_i(s)
359
+ -
360
+ 0.25\bar E\log P_i(s).
361
+ $$
362
+
363
+ HPC then imposes a transition cost between adjacent blocks:
364
+
365
+ $$
366
+ T(s',s)=
367
+ 0.08\bar E
368
+ \left(
369
+ |q_D-q_D'|
370
+ +
371
+ |q_M-q_M'|
372
+ \right).
373
+ $$
374
+
375
+ This is Manhattan distance on the 6×6 Q2 lattice.
376
+
377
+ The dynamic program is:
378
+
379
+ $$
380
+ DP_i(s)=
381
+ C_i(s)+
382
+ \min_{s'}
383
+ \left[
384
+ DP_{i-1}(s')+T(s',s)
385
+ \right].
386
+ $$
387
+
388
+ The result is a globally optimized sequence of Q2 states rather than independently optimized blocks.
389
+
390
+ ---
391
+
392
+ # Greedy safety override
393
+
394
+ HPC does not blindly trust the global optimizer.
395
+
396
+ After Viterbi selection, the engine compares the selected candidate against the best local reconstruction candidate.
397
+
398
+ If the greedy candidate is sufficiently better:
399
+
400
+ $$
401
+ E_{\text{greedy}}
402
+ <
403
+ 0.95E_{\text{selected}},
404
+ $$
405
+
406
+ the local candidate wins.
407
+
408
+ This prevents global regularization from sacrificing too much actual reconstruction quality.
409
+
410
+ ---
411
 
412
+ # Error geometry
413
 
414
+ HPC can also score candidate errors using the D₆ Vesica decomposition.
415
 
416
+ For paired error components:
417
 
418
+ $$
419
+ v_p=e_p+e_{p+h}
420
+ $$
 
421
 
422
+ and
423
 
424
+ $$
425
+ w_p=e_p-e_{p+h},
426
+ $$
427
 
428
+ the error is separated into:
 
 
 
429
 
430
+ * **Vesica / DC-like error**
431
+ * **wave / AC-like error**
432
 
433
+ The weighted objective is:
434
+
435
+ $$
436
+ E=
437
+ \frac12
438
+ \left(
439
+ 4E_{\mathrm{vesica}}
440
+ +
441
+ E_{\mathrm{wave}}
442
+ \right).
443
+ $$
444
+
445
+ Thus:
446
+
447
+ $$
448
+ \boxed{
449
+ E_{\mathrm{vesica}}
450
+ \text{ receives 4× the penalty of }
451
+ E_{\mathrm{wave}}.
452
+ }
453
+ $$
454
+
455
+ The goal is not simply to minimize Euclidean distance. HPC attempts to distinguish error modes that behave differently during downstream computation.
456
+
457
+ ---
458
+
459
+ # Precision strategy
460
+
461
+ HPC is designed for aggressive low-bit quantization and does not require every tensor to be treated identically.
462
+
463
+ A typical strategy is:
464
+
465
+ | Tensor class | HPC strategy |
466
+ | ------------------------- | ----------------------- |
467
+ | Attention projections | Q4_0 / higher precision |
468
+ | FFN / MLP weights | Q2_K |
469
+ | Expert weights | Q2_K |
470
+ | Embeddings | Preserved / promoted |
471
+ | Norms | Preserved |
472
+ | Router / gate parameters | Preserved or promoted |
473
+ | LM head / tied embeddings | Promoted when required |
474
+
475
+ The exact routing is model-dependent.
476
+
477
+ The purpose is straightforward:
478
+
479
+ > Spend precision where small perturbations are most expensive, and aggressively compress where the model has greater tolerance.
480
+
481
+ ---
482
+
483
+ # Calibration
484
+
485
+ HPC supports importance-matrix calibration for aggressive quantization.
486
+
487
+ A typical workflow is:
488
 
489
  ```bash
 
490
  python3 LLM/generate_imatrix.py \
491
+ model.gguf \
492
+ calibration_data.txt \
493
+ -o imatrix.dat \
494
+ --chunks 5 \
495
+ --verbose
496
  ```
497
 
498
+ The resulting importance data can then be supplied to the re-quantizer.
499
+
500
+ ---
501
+
502
+ # Building
503
+
504
+ Install the required dependencies on Ubuntu/Debian:
505
+
506
+ ```bash
507
+ sudo apt install \
508
+ gcc \
509
+ libgmp-dev \
510
+ libmpfr-dev \
511
+ python3 \
512
+ python3-numpy
513
+ ```
514
 
515
+ Build the HPC engine:
516
 
 
 
517
  ```bash
518
+ make -f makefile.quantize
519
+ ```
520
+
521
+ The build should produce:
522
+
523
+ ```text
524
+ libhexstate_q2k.so
525
  ```
 
526
 
527
+ ---
528
 
529
+ # Quantization
530
 
531
+ Convert the source model to BF16 GGUF using llama.cpp:
532
 
533
+ ```bash
534
+ python3 llama.cpp/convert_hf_to_gguf.py \
535
+ /path/to/model \
536
+ --outfile Model-BF16.gguf \
537
+ --outtype bf16
538
+ ```
539
+
540
+ Generate calibration data:
541
 
 
542
  ```bash
543
+ python3 LLM/generate_imatrix.py \
544
+ Model-BF16.gguf \
545
+ calibration_data.txt \
546
+ -o imatrix.dat \
547
+ --chunks 5 \
548
+ --verbose
549
  ```
550
 
551
+ Run HPC quantization:
552
+
553
  ```bash
554
+ python3 hexstate_requantize.py \
555
+ Model-BF16.gguf \
556
+ Model-Q2_K-HPC.gguf \
557
+ --keep-metadata \
558
+ --imatrix imatrix.gguf
559
  ```
560
 
561
+ ---
 
 
 
 
562
 
563
+ # Historical architecture
564
 
565
+ HPC originally used a quantum-inspired implementation based on:
566
 
567
+ * Z₆ state encoding
568
+ * complex amplitudes
569
+ * graph coupling
570
+ * phase operations
571
+ * IDFT₆
572
+ * Griffiths–Niu-style sequential measurement
573
+ * collapse/back-action
574
+ * beam search
575
 
576
+ That architecture was useful for exploring the underlying hypothesis:
577
 
578
+ > **quantization states can be treated as interacting discrete variables rather than independent rounding decisions.**
 
 
 
 
 
579
 
580
+ The current Sieve architecture keeps the useful structural concepts while replacing the Fourier/phase machinery with explicit probability scoring and dynamic programming.
581
 
582
+ In other words:
 
 
 
 
583
 
584
+ ```text
585
+ Original HPC
586
 
587
+ error
588
+ ↓
589
+ complex amplitudes
590
+ ↓
591
+ phase graph
592
+ ↓
593
+ IDFT₆
594
+ ↓
595
+ measurement
596
+ ↓
597
+ back-action
598
 
 
599
 
600
+ Current HPC
601
 
602
+ error
603
+ ↓
604
+ probability
605
+ ↓
606
+ Sieve
607
+ ↓
608
+ bounded back-action
609
+ ↓
610
+ 36-state lattice
611
+ ↓
612
+ Viterbi
 
 
 
 
 
 
 
613
  ```
 
614
 
615
+ The latter is substantially easier to analyze, reproduce, and tune.
 
616
 
617
+ ---
618
 
619
+ # Design philosophy
 
 
 
 
 
 
 
620
 
621
+ HPC is built around several principles.
 
622
 
623
+ ### 1. Do not assume minimum MSE is the whole objective
624
 
625
+ A quantization configuration with slightly higher local error can still be preferable if its error structure is better behaved globally.
 
 
 
 
 
 
626
 
627
+ ### 2. Preserve alternatives
 
 
 
 
 
 
 
 
 
628
 
629
+ Low-bit quantization has a highly discrete error landscape. Prematurely selecting one candidate can eliminate useful configurations.
 
 
 
 
 
 
 
 
630
 
631
+ ### 3. Model interactions explicitly
 
632
 
633
+ Quantization blocks do not exist in complete isolation during inference.
 
 
 
 
 
 
 
634
 
635
+ HPC therefore gives neighboring state assignments an explicit influence.
 
636
 
637
+ ### 4. Encourage diversity without forcing it
638
 
639
+ The Sieve's 0.85 penalty is deliberately bounded.
640
+
641
+ It discourages repeated state assignments but does not prohibit them.
642
+
643
+ ### 5. Separate local inference from global optimization
644
+
645
+ The Sieve supplies local state information.
646
+
647
+ Viterbi then searches the resulting 36-state Q2 lattice globally.
648
+
649
+ ### 6. Keep a reconstruction-quality escape hatch
650
+
651
+ The 5% greedy override prevents the global model from making obviously bad local decisions.
652
+
653
+ ---
654
+
655
+ # What HPC is — and isn't
656
+
657
+ HPC is:
658
+
659
+ * an experimental ultra-low-bit quantization engine
660
+ * MIT licensed
661
+ * designed for GGUF/llama.cpp workflows
662
+ * focused on Q2-class compression
663
+ * based on structured discrete-state optimization
664
+ * capable of combining local reconstruction error with state interactions
665
+
666
+ HPC is **not**:
667
 
668
+ * a claim that LLM inference is literally quantum computation
669
+ * a replacement for llama.cpp itself
670
+ * a guarantee of improved perplexity on every model
671
+ * a conventional round-to-nearest quantizer
672
+ * dependent on quantum hardware
673
 
674
+ The current Sieve is entirely classical.
675
 
676
+ The "quantum-inspired" terminology refers to the historical mathematical lineage and the state/graph representation—not to a requirement for quantum hardware.
677
 
678
+ ---
679
+
680
+ # License
681
+
682
+ HPC-Quantize is released under the **MIT License**.
683
+
684
+ Quantized model files remain subject to the license and terms of the underlying base model.
685
+
686
+ ---
687
+
688
+ # Status
689
+
690
+ HPC-Quantize is research software.
691
+
692
+ The quantization architecture is intentionally experimental, particularly at extremely low bitrates such as Q2.
693
+
694
+ Results should therefore be evaluated using:
695
+
696
+ * perplexity
697
+ * task benchmarks
698
+ * generation quality
699
+ * long-context behavior
700
+ * mathematical reasoning
701
+ * coding benchmarks
702
+ * model-specific evaluations
703
+
704
+ rather than RMSE alone.
705
+
706
+ ---
707
+
708
+ ## The short version
709
+
710
+ Conventional Q2:
711
+
712
+ $$
713
+ \boxed{
714
+ \text{pick the lowest-error candidate}
715
+ }
716
+ $$
717
+
718
+ HPC:
719
+
720
+ $$
721
+ \boxed{
722
+ \text{score candidates}
723
+ \rightarrow
724
+ \text{encode state}
725
+ \rightarrow
726
+ \text{sieve}
727
+ \rightarrow
728
+ \text{condition neighbors}
729
+ \rightarrow
730
+ \text{search the 36-state lattice}
731
+ \rightarrow
732
+ \text{select a globally coherent configuration}
733
+ }
734
+ $$
735
 
736
+ **HPC-Quantize treats ultra-low-bit quantization as a structured state-selection problem, not merely a rounding problem.**