* Refactor pareto optimise and convexify * Refactor lagrange_penalty() * Refactor quantisation checks into its own function * Exit loop if no better solution found * Replace slope with cross product * Adjust for small vector size * Simplify candidates sorting * Add comments to explain magic numbers * Increase scale multiplier * Move is_iq() into a lambda and remove unused variables * Combine quant types * Reduce bpw range * Refactor outlier trimming * Tighten worker allocator * Check for direction reversal * Simplify dequantisation * Calculate bpw over all tensors * Compute rows based on tensor shape and slice count * Prioritise important tensors * Select quantization type if target_bpw is set unless user specifies type and threads * Relax lambda clamping * Add signal handler * Add save_bpw_state() * Add load_bpw_state() * Add delete_bpw_state() * Persist progress * Uninstall signal handler and cleanup * Fix trimming logic * Generate model ID hash * Remove bias mode computation * Remove --no-bias option * Automatically determine if bias error is significant * Reduce compute time by parallelising tensor processing - courtesy of https://github.com/ddh0 * Add quant types * Add --keep-bpw-state option * Refactor signal handlers * Update quant types * Minor refactoring * Add tensor type and depth heuristics * Add option to override bpw state file name * Minor refactoring * Finetune heuristics * Update usage * Fix lambda capture * Update epsilon specifier * Finetune heuristics * Simplify tensor selection * Read statistics from imatrix * Add Euclidean-Cosine score to identify important tensors * Improved is_important() logic * Fix lambda capture bug in Windows and initialise candidate_types struct * Remove processing statistics_data * Add --disable-tensor-importance option * Use more descriptive option naming * Relax target bpw range * Increase importance boost for final pass * Add B/F16 to get_ftype() * Process bpw targets up to B/F16 * Improve state checkpoint filename * Add code comments * Update usage() * Update README.md * Change checkpoint file magic * Prepare for future optimization algorithms * Add parse_target_size() * Add --target-size option * Implement target_size logic * Update usage() * Refactor parameter names * Refactor option names * Update parameter names * Improve file handling * Remove file deletion * Refactor variable names * Update usage() * Add use_wce option * Read statistics_data from imatrix * Add experimental entropy-modulated weighted cosine error (WCE) * Performance optimisations (AI assisted) * Memory optimisations (AI assisted) * Update output log * Fix state file name generation and simplify_pareto() lambda capture * Change tensor importance score logic * Refactor is_quantizable() * Improve WCE to be magnitude-aware * Expected Output Error MSE * Fix scale factor overwrite bug * Test removing unused headers * Remove wce flag * Angle-aware/Magnitude-aware (MSE/WCE) hybrid error estimation * Revert to weighted cosine error estimation * Enhanced scaling factor * Use centered‑normalized importance scaling factor (CNIF) * Remove redundant logs * Improve state file handling * Update usage instructions * Update ftype parsing logic * Flag experimental features subject to future removal * Fix --target-size description * Fix "casts away qualifiers" compiler warning * Exclude user defined tensors (--tensor-type) from the Lagrangian optimization (courtesy of https://github.com/AesSedai) * TurboQuant bias factor for inner-product sensitive tensors * TurboQuant outlier mitigation * Refactor TurboQuant improvements * Fix remap tensor bug * Remove --importance-pct option * Refactor llama_model_quantize_params to expose a pure C interface * Consolidate load/save process and remove --save-state flag * Minor log output changes * Use the tensor statistics' schema * Add quant types * Release finished tensors mmap allocation * Reuse sample buffers * Fix C2327 error when target compilation is a MS platform * Minor refactoring and AI assisted optimizations * Add uv.lock * Minor refactoring and AI assisted optimizations * Add Halko, Martinsson & Tropp randomized SVD condition number estimator * Add kappa squashing functio * Remove unnecessary includes * Add required include * Update python dependencies * Fine-tune kappa mapping parameters * Fine-tune CNIF beta parameters * Fix fallback counter error * Move to libllama and unmap weights offloaded to backend * Remove unmap weights offloaded to backend * Add winsorization * Add adaptive tensor boosting * Minor cosmetic changes * Refactor processing of unused kv tensors * Minor cosmetic change * Implement --max-buffer-size in target_bpw_type() * Fix 32-block fallback case * tensor_type_override_for() DRY refactoring * Fix typo and remove unused option * Fix #28491 linking bug when compiling with BUILD_SHARED_LIBS=OFF * Remove GGML_USE_METAL conditional macro and let the optimizer decide\ * Add --target-exclude * Remove and ignore uv.lock * Fix pinned tensors safety limits calculation * Fix truncation error * Add downwards greedy upgrade * Add target bpw/size tests * Guard imatrix schema * Update --target-bpw/size descriptions and README.md * Harden state checkpoint's file operations * Link model and imatrix to state checkpoint * Enforce and consume stats schema data * Add stats schema tests * Refactor signal handlers out of lib and harden the logic * Improve handling of pinned tensors * Add tests * Add include to keep ubuntu-webgpu happy * Moving new API entries to prevent brittle downstream apps failing * Fix miscellaneous issues
14 KiB
quantize
This tool takes a GGUF input model file, typically in a high-precision format like F32 or BF16, and converts it to a quantized format. Quantization reduces the precision of model weights (e.g., from 32-bit floats to 4-bit integers), which shrinks the model's size and can speed up inference. This process however, may introduce some accuracy loss which is usually measured in Perplexity (ppl) and/or Kullback–Leibler Divergence (kld). This can be minimized by using a suitable imatrix file.
You can also use the GGUF-my-repo space on Hugging Face to build your own quants without any setup. It syncs from llama.cpp main every 6 hours.
Overview
Quantization is done in two phases:
- Convert the original model to GGUF format.
- Quantize the converted GGUF file.
If the model supports multimodal inputs (images or audio), you also need to convert and quantize the multimodal encoders and projectors.
To perform these tasks, you need to install the Python requirements:
python3 -m pip install -r requirements.txt
Or if you use uv:
uv pip install -r requirements.txt --index-strategy unsafe-best-match
Prepare the input GGUF file
To convert a model from a Hugging Face repo, you can use a command like the following:
python convert_hf_to_gguf.py --outfile gemma-4-E2B-it-bf16.gguf --outtype bf16 --remote google/gemma-4-E2B-it
Notes:
- In the usual case where the model is distributed in 16-bit format,
--outtype auto(or omitting--outtypeentirely) also works well. - If you have previously downloaded the model locally, specify the directory and remove the
--remoteflag. - For compatibility reasons, the Python requirements install transformers 4, but more and more models (like Gemma 4) require transformers 5. You can safely
pip install -U transformersto get the latest version.
Quantize the GGUF
After you have created a high-quality GGUF version of the model, you use llama-quantize to apply quantization. For example, quantize to Q4_K_M using a command like the following:
./build/bin/llama-quantize gemma-4-E2B-it-bf16.gguf gemma-4-E2B-it-Q4_K_M.gguf Q4_K_M
Various quantization methods are described later in this document.
Options:
--allow-requantizeallow requantizing tensors that have already been quantized. Warning: This can severely reduce quality compared to quantizing from 16bit or 32bit--leave-output-tensorleave output.weight un(re)quantized. Increases model size but may also increase quality, especially when requantizing--puredisable k-quant mixtures and quantizes all tensors to the same type--imatrix file_nameuse data in file_name as importance matrix for quant optimizations--include-weights tensor_nameuse importance matrix for this tensor (can be specified multiple times)--exclude-weights tensor_nameuse importance matrix for the tensors not specified (include/exclude cannot be mixed)--output-tensor-typeuse a specific quant type for the output.weight tensor--token-embedding-typeuse a specific quant type for the token embeddings tensor--keep-splitgenerate the quantized model in the same shards as the input file instead of a single quantized file--dry-runsimulate the quantization process--max-buffer-size MiBcap the amount of tensor rows kept in memory while quantizing one tensor (default: 8192). Lower it to quantize models with very large tensors on a machine with little RAM
Advanced options:
--tensor-typequantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times--prune-layersprune (remove) the layers in the list--override-kvoption to override model metadata by key in the quantized model. May be specified multiple times--target-bpwautomatically choose quant types to meet an overall bits per weight (bpw) target--target-sizeautomatically choose quant types to meet a file size target--state-filefile name to store or load the bpw/size scores. If left unspecified it defaults to<model name>-<hash>.bpw_state; progress is automatically preserved upon interruptions (SIGTERM or Ctrl-C) allowing execution of the same command to resume the process--target-excludecomma-separated list of quant types (names or ordinals) that automatic quant type selection must ignore; for use with--target-bpw/--target-size. May be specified multiple times. A state checkpoint is not written while this option is active
When using --target-bpw or --target-size, any tensors specified by --tensor-type, --token-embedding-type, or --output-tensor-type retain their defined types, with their total size counted toward the overall target. Quantization will fail if the budget allocated to these tensors leaves insufficient capacity for the remainder of the model.
(Optional) Convert the multimodal components
llama.cpp will convert the LLM portion of the source model, which is enough for conversational applications. If the model accepts multimodal inputs and you wish to take advantage of them, you need to create a separate GGUF file. This file is generically known as mmproj, for "multimedia projector"; however, it may contain various components such as vision or audio encoders in addition to projections.
Multimodal components are usually much smaller than the LLMs they come with. In addition, their quality has a direct impact on the quality of LLM generations, because these components are in charge of preparing the inputs for the LLM: the closer inputs are to data seen during training, the better LLM results will be.
For these reasons, multimodal components are usually kept in a high-quality format such as bf16 or q8. The impact on speed and memory from using a smaller quant is negligible, but overall quality could be impacted.
python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf --outtype q8_0 --remote google/gemma-4-E2B-it
Run the quantized model
./build/bin/llama cli -m ./gemma-4-E2B-it-Q4_K_M.gguf --mmproj ./mmproj-gemma-4-E2B-it-Q8_0.gguf --image <input_image> --prompt "Describe this image"
Quantization Examples
# naive Q4_K_M quantization using default settings and 8 CPU threads. Output will be "ggml-model-Q4_K_M.gguf"
./llama-quantize input-model-f32.gguf q4_k_m 8
# simulate naive Q4_K_M quantization process. No model will be generated
./llama-quantize --dry-run input-model-f32.gguf q4_k_m 8
# naive Q4_K_M quantization overriding general.name and model.rope.freq_base metadata values
./llama-quantize --override-kv general.name=str:"New model name" --override-kv model.rope.freq_base=float:1.234e+08 input-model-f32.gguf q4_k_m 8
# quantize model enabling re-quantization, leaving the output tensor unquantized and all others quantized at the same level (Q4_K)
./llama-quantize --allow-requantize --leave-output-tensor --pure input-model-f32.gguf q4_k_m 8
# quantize model using an importance matrix for specified tensors only (attn_v and ffn_down)
./llama-quantize --imatrix imatrix.gguf --include-weights attn_v --include-weights ffn_down input-model-f32.gguf q4_k_m 8
# quantize model setting output tensor to Q5_K_M, token embeddings to Q3_K_M, and keeping the input file's shards
./llama-quantize --imatrix imatrix.gguf --output-tensor-type q5_k --token-embedding-type q3_k --keep-split input-model-f32.gguf q4_k_m 8
# quantize model using a regex to quantize attn_k tensors in odd layers to Q5_K_M and attn_q tensors in even layers to Q3_K_M
./llama-quantize --imatrix imatrix.gguf --tensor-type "\.(\d*[13579])\.attn_k=q5_k" --tensor-type "\.(\d*[02468])\.attn_q=q3_k" input-model-f32.gguf q4_k_m 8
# quantize model setting tensors attn_v and ffn_down to Q5_K_M and pruning layers 20, 21, and 22
./llama-quantize --imatrix imatrix.gguf --tensor-type attn_v=q5_k --tensor-type ffn_down=q5_k --prune-layers 20,21,22 input-model-f32.gguf q4_k_m 8
# override expert used count metadata to 16, prune layers 20, 21, and 22 without quantizing the model (copy tensors) and use specified name for the output file
./llama-quantize --imatrix imatrix.gguf --override-kv qwen3moe.expert_used_count=int:16 --prune-layers 20,21,22 input-model-f32.gguf pruned-model-f32.gguf copy 8
# quantize model targeting a specific bpw average and save the target computations to the default file. Model type is optional and can be omitted
./llama-quantize --target-bpw 4.5678 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
# quantize model targeting a specific bpw average using the default state checkpoint (if available) and ignoring IQ2_XXS, IQ2_XS and IQ2_S types (checkpoint is not saved)
./llama-quantize --target-bpw 4.5678 --target-exclude IQ2_XXS,IQ2_XS,IQ2_S --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
# quantize model targeting a specific bpw average reusing previous target computations in default file (e.g. input-model-8fd7a8bef0803042.bpw_state)
./llama-quantize --target-bpw 2.345 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
# quantize model targeting a specific file size and save the target computations to a custom file.
./llama-quantize --target-size 1.5g --state-file my-state-file.dat --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
Memory/Disk Requirements
When running the larger models, make sure you have enough disk space to store all the intermediate files. As the models are currently fully loaded into memory, you will need adequate disk space to save them and sufficient RAM to load them. At the moment, memory and disk requirements are the same. For example (Llama 3.1):
| Model | Original size | Quantized size (Q4_K_M) |
|---|---|---|
| 8B | 32.1 GB | 4.9 GB |
| 70B | 280.9 GB | 43.1 GB |
| 405B | 1,625.1 GB | 249.1 GB |
Quantization
Several quantization methods are supported. They differ in the resulting model disk size and inference speed. For example,
meta-llama/Llama-3.1-8B
| Quant Type | bits/weight | size (GiB) | prompt processing t/s @ 512 | text generation t/s @ 128 |
|---|---|---|---|---|
| IQ1_S | 2.0042 | 1.87 | 858.88 ±1.22 | 79.73 ±0.79 |
| IQ1_M | 2.1460 | 2.01 | 847.99 ±0.47 | 72.92 ±0.14 |
| IQ2_XXS | 2.3824 | 2.23 | 852.39 ±0.85 | 79.86 ±0.22 |
| IQ2_XS | 2.5882 | 2.42 | 826.99 ±12.51 | 78.04 ±0.46 |
| IQ2_S | 2.7403 | 2.56 | 783.55 ±13.73 | 77.30 ±2.47 |
| IQ2_M | 2.9294 | 2.74 | 787.68 ±7.00 | 74.44 ±0.15 |
| IQ3_XXS | 3.2548 | 3.04 | 813.88 ±6.53 | 73.95 ±0.20 |
| IQ3_XS | 3.4977 | 3.27 | 708.71 ±1.26 | 71.67 ±0.54 |
| IQ3_S | 3.6606 | 3.42 | 798.78 ±8.81 | 69.31 ±0.63 |
| IQ3_M | 3.7628 | 3.52 | 768.70 ±13.73 | 70.15 ±0.33 |
| IQ4_XS | 4.4597 | 4.17 | 771.80 ±11.38 | 77.51 ±0.20 |
| IQ4_NL | 4.6818 | 4.38 | 806.03 ±7.07 | 76.63 ±0.28 |
| Q2_K_S | 2.9697 | 2.78 | 798.91 ±6.40 | 90.01 ±0.12 |
| Q2_K | 3.1593 | 2.95 | 784.45 ±7.85 | 79.85 ±0.20 |
| Q3_K_S | 3.6429 | 3.41 | 752.17 ±7.94 | 69.84 ±0.18 |
| Q3_K_M | 3.9960 | 3.74 | 783.44 ±9.92 | 71.68 ±0.22 |
| Q3_K_L | 4.2979 | 4.02 | 761.17 ±7.55 | 69.38 ±0.49 |
| Q4_K_S | 4.6672 | 4.36 | 818.55 ±9.58 | 76.71 ±0.20 |
| Q4_K_M | 4.8944 | 4.58 | 821.81 ±21.44 | 71.93 ±1.52 |
| Q5_K_S | 5.5704 | 5.21 | 752.52 ±0.99 | 69.53 ±0.18 |
| Q5_K_M | 5.7036 | 5.33 | 758.69 ±7.43 | 67.23 ±1.08 |
| Q6_K | 6.5633 | 6.14 | 812.01 ±10.82 | 58.67 ±3.13 |
| Q8_0 | 8.5008 | 7.95 | 865.09 ±8.30 | 50.93 ±0.08 |
| F16 | 16.0005 | 14.96 | 923.49 ±0.53 | 29.17 ±0.04 |
Background information on llama-quantize
- k-quants
- k-quants improvements and i-quants
- #2707
- #2807
- #4773 - 2-bit i-quants (inference)
- #4856 - 2-bit i-quants (inference)
- #4861 - importance matrix
- #4872 - MoE models
- #4897 - 2-bit quantization
- #4930 - imatrix for all k-quants
- #4951 - imatrix on the GPU
- #4969 - imatrix for legacy quants
- #4996 - k-quants tuning
- #5060 - Q3_K_XS
- #5196 - 3-bit i-quants
- quantization tuning, another one, and another one
- target bpw/size