- Important note
- Block output example
- SMQ: Closed-Form Quadratic Quantizer & Architecture-Agnostic Algebraic QAT for GGUF
- TQ Format information
- Table of Contents
- 1. Architecture & Module Overview
- 2. Supported Quantization Formats & Block Layouts
- 3. Direct Converter Mathematics (
smq_gguf_convert_live.py) - 4. Algebraic QAT Mathematics (
smq_qat.py)- Streaming Gram Statistics
- Closed-Form Scale & Offset Normal Equations
- Metric-Coupled Lattice Snapping
- Wiener Target & Sub-Block Cholesky OBQ/GPTQ Error Feedback
- Boundary-Preserving Coordinate Descent & Coupled Scale Relaxation
- Full Empirical-Bayes Prior Annealing
- Closed-Form FP32 RMSNorm Co-Adaptation (Hadamard Gram System)
- Intermediate (
o_proj) & Final (down_proj) Residual Absorption - Final LM Head (
output_norm.weight+output.weight) Algebraic Fit - Per-Row Dual Guards & Converter Round-Trip Verification
- 5. Architecture-Agnostic GGUF Execution Engine
- 6. SMQ Studio GUI (
smq_gui.py) - 7. CLI Usage & Workflows
- 8. CLI Reference
- Table of Contents
Important note
Some forward passes are NOT compatible with this method of QAT, I am working on it presently..
Block output example
(Q2K) Before training:
(Q2K) After training:
SMQ: Closed-Form Quadratic Quantizer & Architecture-Agnostic Algebraic QAT for GGUF
SMQ is a mathematical quantization and quantization-aware adaptation (QAT) suite for GGUF language models. It combines a closed-form quadratic weight factorizer (smq_gguf_convert_live.py), an architecture-agnostic closed-form algebraic QAT engine (smq_qat.py / train_smq_qat.py), and a PyQt5 desktop studio (smq_gui.py).
Unlike conventional QAT pipelines that rely on stochastic gradient descent, backpropagated surrogates, optimizer states, and learning-rate schedules, SMQ-QAT is 100% closed-form and algebraic:
- Sub-block scales and offsets are solved directly from activation Gram matrices ($C = X^T X$, $G = X^T Y$) via Jacobi-preconditioned normal equations.
- Scales and offsets are projected onto the discrete GGUF parameter lattice under the Schur-complement curvature metric with scale-to-offset residual compensation.
- Discrete codes are updated jointly using sub-block Cholesky error feedback (OBQ/GPTQ) around the ridge-regularized Wiener optimal weight target $W^*$, followed by boundary-preserving coordinate descent and coupled scale relaxation.
- Upstream FP32 RMSNorm weights (
attn_norm,ffn_norm,output_norm) are co-adapted in closed form via a $d \times d$ Hadamard Gram system ($H_{\text{norm}} = C \odot \sum_k W_k^T W_k$), providing continuous per-input-channel post-compensation at zero GGUF bit overhead. - Intermediate (
attn_output/o_proj) and block-final (ffn_down/down_proj) projections absorb upstream quantization residuals directly in the residual stream, and the final language modeling head (output_norm.weight+output.weight) is fitted in closed form on the final block's output activations. - Every candidate state is guarded per output row on both fitting tokens and held-out validation tokens, and verified through a bit-exact FP16 + converter round-trip check, guaranteeing monotonic error reduction on every row.
Runtime note for
TQ*_128formats: StandardQ2_K,Q3_K, andQ4_0outputs load in stockllama.cpp. GGUFs using the denseTQ9_128,TQ27_128, orTQ81_128formats (GGML type IDs 44β46) require the patched llama.cpp-tr runtime (https://github.com/ternii-ai/tritq-vllm, Apache-2.0).
TQ Format information
The TQ* series format is made by https://huggingface.co/Ternii
It is highly superior to Q2K/3K/4 per bit used.
Table of Contents
- Architecture & Module Overview
- Supported Quantization Formats & Block Layouts
- Direct Converter Mathematics (
smq_gguf_convert_live.py) - Algebraic QAT Mathematics (
smq_qat.py)- Streaming Gram Statistics
- Closed-Form Scale & Offset Normal Equations
- Metric-Coupled Lattice Snapping
- Wiener Target & Sub-Block Cholesky OBQ/GPTQ Error Feedback
- Boundary-Preserving Coordinate Descent & Coupled Scale Relaxation
- Full Empirical-Bayes Prior Annealing
- Closed-Form FP32 RMSNorm Co-Adaptation (Hadamard Gram System)
- Intermediate (
o_proj) & Final (down_proj) Residual Absorption - Final LM Head (
output_norm.weight+output.weight) Algebraic Fit - Per-Row Dual Guards & Converter Round-Trip Verification
- Architecture-Agnostic GGUF Execution Engine
- SMQ Studio GUI (
smq_gui.py) - CLI Usage & Workflows
- CLI Reference
1. Architecture & Module Overview
| File | Role |
|---|---|
smq_gguf_convert_live.py |
Direct GGUF Quantizer & Codec Engine. Implements closed-form quadratic/WLS factorization, metric-coupled lattice snapping, bit-exact encoders/decoders for Q2_K, Q3_K, Q4_0, TQ9_128, TQ27_128, and TQ81_128, imatrix readers (.imatrix.gguf and legacy .dat), and streaming GGUF export. |
smq_qat.py |
Algebraic QAT Engine & Agnostic GGUF Runtime. Implements sequential blockwise closed-form QAT, Cholesky GPTQ + coordinate-descent code solvers, Hadamard-Gram RMSNorm co-adaptation, intermediate/final residual absorption, LM-head fitting, preflight validation, and the architecture-agnostic _GGUFNativeBlockModel execution engine. |
train_smq_qat.py |
CLI Entrypoint for SMQ-QAT. Command-line interface exposing block ranges, calibration corpus settings, mixed-precision --tensor-type overrides, and algebraic solver hyperparameters. |
smq_gui.py |
SMQ Studio (PyQt5 GUI). Interactive tensor planner, live GiB/BPW estimator, role/regex filter, mixed-precision preset bar, and background worker thread for Direct Quantization and Algebraic QAT + Quantization. |
smq.py |
Standalone PyTorch Reference Kernel. Compact PyTorch reference implementation of coupled Gram-folded Q2_K projection. |
Input GGUF (F16 / BF16 / Q8_0 / ...)
β
βββ [1] Preflight Check (python smq_qat.py model.gguf)
β βββ Maps all blk.<N>.* and model-level tensors (known tables + agnostic fallback)
β βββ Verifies bit-exact GGUF <-> PyTorch transform invertibility
β βββ Verifies parameter names & shapes against the target block model on meta device
β
βββ [2] Algebraic QAT (train_smq_qat.py / smq_gui.py)
β βββ Rebuilds BPE or SentencePiece tokenizer directly from GGUF metadata
β βββ Embeds calibration sequences (+ optional token_embd_norm.weight RMSNorm)
β βββ For each block b = 0 .. N_real - 1:
β β βββ Computes exact FP32 teacher block targets (and maintains depth-residual bank)
β β βββ Discovers execution order & shared-input projection groups automatically
β β βββ Streams Gram matrices C = X_q^T X_q, G = X_q^T Y_t (with intermediate/final residual absorption)
β β βββ Solves (scales -> Cholesky GPTQ codes -> scales -> CD codes -> scales) across prior schedule
β β βββ Verifies per-row improvement on fit + held-out tokens AND FP16 converter round-trip
β β βββ Co-adapts upstream FP32 RMSNorms via closed-form Hadamard Gram solve
β β βββ Propagates quantized student activations to block b + 1
β βββ Fits final output_norm.weight + output.weight (LM head) in vocab chunks
β βββ Exports adapted F16 staging GGUF (with trained FP32 norms & F16 linear weights)
β
βββ [3] SMQ Converter (smq_gguf_convert_live.py / smq_gui.py)
βββ Factorizes each eligible tensor to its target format (with automatic 256 -> 128 -> 32 qk fallback)
βββ Packs native GGUF block payloads with per-block RTN safeguard
βββ Writes final quantized GGUF + optional CSV/JSON telemetry report
2. Supported Quantization Formats & Block Layouts
SMQ supports six block quantization formats uniformly (--qtype) or in arbitrary per-tensor combinations (--tensor-type PATTERN=QTYPE):
Format (--qtype) |
Block Size (qk) |
Sub-Blocks | Bytes / Block | Nominal BPW | Code Alphabet $q$ | Reconstruction Formula | GGML Type ID |
|---|---|---|---|---|---|---|---|
q2_k (default) |
256 |
16 Γ 16 |
84 B |
2.625 bpw | ${0, 1, 2, 3}$ | $\hat{w}{j,a} = (d \cdot \text{ls}j), q{j,a} - (d{\min} \cdot \text{lm}_j)$ | 10 (Q2_K) |
q3_k |
256 |
16 Γ 16 |
110 B |
3.4375 bpw | ${-4, \dots, +3}$ | $\hat{w}_{j,a} = (d \cdot \text{sc}j), q{j,a},\quad \text{sc}_j \in [-32, 31]$ | 11 (Q3_K) |
q4_0 |
32 |
1 Γ 32 |
18 B |
4.500 bpw | ${-8, \dots, +7}$ | $\hat{w}_a = d , q_a$ | 2 (Q4_0) |
tq9_128β |
128 |
1 Γ 128 |
54 B |
3.375 bpw | ${-4, \dots, +4}$ (9 levels) | $\hat{w}_a = d , q_a$ (5 base-9 digits / 16-bit word) | 44 (TQ9_128) |
tq27_128β |
128 |
1 Γ 128 |
80 B |
5.000 bpw | ${-13, \dots, +13}$ (27 levels) | $\hat{w}_a = d , q_a$ (5 base-27 digits / 24-bit word) | 45 (TQ27_128) |
tq81_128β |
128 |
1 Γ 128 |
106 B |
6.625 bpw | ${-40, \dots, +40}$ (81 levels) | $\hat{w}_a = d , q_a$ (5 base-81 digits / 32-bit word) | 46 (TQ81_128) |
β Requires the patched llama.cpp-tr runtime.
3. Direct Converter Mathematics (smq_gguf_convert_live.py)
Q2_K Closed-Form Quadratic Factorization & Schur-Complement Snapping
In Q2_K, each 256-weight super-block is partitioned into 16 sub-blocks of 16 weights. Within sub-block $j \in {0, \dots, 15}$, weights are reconstructed as:
where $d, d_{\min} \in \text{FP16}$ are super-block scales and $\text{ls}_j, \text{lm}_j \in {0, \dots, 15}$ are 4-bit unsigned nibbles.
Given optional per-weight importance factors $w_{j,i} > 0$, _factorize_chunk executes a three-candidate closed-form pipeline per 256-weight block:
RTN Seed & Second Moments: Computes the initial min/max RTN lattice $(d^{(0)}, d_{\min}^{(0)}, \text{ls}^{(0)}, \text{lm}^{(0)}, q^{(0)})$ and accumulates the sub-block second moments $(S_w, S_x, S_{xx}, S_q, S_{qq}, S_{xq})$, allowing exact SSE evaluation without materializing residual arrays: $$\text{SSE}(s, o) = S_{xx} - 2s S_{xq} + 2o S_x + s^2 S_{qq} - 2so S_q + S_w o^2$$
Exact 2Γ2 Sub-Block WLS Projection (
_ls_grid_fit): Projects $x$ onto $\operatorname{span}{q^{(0)}, 1}$ in closed form: $$s_1 = \frac{S_w S_{xq} - S_q S_x}{S_w S_{qq} - S_q^2}, \qquad o_1 = \frac{S_q S_{xq} - S_{qq} S_x}{S_w S_{qq} - S_q^2}$$ with boundary refit $s_1 = S_{xq} / S_{qq}$ whenever $o_1 < 0$ is clamped to $0$.Metric-Coupled Schur-Complement Lattice Snapping & Alternating Refinement: The 2Γ2 sub-block Hessian of $\frac{1}{2}\text{SSE}(s, o)$ is: $$A = \begin{pmatrix} A_{ss} & A_{so} \ A_{so} & A_{oo} \end{pmatrix} = \begin{pmatrix} S_{qq} & -S_q \ -S_q & S_w \end{pmatrix}$$
- Candidate A (Canonical Snap): Snaps $(s_1, o_1)$ directly at $\alpha = 1.0$, which acts as a bit-exact identity transform on weights already lying on a canonical QAT
Q2_Klattice. - Candidate B (Schur-Complement Metric-Coupled Snap): Snaps $s_1$ over multiplier grid $\alpha \in {1.0, 0.72, 0.78, 0.84, 0.88, 0.92, 0.95, 0.98, 1.02}$ weighted by the marginal Schur-complement curvature $W_s = A_{ss} - A_{so}^2 / A_{oo}$, canonicalizes $(d, \text{ls})$ so $\max_j \text{ls}j = 15$, shifts the offset to its conditional optimum given the snapped scale: $$o{\text{adj}} = \max!\left(o_1 - \frac{A_{so}}{A_{oo}}(s_{\text{snap}} - s_1),; 0\right)$$ and snaps $o_{\text{adj}}$ under $W_o = A_{oo}$.
- Candidate C (Second Alternating WLS + Schur Snap Round): Re-derives codes $q^{(1)}$ on the winning grid, refits continuous $(s_3, o_3)$, and performs a second Schur-coupled snap.
- Per-Block Monotonic Guard: Each 256-weight super-block selects the minimum-SSE candidate among ${\text{RTN}, A, B, C}$, guaranteeing $\text{SSE}{\text{SMQ}} \le \text{SSE}{\text{RTN}}$ on every block.
- Candidate A (Canonical Snap): Snaps $(s_1, o_1)$ directly at $\alpha = 1.0$, which acts as a bit-exact identity transform on weights already lying on a canonical QAT
Q3_K, Q4_0, and TQ*_128 WLS Factorizers & Sub-Peak Recovery
Q3_K(_factorize_q3k_chunk): Tests both $+s_{\text{pos}}$ and $-s_{\text{neg}}$ asymmetric $[-4, 3]$ seeds plus exact integer-peak divisor seeds $\pm \max(|x_j|) / k$ for $k \in {4, 3, 2, 1}$, runs 3 per-sub-block WLS iterations, fits the signed FP16 super-block scale $d$ over $\pm d_{\text{base}}$ and multipliers ${1.0, 0.94, 0.97, 1.03}$, and guards per block against RTN.Q4_0&TQ*_128(_factorize_single_scale_chunk): Tests exact integer-peak FP16 scales $\text{fp16}(\max|x| / k)$ across $k \in [k_{\max}-16, k_{\max}]$ alongside RTN and $\tanh$-companded analog seeds with 4 WLS iterations. Testing exact integer-peak divisors guarantees that any QAT-adapted block whose discrete codes happen to peak at $|q| = k < q_{\max}$ is recovered losslessly during post-QAT conversion.
Importance Matrix (imatrix) Integration
Both smq_gguf_convert_live.py and smq_qat.py accept --imatrix in either:
- GGUF imatrix format (
.imatrix.ggufwith*.imatrix_sum2and*.imatrix_counts), or - Legacy
llama.cppbinaryimatrix.datformat.
Per-channel ($E[x_i^2]$) or per-expert-channel importance weights are normalized and tiled across rows into the sub-block WLS moments.
Tensor Eligibility & Automatic Block-Size Fallback
A GGUF tensor is eligible for quantization (tensor_is_eligible) when:
- It has $\ge 2$ GGML dimensions with no degenerate dimension (
shape[1:]contains no1), - Its row length
ne[0]and total element count are divisible by the format's block sizeqk(256,128, or32), and - It is not a structural FP32 tensor (
*_conv.weight,*_conv1d.weight,*_clip.weight,*_res_query.weight,loop_msg_query.weight,attn_rel_bias.weight,ffn_gate_inp.weight,ffn_gate_inp_shexp.weight,*norm.weight, or*.bias).
When a weight matrix's ne[0] is not divisible by the default format's qk=256 (for example, Inkling-2-Mini's blk.*.ffn_down_exps.weight with ne[0] = 1152 = 9 Γ 128, or blk.*.loop_*_ctrl_{gain,forget}.weight with ne[0] = 64 = 2 Γ 32), fallback_qtype_for_tensor automatically falls back to tq9_128/tq27_128 (qk=128) or q4_0 (qk=32) across the converter, QAT trainer, and GUI.
4. Algebraic QAT Mathematics (smq_qat.py)
Streaming Gram Statistics
For a linear projection $W \in \mathbb{R}^{m \times d}$ mapping student input activations $X_q \in \mathbb{R}^{N \times d}$ to target outputs $Y \in \mathbb{R}^{N \times m}$, the output-error objective is:
where:
are accumulated by streaming over the calibration sequences in micro-batches. Projections that consume the exact same input tensor (e.g., q_proj + k_proj + v_proj, gate_proj + up_proj, or Inkling-2's q_proj + rel_proj + sink_proj + o_gate_proj) are grouped automatically by _discover_groups and share a single Gram matrix $C$.
Closed-Form Scale & Offset Normal Equations
For row $r$ with $J = d / 16$ sub-blocks and fixed codes $q_{r,j} \in {0, 1, 2, 3}^{16}$, the weight row is $w_r = M_r \theta_r$ where $\theta_r = [s_{r,0}, \dots, s_{r,J-1}, o_{r,0}, \dots, o_{r,J-1}]^T \in \mathbb{R}^{2J}$. Minimizing the output error over $\theta_r$ yields the $2J \times 2J$ normal equations (_ls_fit_gram):
Each row's system is Jacobi-equilibrated to unit diagonal ($D_r = \operatorname{diag}(A_r)^{1/2}$, $\tilde{A}_r = D_r^{-1} A_r D_r^{-1}$) and solved with a proximal ridge prior toward the current scales $\theta_r^{(0)}$:
via batched Cholesky factorization (_cholesky_solve_unit_diag, with automatic ridge escalation and transparent CPU/Accelerate fallback on Apple Metal MPS). For zero-offset formats (Q3_K, Q4_0, TQ*_128), _ls_fit_gram_linear solves the reduced $J \times J$ system $A_r = U_r^T C U_r$.
Metric-Coupled Lattice Snapping
Continuous scales $(s_{r,j}, o_{r,j})$ are snapped to the GGUF lattice (_snap_scales) using each sub-block's $2 \times 2$ diagonal block $(A_{ss}, A_{so}, A_{oo})$ of $A_r$:
- $s$ is snapped under the Schur-complement curvature $W_s = A_{ss} - A_{so}^2 / A_{oo}$ over $\alpha \in {1.0, 0.72, 0.78, 0.84, 0.88, 0.92, 0.95, 0.98, 1.02}$ and canonicalized to $\max_j \text{ls}_j = 15$.
- $o$ is shifted by the conditional optimum $o_{\text{adj}} = \max(o - (A_{so} / A_{oo})(s_{\text{snap}} - s), 0)$ to absorb the mean scale-rounding residual before snapping $(d_{\min}, \text{lm})$ under $W_o = A_{oo}$.
Wiener Target & Sub-Block Cholesky OBQ/GPTQ Error Feedback
Before the iterative phases begin, _prepare_gptq computes the ridge-regularized Wiener optimal weight matrix $W^* \in \mathbb{R}^{m \times d}$ and the upper triangular Cholesky factor $U$ of the inverse regularized Gram matrix:
Given candidate scales $(s_c, o_c)$, _gptq_codes (and _gptq_codes_linear for zero-offset formats) quantizes 16 weights (one sub-block) at a time:
- Within sub-block $j$ (
b0:b1), each column $a \in {0, \dots, 15}$ rounds to the nearest valid lattice code and propagates its intra-sub-block error $-((w_a - \hat{w}a) / U{a,a}) U_{a, a+1:b1}$ to the remaining columns of the sub-block. - Active sub-blocks enforce the converter's boundary code condition $\min(q_j) = 0, \max(q_j) = 3$ on the extreme continuous ratios (with distinct indices $\text{idx}_0 \ne \text{idx}_3$).
- The exact sub-block triangular residual $E_{\text{sub}} = (W_{\text{sub}} - \hat{W}{\text{sub}}) U{\text{sub}}^{-1}$ is propagated to all remaining columns
b1:dvia a single blocked GEMM $W_{:, b1:} \leftarrow W_{:, b1:} - E_{\text{sub}} U_{b0:b1, b1:}$.
Boundary-Preserving Coordinate Descent & Coupled Scale Relaxation
In each phase:
- Coupled
(scales -> GPTQ codes -> scales)evaluation: Candidate scales $(s_c, o_c)$ are evaluated both with the existing codes $q$ and with freshly solved Cholesky GPTQ codes $q_g = \text{_gptq_codes}(W^*, U, s_c, o_c)$ followed by a coupled scale refit $(s_{g2}, o_{g2}) = \text{_ls_fit_gram}(C, G, q_g, \dots)$, preventing rows from being rejected when scale updates require code co-adaptation. - Boundary-Preserving Coordinate Descent (
_cd_codes/_cd_codes_linear): Sweeps sub-block by sub-block in the full Gram metric $C$, enforcing $\min(q_j) = 0, \max(q_j) = 3$ on active sub-blocks before propagating the exact delta $\Delta W_{\text{sub}} C_{b0:b1, :}$ across the row, followed by a coupled post-CD scale relaxation.
Full Empirical-Bayes Prior Annealing
To stabilize high-dimensional projections (ffn_down, $d > 8192$) in the nullspace of the calibration tokens while still reaching the unregularized activation optimum, _build_prior_schedule anneals the empirical-Bayes diagonal prior:
across all ls_iters phases down to $\gamma = 0.0$ (e.g., $\gamma \in (2.5, 0.75, 0.15, 0.0)$ for $d > 8192$ and $(2.0, 0.75, 0.15, 0.0)$ for $d \le 8192$, plus an optional alternate-ridge phase ls_ridge_alt).
Closed-Form FP32 RMSNorm Co-Adaptation (Hadamard Gram System)
In GGUF, 1D RMSNorm tensors (attn_norm.weight, ffn_norm.weight, output_norm.weight, etc.) are stored in full FP32. Once an input group $\mathcal{G}$ (such as {q_proj, k_proj, v_proj} or {gate_proj, up_proj}) has been quantized to $W_q^{(k)}$ ($k \in \mathcal{G}$), _find_group_input_norm checks whether an upstream 1D RMSNorm exclusively produces the group's input tensor and verifies its multiplicative parameterization (standard $w$ or zero-centered $1 + w$).
Scaling the RMSNorm output channels by $g \in \mathbb{R}^d$ yields the exact quadratic objective across all projections in $\mathcal{G}$:
where:
By Schur's product theorem, $H_{\text{norm}} \succeq 0$. _solve_hadamard_norm_scale evaluates global scalar gain, diagonal Jacobi shrinkage, and full $d \times d$ Cholesky solves $(H_{\text{norm}} + \lambda D) g = b_{\text{norm}} + \lambda D \mathbf{1}_d$, accepting the candidate $g \in [0.85, 1.15]^d$ that minimizes held-out validation error while reducing training error.
Intermediate (o_proj) & Final (down_proj) Residual Absorption
- Intermediate Post-Attention Residual Absorption:
_find_intermediate_residual_targetuses a 2-token perturbation probe to detect whether an intermediate single-projection group (such asself_attn.o_projorlinear_attn.out_proj) adds with an identity residual connection into the input of the next sub-layer (post_attention_layernorm). When detected,_capture_intermediate_residualsets the projection's target to $Y = h_{\text{mid,fp}} - \text{res}_{\text{stu}}$, canceling upstream attention and norm drift before the nonlinear MLP. - Final Block-Output Residual Absorption: On the final projection of the block (
mlp.down_proj),_can_absorb_block_residualverifies identity residual addition into the block output and sets $Y = Y_{\text{block,fp}} - \text{res}_{\text{stu}}$ sodown_projabsorbs cumulative intra-block quantization residuals in closed form.
Final LM Head (output_norm.weight + output.weight) Algebraic Fit
After the final decoder block blk.{N_real - 1} completes, _train_final_head streams the post-output_norm $d \times d$ Gram matrices:
(plus their held-out counterparts $C_v, C_{v,qt}, C_{v,tt}$), where $d = d_{\text{model}}$ (requiring only $3 \times d^2 \times 4\text{ B} \approx 192\text{ MB}$ at $d=4096$, independent of vocabulary size):
- Pre-aligns
output_norm.weightagainst $W_{\text{out,fp}}$ via_solve_hadamard_norm_scale. - Fits
output.weightin 2,048-row vocabulary chunks using $G_{\text{chunk}} = C_{qt} W_{\text{chunk,fp}}^T$ and $\text{yy}{\text{chunk}} = \operatorname{rowsum}((W{\text{chunk,fp}} C_{tt}) \odot W_{\text{chunk,fp}})$. - Post-polishes
output_norm.weightagainst the quantized $W_{\text{out,stu}}$ and writeshead.safetensors, whichexport_ggufwrites back intooutput_norm.weight(FP32) andoutput.weight(FP16).
Per-Row Dual Guards & Converter Round-Trip Verification
- Per-Row Dual Guard: Every candidate row $r$ is accepted if and only if it improves or preserves both the unregularized training Gram error and the held-out validation error: $$\text{take}r = (e{c,r} \le e_{\text{best},r}) ;\wedge; (v_{c,r} \le v_{\text{best},r})$$
- Per-Row Converter Round-Trip Guard: At the end of
_fit_moduleand_fit_module_linear, the fitted weights $W_{\text{best}}$ are passed throughquantize_dequantize_torchwith FP16 rounding (round_dtype=torch.float16) β simulating the exact FP16 GGUF export followed bysmq_gguf_convert_live.py. Any row whose round-tripped lattice regresses relative to the initial baseline is reverted individually. - Block-Level Revert Guard: If the entire block's held-out relative error after
manager.refresh()exceeds the untouched plain-SMQ baseline,_restore_blockreverts the block to plain SMQ.
5. Architecture-Agnostic GGUF Execution Engine
Native GGUF PyTorch Block Builder (_GGUFNativeBlockModel)
SMQ-QAT does not require a model's general.architecture to appear in a hardcoded HuggingFace whitelist or to be installed in transformers:
- Any tensor suffix
blk.<N>.<suffix>not found in_SUFFIX_TO_HFis dynamically mapped tocustom_projs.<stem>.weight(kind="proj"for 2D weight matrices withne[0] >= 32),custom_norms.<stem>.weight, orcustom_aux.<stem>. _meta_layer_scalartransparently reads both scalar metadata and per-layer array metadata (such as per-layerattention.head_count,attention.head_count_kv,attention.sliding_window_pattern,feed_forward_length, orexpert_used_count), and_arch_configinfers any missing dimensions directly from the GGUF tensor shapes._GGUFNativeBlockModelconstructs the exact PyTorch module hierarchy (nn.Linear,_GGUFNativeRMSNorm,nn.Conv1d,_GGUFNativeExperts, and parameter buffers) directly from the GGUF tensor specs and executes the forward graph adaptively based on which submodules are present (separateq/k/vvs fusedattn_qkv.weight, RoPE, QK-norm, SubLN, post-attention/post-FFN norms, gated attention output, dense SwiGLU/MLP, 2D/3D MoE experts, Gated-Delta-Net SSM, or Inkling2/Inkling2-Loop).
First-Class Inkling / Inkling-2 / Inkling-2-Loop (Inkling-mini) Support
_GGUFNativeDecoderLayer implements the complete Inkling-2 / Inkling-2-Loop (general.architecture = inkling2_loop, e.g. Inkling-2-Mini-Q8_0.gguf) execution graph matching llama.cpp (inkling2.cpp & inkling2-loop.cpp):
- Normed Token Embeddings: Applies
token_embd_norm.weightRMSNorm immediately aftertoken_embd.weightlookup. - Depth-Wise Block Attention Residuals: Maintains the cross-block state bank
_depth_block_statesat macro-block boundaries (block % attn_res.block_size == 0, default 6) and mixes earlier block states with current hidden states viaattn_res_query.weight(1 query on SWA blocks, 3 queries(Q, K, V)on full-attention blocks),ffn_res_query.weight, and finaloutput_res_query.weight. - Looped Core Message Gates: On looped core blocks (
loop.start .. loop.end - 1, blocks6..17), computes cross-pass messages fromloop_msg_query.weight(2304, 4)and applies the rank-64 LoRA message gates (loop_{q,k,v,ffn}_ctrl_{down,gain,forget}.weight), automatically training*_ctrl_down(ne[0]=4608) asQ2_Kand*_ctrl_{gain,forget}(ne[0]=64) via fallback toQ4_0. - Causal Short Convolutions & Dynamic Taps: Executes static grouped
Conv1dshort convolutions (attn_k_conv,attn_v_conv,attn_post_conv,ffn_post_conv) with $(x + \text{conv}(x)) / \sqrt{K + 1}$ scaling, and full-attention input-dependent dynamic convolution taps (attn_k_conv_proj,attn_v_conv_proj+static_weight) with $(x + \text{conv}(x)) / \sqrt{2K + 1}$ scaling. - L2 Head Clipping, Log-Position Scaling, Relative Bias & Sinks: Applies learned scale + L2 clipping (
attn_q_clip,attn_rel_clip,qk_clip,relative_clip), unweighted V-head RMSNorm, full-attention logarithmic position scaling $\tau(p) = 1 + \alpha \ln(\max(1, (p+1)/n_{\text{floor}}))$, distance-gathered relative position bias (attn_rel,attn_rel_bias), per-query attention sink logits (attn_sink_proj), and sigmoid attention output gating (attn_gate). - Situ-Softcapped 128-Expert MoE: Executes sigmoid routing with
exp_probs_b.biasandexpert_weights_scale = 8.0, and softcapped Situ activation: $$\operatorname{Situ}(g, u) = \beta_g \tanh!\left(\frac{g}{\beta_g}\right) \sigma(g) \cdot \beta_u \tanh!\left(\frac{u}{\beta_u}\right), \qquad \beta_g = 4.0,; \beta_u = 25.0$$ withffn_gate_up_exps.weight(ne[0]=2304) trained asQ2_Kandffn_down_exps.weight(ne[0]=1152) automatically trained asTQ9_128(qk=128).
Single-Pass Mixture-of-Experts (MoE) Activation Caching
In MoE blocks (3D stacked ffn_gate_up_exps.weight / ffn_down_exps.weight, 3D ffn_{gate,up,down}_exps.weight, or 2D split ffn_{gate,up,down}.<e>.weight), _install_split_moe_experts splits experts into per-expert 2D nn.Linear modules with deterministic routing lock (_forced_top_k_index).
During _collect_group_stats, _moe_cache captures the post-ffn_norm hidden states and top_k_index at the MoE module entry in one single forward pass across the calibration corpus instead of running $2 \times E$ separate block forwards. Each expert $e \in {0, \dots, E-1}$ slices its routed tokens directly from _moe_cache (automatically falling back to the full post-norm token distribution when an expert has sparse routing $< 16$ training or $< 4$ validation tokens), ensuring all $E$ experts are trained in seconds with zero skipped experts.
Gated-Delta-Net / Linear Attention Hybrid Support
For hybrid recurrent/attention architectures (qwen3next, qwen35, qwen35moe), _build_spec handles merged tensors (attn_qkv_gate.weight, ssm_beta_alpha.weight), grouped-to-tiled V-head reordering (_v_reorder / _v_unreorder), ssm_a = -exp(A_log) log-domain inversion, and ssm_conv1d.weight kernel reshaping, all verified bitwise during preflight.
6. SMQ Studio GUI (smq_gui.py)
Launch the desktop interface with:
python smq_gui.py [optional_model.gguf]
Key capabilities:
- Interactive Tensor Planner Table: Displays every tensor's block index, role, GGML shape, parameter count, source type, and an eligible format dropdown (
Q2_K,Q3_K,Q4_0,TQ9_128,TQ27_128,TQ81_128,Copy). Structural FP32 tensors (*_conv,*_clip,*_res_query,loop_msg_query,attn_rel_bias,ffn_gate_inp,*norm) are automatically locked toCopy. - Live Output Size & BPW Calculator: Updates estimated output GiB and effective bits-per-weight in real time as tensor formats are changed.
- Quick Presets & Regex/Role Filtering: Filter by regex (e.g.,
^blk\.(0|5)\.orffn_down) or role dropdown, and apply bulk formats or one-click mixed-precision presets (All Eligible,Block Tensors Only,Mixed: Q2_K + Q3_K (ffn_down & out),Mixed: Q2_K + TQ9_128 (ffn_down & out)), with automatic256 -> 128 -> 32block-size fallback. - Dual Execution Modes:
- Direct SMQ Quantizer (No QAT): Converts the source GGUF directly to the table's per-tensor format plan.
- Algebraic QAT + Quantize: Runs closed-form blockwise QAT (with
token_embd_norm.weight, depth-residual state bank, RMSNorm co-adaptation, and final LM-head fitting), exports the adapted F16 staging GGUF, and converts it using the table plan.
7. CLI Usage & Workflows
Preflight Verification
Before running a multi-hour QAT job, validate the entire GGUF tensor mapping, transform invertibility, and PyTorch block model compatibility in seconds:
python smq_qat.py /path/to/model.gguf
Example outputs:
QAT preflight: OK (24 blocks, 74 distinct tensor types, 5 layer type(s), 74 tensors inverted + self-checked)
Running Algebraic QAT + Conversion
- Run Algebraic QAT to produce the adapted F16 staging GGUF:
python train_smq_qat.py \
--gguf /path/to/Inkling-2-Mini-Q8_0.gguf \
--corpus /path/to/calibration_data.txt \
--output /path/to/Inkling-2-Mini-qat-f16.gguf \
--qtype q2_k \
--num-seqs 32 \
--seq-len 512 \
--micro-batch 2 \
--ls-iters 4 \
--cd-sweeps 2 \
--device cuda:0
- Convert the adapted F16 GGUF to the final quantized GGUF:
python smq_gguf_convert_live.py \
/path/to/Inkling-2-Mini-qat-f16.gguf \
--qtype q2_k \
--output-gguf /path/to/Inkling-2-Mini-SMQ-Q2K.gguf
(Note: Tensors with ne[0]=1152 like ffn_down_exps.weight automatically fall back to TQ9_128, or you can force Q4_0 for stock llama.cpp compatibility via --tensor-type ffn_down_exps=q4_0 in both steps.)
Running Direct SMQ Conversion
# Uniform Q2_K conversion with optional importance matrix
python smq_gguf_convert_live.py /path/to/model.gguf \
--qtype q2_k \
--imatrix /path/to/model.imatrix.gguf \
--output-gguf /path/to/model-smq-q2k.gguf
# Mixed precision: Q2_K default, Q3_K on ffn_down and output.weight
python smq_gguf_convert_live.py /path/to/model.gguf \
--qtype q2_k \
--tensor-type ffn_down=q3_k \
--tensor-type output.weight=q3_k \
--output-gguf /path/to/model-smq-mixed.gguf
Self-Tests
Verify bit-exact packing, decoding, and WLS factorization guards across all six formats (Q2_K, Q3_K, Q4_0, TQ9_128, TQ27_128, TQ81_128):
python smq_gguf_convert_live.py --self-test
8. CLI Reference
train_smq_qat.py Key Arguments
| Flag | Default | Description |
|---|---|---|
--gguf PATH |
(required) | Input source GGUF model. |
--corpus PATH |
(required) | Calibration text/markdown/JSONL file or directory. |
--output PATH |
(required) | Output adapted F16 staging GGUF path. |
--qtype QTYPE |
q2_k |
Default target lattice (q2_k, q3_k, q4_0, tq9_128, tq27_128, tq81_128). |
--tensor-type PAT=QTYPE |
[] |
Repeatable per-tensor or per-role format override (or PAT=Copy to exclude). |
--imatrix PATH |
None |
Optional importance matrix (.imatrix.gguf or .dat). |
--blocks LO HI |
all real blocks | Half-open block range [LO, HI) to adapt. |
--num-seqs N |
32 |
Number of calibration sequences sampled from --corpus. |
--seq-len L |
512 |
Token length of each calibration sequence. |
--micro-batch B |
4 |
Sequences per forward pass during Gram streaming. |
--ls-iters N |
4 |
Number of prior-annealed closed-form scale + GPTQ/CD rounds. |
--ls-ridge R |
1e-3 |
Proximal ridge on the unit-diagonal scale normal equations. |
--ls-ridge-alt R |
3e-2 |
Extra final scale solve with alternate ridge (0 disables). |
--cd-sweeps K |
2 |
Coordinate-descent sweeps over discrete codes per round (0 disables). |
--cd-damp D |
0.01 |
Relative diagonal step damping in coordinate descent. |
--cd-ridge R |
0.0 |
Proximal ridge toward starting weights during coordinate descent. |
--device DEV |
cuda |
Training device (auto, cuda, cuda:0, mps, metal, cpu). |
smq_gguf_convert_live.py Key Arguments
| Flag | Default | Description |
|---|---|---|
gguf |
(positional) | Input GGUF file (omit with --self-test). |
--output-gguf PATH |
None |
Output quantized GGUF file path. |
--qtype QTYPE |
q2_k |
Default target quantization format. |
--tensor-type PAT=QTYPE |
[] |
Repeatable per-tensor/role format override (or PAT=Copy). |
--imatrix PATH |
None |
Optional importance matrix (.imatrix.gguf or .dat). |
--list-tensors |
False |
List eligible and skipped tensors with target formats and exit. |
--chunk-blocks N |
32768 |
Number of quantization blocks factorized per vectorized NumPy batch. |
--no-rtn-guard |
False |
Disable the per-block RTN SSE guard. |
--self-test |
False |
Run internal packing/decoding and factorization verification suite. |

