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:

image

(Q2K) After training:

image

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*_128 formats: Standard Q2_K, Q3_K, and Q4_0 outputs load in stock llama.cpp. GGUFs using the dense TQ9_128, TQ27_128, or TQ81_128 formats (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

  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)
  5. Architecture-Agnostic GGUF Execution Engine
  6. SMQ Studio GUI (smq_gui.py)
  7. CLI Usage & Workflows
  8. 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: x^j,i=sjqj,iβˆ’oj,sj=dβ‹…lsjβ‰₯0,oj=dmin⁑⋅lmjβ‰₯0,qj,i∈{0,1,2,3}\hat{x}_{j,i} = s_j q_{j,i} - o_j, \qquad s_j = d \cdot \text{ls}_j \ge 0, \quad o_j = d_{\min} \cdot \text{lm}_j \ge 0, \quad q_{j,i} \in \{0, 1, 2, 3\} 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:

  1. 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$$

  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$.

  3. 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_K lattice.
    • 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.

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:

  1. GGUF imatrix format (.imatrix.gguf with *.imatrix_sum2 and *.imatrix_counts), or
  2. Legacy llama.cpp binary imatrix.dat format.

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:

  1. It has $\ge 2$ GGML dimensions with no degenerate dimension (shape[1:] contains no 1),
  2. Its row length ne[0] and total element count are divisible by the format's block size qk (256, 128, or 32), and
  3. 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: L(W)=βˆ₯XqWTβˆ’Yβˆ₯F2=βˆ‘r=1m(wrTCwrβˆ’2wrTG:,r+yyr)\mathcal{L}(W) = \| X_q W^T - Y \|_F^2 = \sum_{r=1}^m \left( w_r^T C w_r - 2 w_r^T G_{:,r} + \text{yy}_r \right) where: C=XqTXq∈RdΓ—d,G=XqTY∈RdΓ—m,yyr=βˆ₯Y:,rβˆ₯22C = X_q^T X_q \in \mathbb{R}^{d \times d}, \qquad G = X_q^T Y \in \mathbb{R}^{d \times m}, \qquad \text{yy}_r = \| Y_{:,r} \|_2^2 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): Ar=(UrTCUrβˆ’UrTCVβˆ’VTCUrVTCV),br=((qrβŠ™G:,rT)116βˆ’G:,rT116)A_r = \begin{pmatrix} U_r^T C U_r & -U_r^T C V \\ -V^T C U_r & V^T C V \end{pmatrix}, \qquad b_r = \begin{pmatrix} (q_r \odot G_{:,r}^T)\mathbf{1}_{16} \\ -G_{:,r}^T \mathbf{1}_{16} \end{pmatrix} 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)}$: (A~r+Ξ»I)ΞΈ~r=Drβˆ’1br+Ξ»DrΞΈr(0)(\tilde{A}_r + \lambda I) \tilde{\theta}_r = D_r^{-1} b_r + \lambda D_r \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$:

  1. $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$.
  2. $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: (C+Ξ»diag⁑(C))(Wβˆ—)T=G+Ξ»diag⁑(C)WfpT,(C+Ξ»diag⁑(C))βˆ’1=UTU(C + \lambda \operatorname{diag}(C)) (W^*)^T = G + \lambda \operatorname{diag}(C) W_{\text{fp}}^T, \qquad (C + \lambda \operatorname{diag}(C))^{-1} = U^T U 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:d via 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:

  1. 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.
  2. 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: Cγ=C+γdiag⁑(C),Gγ=G+γdiag⁑(C)WfpTC_\gamma = C + \gamma \operatorname{diag}(C), \qquad G_\gamma = G + \gamma \operatorname{diag}(C) W_{\text{fp}}^T 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}$: βˆ‘k∈Gwkβˆ₯Xqdiag⁑(g)(Wq(k))Tβˆ’Ykβˆ₯F2=gTHnormgβˆ’2gTbnorm+const\sum_{k \in \mathcal{G}} w_k \| X_q \operatorname{diag}(g) (W_q^{(k)})^T - Y_k \|_F^2 = g^T H_{\text{norm}} g - 2 g^T b_{\text{norm}} + \text{const} where: Hnorm=CβŠ™(βˆ‘k∈Gwk(Wq(k))TWq(k))∈RdΓ—d,bnorm=βˆ‘k∈Gwkrowsum⁑ ⁣(GkβŠ™(Wq(k))T)∈RdH_{\text{norm}} = C \odot \left(\sum_{k \in \mathcal{G}} w_k (W_q^{(k)})^T W_q^{(k)}\right) \in \mathbb{R}^{d \times d}, \qquad b_{\text{norm}} = \sum_{k \in \mathcal{G}} w_k \operatorname{rowsum}\!\left(G_k \odot (W_q^{(k)})^T\right) \in \mathbb{R}^d 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_target uses a 2-token perturbation probe to detect whether an intermediate single-projection group (such as self_attn.o_proj or linear_attn.out_proj) adds with an identity residual connection into the input of the next sub-layer (post_attention_layernorm). When detected, _capture_intermediate_residual sets 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_residual verifies identity residual addition into the block output and sets $Y = Y_{\text{block,fp}} - \text{res}_{\text{stu}}$ so down_proj absorbs 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: C=XqTXq,Cqt=XqTXt,Ctt=XtTXtC = X_q^T X_q, \qquad C_{qt} = X_q^T X_t, \qquad C_{tt} = X_t^T X_t (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):

  1. Pre-aligns output_norm.weight against $W_{\text{out,fp}}$ via _solve_hadamard_norm_scale.
  2. Fits output.weight in 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}})$.
  3. Post-polishes output_norm.weight against the quantized $W_{\text{out,stu}}$ and writes head.safetensors, which export_gguf writes back into output_norm.weight (FP32) and output.weight (FP16).

