Repository navigation
quantize: add option to automatically choose optimal quant types to reach a file/bpw target size at lowest error - #15550
Conversation
|
Sharing some like-for-like test results showing that this approach produces, in the majority of the cases, better quality models compared to naive quantisation (i.e. simply running standard To reduce the duration of the tests, I have chosen two small but representative models: Llama-3.2-1B ("classic" transformer architecture) and Huihui-MoE-1.2B-A0.6B (typical Mixture or Experts). The test protocol for each is:
Llama-3.2-1B results:
Huihui-MoE-1.2B-A0.6B results:
PPL: the smaller the better; 𝜌PPL: the higher the better; KLD: the smaller the better; In bold: best quality NoteAlthough these are very encouraging results, more testing with different model architectures and sizes will be required before categorically concluding this functionality consistently yields higher quality models. Comments, feedback and, in particular, bug reports are very much welcome |
|
This has an effect on the file size of the quants too, right? |
|
That's correct @ThiloteE, file size is directly and proportionally influenced by the chosen bpw |
|
Latest version introduces a new algorithm to select candidates resulting in models that are much closer to the bpw target and, in the large majority of the models tested, with better quality metrics than the equivalent naive version or very close: ERNIE-4.5-21B-A3B-PT
Huihui-MoE-1.2B-A0.6B
Huihui-MoE-5B-A1.7B-abliterated
Llama-3.1-8B
Llama-3.2-1B
NVIDIA-Nemotron-Nano-9B-v2
NVIDIA-Nemotron-Nano-12B-v2
Qwen3-14B
|
|
Checks finally finished. Failed tests are not related to the changes as far as I can see. |
|
@bartowski1182 any chance you could run a quantization pass for some of the popular small models on your hardware using this PR for a range of bpws (starting from 2.50 incrementing every 0.25 up to 5) and see how the KLD / PPL is? I'm afraid it would take ages on my home box. |
|
Remember to use an imatrix created post 0504396. When quanting the same model over a range of sizes (bytes or bpw) it helps to generate the state checkpoint first. My typical workflow starts with: llama-quantize --dry-run --target-bpw 2.345 --state-file --imatrix imatrix.gguf input-model-f16.gguf output-model.ggufThat will generate a More info in the README For an apples-to-apples comparison, I suggest to also try targeting the equivalent sizes of standard types (e.g. Q2_K, Q3_K, Q4_K, etc.) using the same quant/ppl parameters (ctx, logits, ubatch, etc.) |
|
Running some tests and will let you know the results :) |
|
All right. I say we merge it and then we can work on fine-tuning the specific cases in follow-up PRs, let's get this out of the way :) |
|
something is wrong here with MSVC no idea if it's related to this PR |
Please try : |
|
@ServeurpersoCom Your patch fixed the build for me on MSVC 14.52. I see there's also #32902 |
|
@ServeurpersoCom Thank you, but I have already tried PR #32902 - it works fine on my end. |
|
Just seen this. Whilst both approaches work, PR #32902 would be safer due to the lambda captures. |
|
For me, llama.cpp doesn't compile anymore since this commit. changing in llama-quant.cpp |
|
Not even with ServeurpersoCom patch or after applying #32902? |
|
Sorry for ping, @EAddario Basic step-by-step preparations before quantisationStep 1: get gguf's Step 2: get imatrix.gguf Step 3: get the reference Q4_K_M quant from bf16 gguf with imatrix This is with the And this is with the Filesize is bigger, BPW is higher, but PPL is lower - is this expected? |
Upstream's newest tag, 191 commits past b12483, merged on pascal-p106-v5 af00bb1 (the 14 landed branches). 26 files conflicted. Each kept both sides' intent; the list with reasons is the public data folder docs/data/2026-11-24_c912_upstream_b12674/conflicts.tsv. The ones that change code: - ggml.h, ggml.c, ggml-rpc.h: upstream's GGML_OP_SLEEP and GGML_OP_SIGMOID_BACK go after the fork's three ops after GLU, so the fork's op numbers stay; GGML_OP_COUNT 105, RPC patch version 6 (fork 4 + upstream 2). - ggml-rpc.cpp: upstream's single validation step (ggml-org#32651) already rejects unknown ops, so the fork's own check goes; the client's FREE_BUFFER that forgets dropped graphs (C929) sends with upstream's typed call<>. - mmid.cu: upstream's helper with duplicate expert ids (ggml-org#32505) dumps its store in pieces; the legacy tile layout (GGML_CUDA_MMQ_MOE_LEGACY) reads the expert's column count from n_dumped. - mmq.cuh: the kernel takes kq_fp32 (C861) before upstream's force_tiling (GCN only); the force_tiling launch passes kq_fp32 through. - ggml-cuda.cu: ggml-org#32239 (no matrix-vector fusion on any Pascal card) merged without a conflict; the fork keeps the fusion on compute 6.1 as v5 measured it per file, and GGML_CUDA_MMID_GLU_UNFUSE=2 gives upstream's rule (C893). - llama-graph.cpp: upstream's automatic "<name>.scale" lookup (ggml-org#32669) replaces the explicit scale arguments, the cold tier's included (its scales carry their tensors' names); the down projection's rescale is upstream's use_amax rule (ggml-org#32677) and the fork's LLAMA_NO_MOE_DOWN_RESCALE condition; route-once's histogram before upstream's random routing (ggml-org#29539); the device-built KQ mask (LLAMA_GPU_KQ_MASK) moves into upstream's build_attn_iswa_impl (ggml-org#32429) and replaces only the default mask. - llama-memory-hybrid-idx.cpp: ggml-org#32519 scores only the ubatch's sequences' k-pools; with the k-pool tables on the devices (LLAMA_QSA_KPOOL_DEV) the list keeps every sequence's pools, as the tables hold them (get_n_kpool); the pads avoid every pool's rep in both layouts (LLAMA_QSA_PAD_LINEAR's bound kept). - llama-quant.cpp: N2P and N3P's fallbacks go into upstream's fallback_type_for (ggml-org#15550), with the row width; Q4_1_64 in upstream's moved llama_ftype_get_default_type. - glm5-next.cpp, qwen4exp.cpp: the fused lightning indexer is always on (ggml-org#32650): the in-place row variant (LLAMA_QSA_INDEXER_ROWS) without the removed switch. - flint.cpp, qwen4exp.cpp, gemma4.cpp, test-llama-archs.cpp, test-backend-ops.cpp, server-context.cpp: the fork's code with upstream's signature changes, model-name helper, decision groups and label outputs (ggml-org#32553), gemma4's multi-sequence prune (ggml-org#32342) without device-built masks. Carried upstream fixes now merged upstream: ggml-org#32434 (6026911: upstream's version taken, the fork's change kept is only --ctx-checkpoints-share's copy and get_reuse's two trim arguments) and ggml-org#31913 (2b2da8a: upstream's fill, the same change). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
No worries at all @EverchangerL, always happy to help, plus I have a vested interest in people finding the functionality useful 😁 I'll start by saying Gemma 4's history is cursed (AI Mode will give you more gory details). It's a great compact model, but it's cursed nevertheless. With that out of the way, on to your question: the differences you're observing are most likely due to rounding differences and possibly one or more types that sit at the decision boundary whereby just a few bytes difference tip the balance to use one, say IQ4_XS, instead of another (e.g. Q4_K_S). When BPW is used, the internal optimiser will convert to bytes possibly introducing some minor rounding errors. During tests, and working with non-cursed models, I've found the end result to be virtually identical. However, if you're strictly looking for the most faithful outcome, file size is the way to go. |
|
Can we not use identifiers named INFINITE or EPSILON? For example
it's just a lot cleaner to not use the same names. |


This PR adds
target_bpw_type(), a function to determine an optimal per-tensor quantization mix to achieve a user-specified total file size (i.e.,--target-size 1.5g) or a global bits-per-weight (bpw) target (i.e.,--target-bpw 4.5678).An evaluation of 34 models across 238 tests shows that
target_bpw_type()optimization matched or exceeded the quality of standard quantization in 93% of cases, as indicated by lower KLD metrics (see "Test results" below).The function solves a constrained optimization problem to minimize quantization error, subject to a global size budget. It estimates per-tensor error for each layer, and dynamically allocates the bit budget where is needed the most.
High level flow:
--state-fileis set, target computations are saved to a file. If the quantization is interrupted (e.g., Ctrl+C), it can resume where it left off in the next run.Advantages
Target arbitrary size models
--target-size 23.85gwill generate a 23.85 GiB file to utilize the hardware fully.Data-driven mixed precision often can improve quality at fixed size
Allows better like-for-like comparisons between models and families
Standard quantization uses hardcoded rules like: "use Q4_K_M, except bump some tensors up/down, except fall back if incompatible, except keep some tensors unquantized..." and consquently, two different models quantized at the same Q4_K_M level can end up with very different bpw (e.g. 4.75 and 4.30).
Model performance generally scales with size; larger models typically outperform smaller ones. A model quantized with more bits will usually perform better (exhibiting lower perplexity and better evaluation scores) than a smaller version, even when the same underlying quantization method is used. This makes performance comparisons between models not a controlled experiment, as the models being compared have different effective compression ratios.
--target-bpwhelps to normalize experiments by forcing models to be quantized to a roughly equal overall byte budget. This standardization allows performance variations between models to be more accurately linked to underlying factors such as architectural or training differences, the effect of quantization error at the same compression level, or the decisions made by the optimizer regarding allocation.Disadvantages
Quantization process is significantly slower than standard
This approach can take 5x-10x longer as it quantizes a sample of most tensors into 15 different formats, dequantizes them back, computes error diffs, and selects the best size/error option that fits the target file size or global bpw budget.
However, the
--state-fileoption will save the above-mentioned computations to disk so that future quantizations can be generated at normal speed. It also allows to interrupt the computation process and resume it at a later time.The optimization target is only a proxy for the model's performance quality
An imatrix with activations data is required for best results
llama-imatrixcommit 0504396 or newer--target-bpwand--target-filewill refuse to run.Design considerations
The
target_bpw_type()function is implemented as a container for several lambdas providing all the logic for serialization, multithreading, math/stats, and optimization. Although there are clear downsides to this approach (i.e. cognitive load, testability and maintainability), given that all structs and helper lambdas are highly specific to this exact algorithm and have no reuse value elsewhere in the library, a self-contained "God function" seemed the best option to keep modifications to existing code to a minimum.Test results
Target BPW test results
238 tests: 195 (82%) WIN, 26 (11%) TIE, 16 (7%) LOSS, 1 NAAI usage disclosure
AI was used to validate the mathematical approach and calculations, and to optimize and debug the code.
Special thanks to @AesSedai, @am17an, @compilade, @ddh0 and @ngxson for their contributions during the development of this PR.