Nairod785 commited on
Commit
18ddfa9
·
verified ·
1 Parent(s): 33228ed

Upload QUANTIZATION_ARMS.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. QUANTIZATION_ARMS.md +86 -194
QUANTIZATION_ARMS.md CHANGED
@@ -1,197 +1,89 @@
1
  # Per-Tensor Quantization Arms — Methodology & Principles
2
 
3
- > Companion document for [Confucius4-R2T2-Q4_K_M-GGUF](https://huggingface.co/Nairod785/Confucius4-R2T2-Q4_K_M-GGUF) detailing the per-tensor quantization arms method, `--keep-type` mechanics, validation protocols, and generalized learnings.
4
-
5
- # Per-tensor quantization arms
6
-
7
- `docs/tools/quantization.md` covers `transcribe-quantize`, which applies a
8
- **preset** to a whole file according to a bucket policy. That is the right tool
9
- for shipping a model and it is the tool that should stay the default.
10
-
11
- This document covers the other thing: building **arms** — variants that differ
12
- from each other in exactly one block, so that the effect of quantizing that
13
- block can be attributed. A preset cannot express "everything at Q6_K except
14
- `mlp.down_proj`, which stays at Q4_K", so the arms were built with the external
15
- `audiocpp_gguf` converter from the read-only `audio.cpp` tree.
16
-
17
- The tooling here is a means, not a policy. Per-tensor control is what you reach
18
- for when a preset's floor is too conservative and you want to know *which* block
19
- is actually paying for it.
20
-
21
- ## Why the bundled quantizer can't do this
22
-
23
- | | `transcribe-quantize` | `audiocpp_gguf` |
24
- |---|---|---|
25
- | unit of control | whole file | whole file **plus** per-tensor overrides |
26
- | selection | bucket policy (`Linear`, `Embed`, `ConvPw`, `Conv`, `Norm`) | exact source tensor name, or trailing-`*` prefix |
27
- | type menu | F16, Q4_0/1, Q5_0/1, Q8_0, Q6_K, Q5_K_M, Q4_K_M | orig, f16, bf16, q8_0, q2_k…q6_k |
28
- | accepts non-allowlisted types | no — loader allowlist enforced | yes; output is not guaranteed loadable |
29
- | output guarantee | loads in `transcribe` | **none** — verify before trusting |
30
-
31
- The last row matters. `transcribe-quantize` only emits types the loader
32
- allowlist accepts (`kQuantLinearTypes`), so its output is loadable by
33
- construction. `audiocpp_gguf` will happily write a package the loader rejects.
34
- Every arm must therefore be opened and run, not just built.
35
-
36
- ## `--keep-type` semantics
37
-
38
- The whole method rests on this flag, and its behaviour is not obvious:
39
-
40
- - **`--type <t>` is all-or-nothing per file.** It sets the default for every
41
- tensor the converter is willing to quantize.
42
- - **`--keep-type <name>=<t>` overrides one tensor.** The base `--type` plus N
43
- overrides *is* the arm — there is no other axis.
44
- - **Names are matched against the SOURCE safetensors tensor name**, not the
45
- name the tensor ends up with in the GGUF. Getting this backwards silently
46
- produces an arm with no overrides applied and the wrong size.
47
- - **A pattern is either an exact name or a trailing-`*` prefix.** There is no
48
- mid-string wildcard. `thinker.model.layers.*.mlp.down_proj.weight` does *not*
49
- work; you must enumerate the 28 names.
50
- - **First matching rule wins.** Order is significant when rules overlap.
51
- - **An override to a quantized type THROWS rather than falling back** if the
52
- tensor is not 2D float or `shape.back() % blck_size != 0`. This is the trap
53
- behind prefix rules: a `*-proj.weight`-style prefix that also catches a 1D
54
- bias aborts the build instead of quietly skipping it. Enumerate exactly.
55
- - **An override beats the `use_f16_lookup` heuristic.** The converter pins
56
- embedding-like tensors (`embed`, `codebook`) to F16 on its own. An explicit
57
- override wins over that pin — which is the only reason the tied embedding is
58
- available as a size lever at all.
59
-
60
- ## Enumerating names, and checking the census
61
 
62
- Because there is no mid-string wildcard, protecting half a model means listing
63
- its matmuls by exact name. Do not retype them. Dump them from a package the
64
- converter already got right — the Q8_0 reference — by reading the GGUF header
65
- directly.
66
-
67
- `scripts/quant/quantized-names.js` does this: it reads the tensor-info table,
68
- prints the names whose dtype is quantized, and takes an optional scope prefix to
69
- filter.
70
-
71
- The build script must then **assert a census** before invoking the converter —
72
- a count per block, aborting on mismatch. The failure mode this prevents is a
73
- build that succeeds while quantizing the wrong set of tensors, which looks fine
74
- until you notice the size is wrong. For R2T2 the census is tower 147, attention
75
- 112, gate/up 56, down 28.
76
-
77
- ## Command-line length
78
-
79
- 147 exact-name overrides do not fit in the Windows `cmd` limit (8191
80
- characters). Drive the converter from bash, not `cmd.exe`, or the arm silently
81
- truncates and comes out wrong. This is a real limit, not a style preference.
82
-
83
- ## Verify what you built, not what you meant to build
84
-
85
- After building an arm, read its dtype table back off disk with
86
- `scripts/quant/dtype-table.js`: one representative tensor per block, asserting
87
- uniformity within the block and flagging `MIXED` where the tower legitimately
88
- mixes. Never infer an arm's composition from the build script's intent — the
89
- flags are easy to get subtly wrong and the build does not complain.
90
-
91
- The unit of a documented arm is the **dtype table**, not the command line that
92
- produced it. Two arms can have identical command lines and different contents if
93
- a name failed to match.
94
-
95
- ## Validation protocol
96
-
97
- ### `jfk` + `zh` is not a screen
98
-
99
- This is the most expensive lesson here. R2T2 is trained to score high on English
100
- and Chinese, so those are its two *easiest* inputs. An arm can match the
101
- reference exactly on both and still be broken.
102
-
103
- Concretely: `q5_k` matched Q8_0 exactly on jfk+zh and switched to English on
104
- Russian. E, D5 and N all passed jfk+zh and switched to English on German — three
105
- arms that were reported as passing on the strength of jfk+zh alone.
106
-
107
- **A probe only tests what the model is bad at.** Pick a clip in a language the
108
- model was *not* optimized for. For R2T2 that is German.
109
-
110
- ### Use the model's own language detection
111
-
112
- `transcribe-cli` logs `detected-language:`. Grep that instead of scoring the
113
- transcript with a heuristic — it is the model's own answer about which language
114
- it thinks it is transcribing, which is precisely the failure being tested, and
115
- it is one grep. Across 8 arms × 5 French clips it read `fr` in 39/40 runs, and
116
- the single `en` was the real failure.
117
-
118
- Note the CLI runs these on **CPU** (`backend: CPU`), roughly 3× realtime, so a
119
- sweep is cheap but not instant.
120
-
121
- ### Compare against the highest-precision reference, not against each other
122
-
123
- Arms should be diffed against F16 or Q8_0, never ranked against one another —
124
- two arms agreeing on wrong output is not evidence of anything.
125
-
126
- Textual comparison needs **three levels**, because they mean different things
127
- (`scripts/quant/fr-diff.js` implements them):
128
-
129
- | level | normalization | what a difference means |
130
- |---|---|---|
131
- | `raw` | none | punctuation and casing the model chose differently — benign |
132
- | `strict` | lowercase, punctuation stripped | orthography, including accents (`voilà` → `voila`) |
133
- | `loose` | strict + diacritics folded (NFD, drop `\p{Mn}`) | **content** drift — a dropped or substituted word |
134
-
135
- Only `loose` answers the question. Without the diacritic fold, `voila`/`voilà`
136
- is flagged as content drift when it is the same word. That is the same
137
- orthographic class as Japanese `五十円`/`50円` and `いけない`/`行けない` — different
138
- renderings of identical content, not a quality difference.
139
-
140
- ### Empty output is a failure, not a pass
141
-
142
- A quantized matmul can fail hard and produce *nothing*. A harness that only
143
- diffs text will not notice; a harness that reads the exit code will see success.
144
- Check that output is non-empty before comparing it.
145
-
146
- ### Read output files only after the process exits
147
-
148
- **A harness trap that produced a wrong published conclusion.** Polling for an
149
- output file and diffing it while the CLI is still writing yields an **empty
150
- transcript, which is indistinguishable from the "empty output" cliff.** An arm
151
- was falsely reported as emitting nothing until the file settled. Wait on process
152
- exit, not on file existence.
153
-
154
- ## Speed
155
-
156
- Interleave arms rather than running all reps of one and then all reps of the
157
- next — thermal and cache state drift over a sweep and will look like a real
158
- difference. Four reps, drop the first, average the remaining three. Revert any
159
- win below the noise floor; a change that cannot be distinguished from noise is
160
- not a win.
161
-
162
- Speed is only meaningful next to quality. The two fastest arms in the R2T2
163
- ladder are both broken, so a speed table without a quality column is worse than
164
- no table.
165
-
166
- ## What generalizes beyond R2T2
167
-
168
- 1. **Quantization error is cumulative, not per-tensor.** There is no independent
169
- per-tensor floor to look up. Block A at Q4_K may be fine alone and fatal in
170
- combination with block B at Q4_K, because the budget is spent network-wide.
171
- 2. **Blocks differ in cost per bit, and the ordering is architectural.** What
172
- matters is whether a block's error writes into the residual stream or passes
173
- through a bounded nonlinearity. `down_proj` writes into the residual, so its
174
- error compounds through every remaining layer — the strictest floor.
175
- `gate_proj`/`up_proj` pass through SwiGLU, which bounds the error — a looser
176
- floor. Embeddings are a lookup: error enters once and leaves once and does
177
- not compound at all — the loosest floor. This is why llama.cpp's Q4_K_M rule
178
- protects `down_proj`, and it is worth checking that rule's step size against
179
- your own model rather than assuming it transfers.
180
- 3. **Low-bit matmuls are a cliff, not a slope.** Q3_K on a matmul produced empty
181
- output in every attempt. There is no gradual degradation to trade against
182
- size — the arm works or it does not, and the transition is fast.
183
- 4. **Floors can be non-monotone.** A *higher*-precision block can fail where a
184
- lower-precision one passes. Do not assume that stepping one block up in
185
- precision buys safety, and do not treat a single passing arm as having
186
- margin.
187
- 5. **A tied embedding is a real size lever, and an unusual one.** When the
188
- embedding matrix also serves as the output projection head, quantizing it
189
- changes the logits directly. The converter's automatic F16 pinning of
190
- embedding tensors must be overridden explicitly to exploit this.
191
- 6. **A quant can preserve text on one language and switch language on another.**
192
- Quality is not a scalar. Text similarity on the training distribution tells
193
- you almost nothing about behaviour off it.
194
- 7. **Better precision is not always slower in the ways you expect.** Optimizer
195
- coverage per type dominates: Q5_K was *slower* than Q8_0 and Q6_K because its
196
- kernel is less well optimized. A quant ladder must be measured, not derived
197
- from bit width.
 
1
  # Per-Tensor Quantization Arms — Methodology & Principles
2
 
3
+ > Companion technical document for [Confucius4-R2T2-Q4_K_M-GGUF](https://huggingface.co/Nairod785/Confucius4-R2T2-Q4_K_M-GGUF).
4
+ > Details the general per-tensor quantization arms methodology, `--keep-type` semantics, cross-lingual validation protocols, and core architectural rules.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ ---
7
+
8
+ ## 1. Why Per-Tensor Arms?
9
+
10
+ Standard model quantization tools apply uniform presets (e.g. standard Q4_K_M or Q5_K_M) across entire layers or architectures. For many speech models, however, uniform quantization either fails catastrophic quality checks or leaves substantial memory optimization on the table.
11
+
12
+ Building **quantization arms** means creating experimental variants that differ in exactly one block or layer type, isolating the quality, memory, and speed impact of each architectural component:
13
+ - Isolating which blocks represent non-negotiable precision floors.
14
+ - Finding which blocks can be aggressively quantized without measurable loss.
15
+ - Measuring real kernel execution speed across mixed-precision representations.
16
+
17
+ ---
18
+
19
+ ## 2. Converter Overrides & Mechanics
20
+
21
+ Per-tensor control requires specifying precision at the individual weight level:
22
+ - **Base Type:** Sets the baseline default type for all quantizable weights in the graph.
23
+ - **Explicit Overrides (`--keep-type <tensor>=<type>`):** Selectively overrides the precision of specific tensors.
24
+ - **Source Naming Contract:** Override rules must target the exact source parameter names (e.g. `thinker.model.layers.0.mlp.down_proj.weight`), not transformed runtime names.
25
+ - **Asserting Tensor Census:** Always assert a strict tensor census per architectural block before and after conversion to prevent silent fallbacks or unmatched patterns:
26
+ - Tower: 147 tensors
27
+ - Attention (`q`, `k`, `v`, `o_proj`): 112 tensors
28
+ - Gate / Up (`gate_proj`, `up_proj`): 56 tensors
29
+ - Down (`down_proj`): 28 tensors
30
+ - Embeddings: 1 tensor
31
+ - **Command-Line Limits:** When passing dozens of tensor overrides on Windows systems, drive conversion scripts from bash or JSON specifications rather than `cmd.exe` to avoid the 8191-character command-line length truncation limit.
32
+
33
+ ---
34
+
35
+ ## 3. Verification Protocol: Verify What Was Built
36
+
37
+ Never infer a model arm's composition from the conversion arguments alone—conversion flags can fail silently without throwing errors.
38
+ Always verify the resulting GGUF by inspecting the tensor header table:
39
+ 1. Verify that all 28 `down_proj` weights are assigned their target type.
40
+ 2. Confirm that `embed_tokens` was successfully overridden from the default F16 pin to the desired low-bit type.
41
+ 3. Confirm that sensitive encoder layers retain their target mixed precision.
42
+
43
+ ---
44
+
45
+ ## 4. Cross-Lingual Validation Protocol
46
+
47
+ A critical lesson learned during quantization validation:
48
+
49
+ ### English and Chinese Are Not a Screen
50
+ Speech models like R2T2 are trained with massive data allocations for English and Chinese, making them the model's most resilient input distributions.
51
+ - Multiple quantization configurations matched the Q8_0 reference baseline on English (`jfk`) and Chinese (`zh`), but completely broke down on non-target languages.
52
+ - For example, naive Q5_K matched Q8_0 on English and Chinese, but silently flipped to English when fed Russian audio.
53
+ - Other experimental configurations passed English and Chinese tests, but emitted English translations when given German audio.
54
+
55
+ ### The Non-Target Probe Principle
56
+ Always evaluate quantization quality against languages with smaller training footprints (e.g. German, French, Russian). If a model switches languages or drops tokens on secondary languages, its representation space has degraded.
57
+
58
+ ### Automated Detection
59
+ Rather than manually inspecting hours of transcripts, automated validation checks should monitor:
60
+ 1. **Detected Language Output:** Grep the model runtime's detected language tag (`detected-language:`). A switch from `de` or `fr` to `en` immediately identifies representation collapse.
61
+ 2. **Three-Tier Word Diffing:**
62
+ - **Raw:** Exact matching including punctuation and casing differences (benign).
63
+ - **Strict:** Lowercase, punctuation-stripped matching.
64
+ - **Loose:** Diacritics folded (NFD normalization). Flags true **content drift** (omitted, substituted, or hallucinated words).
65
+ 3. **Empty Output Detection:** Low-bit matmuls can collapse abruptly to empty strings. Ensure output files are confirmed non-empty before running text diffs.
66
+
67
+ ---
68
+
69
+ ## 5. Architectural Principles That Generalize
70
+
71
+ The findings from the R2T2 quantization campaign reveal principles that apply broadly to modern transformer and speech architectures:
72
+
73
+ 1. **Quantization Error is Cumulative, Not Per-Tensor:**
74
+ There is no fixed precision floor for a block in isolation. A block at Q4_K may work perfectly alone, but cause collapse when another block is also reduced. The total error budget is shared network-wide.
75
+
76
+ 2. **Residual Stream Writes Compound Strictly:**
77
+ Blocks that write directly into the residual stream (`down_proj`) compound numerical error through every subsequent layer. Consequently, `down_proj` imposes the strictest precision requirement (Q6_K for R2T2).
78
+
79
+ 3. **Non-Linearities Bound Error Propagation:**
80
+ Projections that feed into bounded activation functions (such as SwiGLU in `gate_proj` and `up_proj`) tolerate lower bitwidths (Q4_K) because the non-linearity bounds error growth.
81
+
82
+ 4. **Lookup Tables Do Not Compound:**
83
+ Token embeddings (`embed_tokens`) are accessed via table lookup. Their quantization error is introduced once per token and does not propagate recurrently. Aggressively quantizing embeddings (even to Q2_K) saves substantial memory with virtually no degradation.
84
+
85
+ 5. **Low-Bit Matmul Cliff:**
86
+ Matmul quantization does not degrade gracefully below Q4_K. Q3_K matmuls in R2T2 produced immediate empty output cliffs.
87
+
88
+ 6. **Speed Does Not Track Bit Width Alone:**
89
+ Kernel optimization quality dominates hardware throughput. Q5_K performed ~20% slower than Q8_0 due to non-vectorized paths, whereas highly optimized Q4_K and Q6_K routines provided significant speedups.