Per-Row Dual Guards & Converter Round-Trip Verification

  1. 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})$$
  2. Per-Row Converter Round-Trip Guard: At the end of _fit_module and _fit_module_linear, the fitted weights $W_{\text{best}}$ are passed through quantize_dequantize_torch with FP16 rounding (round_dtype=torch.float16) β€” simulating the exact FP16 GGUF export followed by smq_gguf_convert_live.py. Any row whose round-tripped lattice regresses relative to the initial baseline is reverted individually.
  3. Block-Level Revert Guard: If the entire block's held-out relative error after manager.refresh() exceeds the untouched plain-SMQ baseline, _restore_block reverts 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_HF is dynamically mapped to custom_projs.<stem>.weight (kind="proj" for 2D weight matrices with ne[0] >= 32), custom_norms.<stem>.weight, or custom_aux.<stem>.
  • _meta_layer_scalar transparently reads both scalar metadata and per-layer array metadata (such as per-layer attention.head_count, attention.head_count_kv, attention.sliding_window_pattern, feed_forward_length, or expert_used_count), and _arch_config infers any missing dimensions directly from the GGUF tensor shapes.
  • _GGUFNativeBlockModel constructs 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 (separate q/k/v vs fused attn_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.weight RMSNorm immediately after token_embd.weight lookup.
  • Depth-Wise Block Attention Residuals: Maintains the cross-block state bank _depth_block_states at macro-block boundaries (block % attn_res.block_size == 0, default 6) and mixes earlier block states with current hidden states via attn_res_query.weight (1 query on SWA blocks, 3 queries (Q, K, V) on full-attention blocks), ffn_res_query.weight, and final output_res_query.weight.
  • Looped Core Message Gates: On looped core blocks (loop.start .. loop.end - 1, blocks 6..17), computes cross-pass messages from loop_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) as Q2_K and *_ctrl_{gain,forget} (ne[0]=64) via fallback to Q4_0.
  • Causal Short Convolutions & Dynamic Taps: Executes static grouped Conv1d short 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.bias and expert_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$$ with ffn_gate_up_exps.weight (ne[0]=2304) trained as Q2_K and ffn_down_exps.weight (ne[0]=1152) automatically trained as TQ9_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 to Copy.
  • 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)\. or ffn_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 automatic 256 -> 128 -> 32 block-size fallback.
  • Dual Execution Modes:
    1. Direct SMQ Quantizer (No QAT): Converts the source GGUF directly to the table's per-tensor format plan.
    2. 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

  1. 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
  1. 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.
Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support