Commit 30ec35ae2 for llama.cpp

commit 30ec35ae2e27f1eca486af02b9d3d53fa7a26950
Author: Ed Addario <29247825+EAddario@users.noreply.github.com>
Date:   Mon Nov 23 17:06:26 2026 +0000

    quantize: add option to automatically choose optimal quant types to reach a file/bpw target size at lowest error (#15550)

    * 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

diff --git a/common/imatrix-loader.cpp b/common/imatrix-loader.cpp
index ec057cac2..ece91ff09 100644
--- a/common/imatrix-loader.cpp
+++ b/common/imatrix-loader.cpp
@@ -117,14 +117,32 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
     imatrix.chunk_size    = chunk_size_key  != -1 ? gguf_get_val_u32(ctx_gguf, chunk_size_key) : 0;
     imatrix.n_layer_nextn = nextn_key       != -1 ? gguf_get_val_u32(ctx_gguf, nextn_key) : 0;

+    const int64_t schema_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA);
+    if (schema_idx != -1 && gguf_get_kv_type(ctx_gguf, schema_idx) == GGUF_TYPE_ARRAY &&
+        gguf_get_arr_type(ctx_gguf, schema_idx) == GGUF_TYPE_STRING) {
+        const int64_t n_schema = gguf_get_arr_n(ctx_gguf, schema_idx);
+        imatrix.stats_schema.resize(n_schema);
+        for (int64_t i = 0; i < n_schema; ++i) { imatrix.stats_schema[i] = gguf_get_arr_str(ctx_gguf, schema_idx, i); }
+    } else {
+        if (schema_idx != -1) {
+            LOG_WRN("%s: %s in %s is not an array of strings, using the default order\n", __func__, LLM_KV_IMATRIX_STATS_SCHEMA, fname.c_str());
+        }
+
+        imatrix.stats_schema = {
+            "sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance",
+        };
+    }
+
     const std::string in_sum_suffix{ ".in_sum" };
     const std::string in_sum2_suffix{ ".in_sum2" };
     const std::string counts_suffix{ ".counts" };
+    const std::string stats_suffix{ ".stats" };

     struct sum_tensors {
         struct ggml_tensor * in_sum  = nullptr;
         struct ggml_tensor * in_sum2 = nullptr;
         struct ggml_tensor * counts  = nullptr;
+        struct ggml_tensor * stats   = nullptr;
     };

     std::map<std::string, sum_tensors> sums_counts_for;
@@ -138,6 +156,8 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
             sums_counts_for[std::move(name)].in_sum2 = cur;
         } else if (string_remove_suffix(name, counts_suffix)) {
             sums_counts_for[std::move(name)].counts = cur;
+        } else if (string_remove_suffix(name, stats_suffix)) {
+            sums_counts_for[std::move(name)].stats = cur;
         }
     }

@@ -146,6 +166,7 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
         const struct ggml_tensor * in_sum  = sc.second.in_sum;
         const struct ggml_tensor * in_sum2 = sc.second.in_sum2;
         const struct ggml_tensor * counts  = sc.second.counts;
+        const struct ggml_tensor * stats   = sc.second.stats;

         if (!in_sum2 || !counts || (in_sum != nullptr && ggml_nelements(in_sum) != ggml_nelements(in_sum2))) {
             LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str());
@@ -182,6 +203,12 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
                 e.activations[j] = ((const float *) in_sum->data)[j];
             }
         }
+
+        if (stats && stats->type == GGML_TYPE_F32) {
+            const int64_t n_stats = ggml_nelements(stats);
+            e.stats.resize(n_stats);
+            for (int64_t j = 0; j < n_stats; ++j) { e.stats[j] = ((const float *) stats->data)[j]; }
+        }
     }

     gguf_free(ctx_gguf);
diff --git a/common/imatrix-loader.h b/common/imatrix-loader.h
index d4616bf30..1b6d8c4c0 100644
--- a/common/imatrix-loader.h
+++ b/common/imatrix-loader.h
@@ -15,11 +15,13 @@ struct common_imatrix_entry {
     std::vector<float>   sums;
     std::vector<float>   activations;
     std::vector<int64_t> counts;
+    std::vector<float>   stats;
 };

 struct common_imatrix {
     std::map<std::string, common_imatrix_entry> entries;
     std::vector<std::string> datasets;
+    std::vector<std::string> stats_schema;
     int32_t chunk_count    = 0;
     int32_t chunk_size     = 0;
     int32_t n_layer_nextn  = 0;
diff --git a/include/llama.h b/include/llama.h
index 7122143e5..9cc17a82b 100644
--- a/include/llama.h
+++ b/include/llama.h
@@ -466,6 +466,15 @@ extern "C" {
         const struct llama_model_tensor_override * tt_overrides;    // pointer to tensor overrides
         const int32_t * prune_layers;                               // pointer to layer indices to prune
         size_t max_buf_size;                                        // max bytes of tensor rows kept in memory at once, 0 = default (8 GiB)
+        const struct llama_model_imatrix_data * activations;        // pointer to activations data
+        const struct llama_model_imatrix_data * statistics;         // pointer to statistics data
+        const char * const * stats_schema;                          // pointer to statistics schema names
+        float target_bpw;                                           // target bits per weight (bpw)
+        int64_t target_size;                                        // target file size in bytes
+        const char * state_file;                                    // pointer to bpw state file
+        const enum ggml_type * target_exclude;                      // pointer to excluded GGML_TYPEs
+        ggml_abort_callback abort_callback;                         // callback to abort quantization
+        void * abort_callback_data;                                 // pointer to user data for abort_callback
     } llama_model_quantize_params;

     typedef struct llama_logit_bias {
diff --git a/src/llama-ext.h b/src/llama-ext.h
index b8b7fba0b..a77b2f409 100644
--- a/src/llama-ext.h
+++ b/src/llama-ext.h
@@ -51,7 +51,7 @@ LLAMA_API quantize_state_impl * llama_quant_init(
         const llama_model * model,
         const llama_model_quantize_params * params);

-LLAMA_API void llama_quant_free(quantize_state_impl * qs);
+LLAMA_API void llama_quant_free(const quantize_state_impl * qs);

 // Descriptor for constructing a mock model for quantization testing.
 struct llama_quant_model_desc {
diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp
index 0515756dc..c66f060f6 100644
--- a/src/llama-quant.cpp
+++ b/src/llama-quant.cpp
@@ -2,58 +2,63 @@
 #include "llama-model.h"
 #include "llama-model-loader.h"
 #include "llama-ext.h"
-#include "llama.h"
+#include "llama-quant.h"

 #include <algorithm>
-#include <cmath>
-#include <cstring>
+#include <array>
+#include <atomic>
+#include <cerrno>
 #include <cinttypes>
+#include <cstdio>
+#include <cstring>
+#include <exception>
 #include <fstream>
 #include <mutex>
+#include <numeric>
+#include <optional>
+#include <queue>
+#include <random>
 #include <regex>
 #include <thread>
 #include <unordered_map>
+#include <unordered_set>

 // result of parsing --tensor-type option
 // (changes to this struct must be reflected in tools/quantize/quantize.cpp)
 struct tensor_type_option {
     std::string name;
-    ggml_type type = GGML_TYPE_COUNT;
+    ggml_type   type = GGML_TYPE_COUNT;
 };

 // tensor categorization - used to avoid repeated string matching in quantization logic.
 // this is different from LLM_TN - we want broad categories, not specific tensor names per arch.
-enum class tensor_category {
-    TOKEN_EMBD,
-    ATTENTION_Q,
-    ATTENTION_V,
-    ATTENTION_K,
-    ATTENTION_QKV,
-    ATTENTION_KV_B,
-    ATTENTION_OUTPUT,
-    ATTENTION_GATE,
-    FFN_UP,
-    FFN_GATE,
-    FFN_DOWN,
-    FFN_LATENT,
-    OUTPUT,
-    OTHER
+enum tensor_category {
+    TENSOR_CATEGORY_TOKEN_EMBD,
+    TENSOR_CATEGORY_ATTENTION_Q,
+    TENSOR_CATEGORY_ATTENTION_V,
+    TENSOR_CATEGORY_ATTENTION_K,
+    TENSOR_CATEGORY_ATTENTION_QKV,
+    TENSOR_CATEGORY_ATTENTION_KV_B,
+    TENSOR_CATEGORY_ATTENTION_OUTPUT,
+    TENSOR_CATEGORY_ATTENTION_GATE,
+    TENSOR_CATEGORY_FFN_UP,
+    TENSOR_CATEGORY_FFN_GATE,
+    TENSOR_CATEGORY_FFN_DOWN,
+    TENSOR_CATEGORY_FFN_LATENT,
+    TENSOR_CATEGORY_OUTPUT,
+    TENSOR_CATEGORY_OTHER
 };

 // max amount of tensor data kept in memory while quantizing a single tensor
 static const size_t LLAMA_QUANT_MAX_BUF_SIZE = 8ull*1024*1024*1024;

-static void zeros(std::ofstream & file, size_t n) {
-    char zero = 0;
-    for (size_t i = 0; i < n; ++i) {
-        file.write(&zero, 1);
-    }
+static void zeros(std::ofstream & file, const size_t n) {
+    constexpr char zero = 0;
+    for (size_t i = 0; i < n; ++i) { file.write(& zero, 1); }
 }

 static std::string remap_layer(const std::string & orig_name, const std::vector<int> & prune, std::map<int, std::string> & mapped, int & next_id) {
-    if (prune.empty()) {
-        return orig_name;
-    }
+    if (prune.empty()) { return orig_name; }

     static const std::regex pattern(R"(blk\.(\d+)\.)");
     if (std::smatch match; std::regex_search(orig_name, match, pattern)) {
@@ -79,9 +84,7 @@ static std::string remap_layer(const std::string & orig_name, const std::vector<
 }

 static std::string remap_imatrix(const std::string & orig_name, const std::map<int, std::string> & mapped) {
-    if (mapped.empty()) {
-        return orig_name;
-    }
+    if (mapped.empty()) { return orig_name; }

     static const std::regex pattern(R"(blk\.(\d+)\.)");
     if (std::smatch match; std::regex_search(orig_name, match, pattern)) {
@@ -89,20 +92,16 @@ static std::string remap_imatrix(const std::string & orig_name, const std::map<i
         std::string new_name = orig_name;

         for (const auto & p : mapped) {
-            if (p.second == blk) {
-                return new_name.replace(match.position(1), match.length(1), std::to_string(p.first));
-            }
+            if (p.second == blk) { return new_name.replace(match.position(1), match.length(1), std::to_string(p.first)); }
         }
+
         GGML_ABORT("\n%s: imatrix mapping error for %s\n", __func__, orig_name.c_str());
     }

     return orig_name;
 }

-//
 // helper functions for tensor name matching
-//
-
 static bool tensor_name_match_token_embd(const char * tensor_name) {
     return std::strcmp(tensor_name, "token_embd.weight") == 0 ||
            std::strcmp(tensor_name, "per_layer_token_embd.weight") == 0;
@@ -112,54 +111,36 @@ static bool tensor_name_match_output_weight(const char * tensor_name) {
     return std::strcmp(tensor_name, "output.weight") == 0;
 }

-//
-// tensor categorization for quantization
-//
-// (this is different from LLM_TN - we want broad categories, not specific tensor names per arch)
-//
+// layers sharing the kv cache of an earlier layer never run their own attn_k/attn_v
+static bool tensor_name_match_unused_kv(const std::string & tensor_name, const int n_unused_from) {
+    if (n_unused_from < 0) { return false; }

-static tensor_category tensor_get_category(const std::string & tensor_name) {
-    if (tensor_name_match_output_weight(tensor_name.c_str())) {
-        return tensor_category::OUTPUT;
-    }
-    if (tensor_name_match_token_embd(tensor_name.c_str())) {
-        return tensor_category::TOKEN_EMBD;
+    static const std::regex pattern(R"(^blk\.(\d+)\.attn_[kv]\.weight$)");
+    if (std::smatch match; std::regex_match(tensor_name, match, pattern)) {
+        return std::stoi(match[1]) >= n_unused_from;
     }
+
+    return false;
+}
+
+// tensor categorization for quantization
+static tensor_category tensor_get_category(const std::string & tensor_name) {
+    if (tensor_name_match_output_weight(tensor_name.c_str()))           { return TENSOR_CATEGORY_OUTPUT; }
+    if (tensor_name_match_token_embd(tensor_name.c_str()))              { return TENSOR_CATEGORY_TOKEN_EMBD; }
     // attn_qkv_gate is [attn_qkv | attn_gate] in one weight, the qkv rows decide its type
-    if (tensor_name.find("attn_qkv.weight") != std::string::npos || tensor_name.find("attn_qkv_gate.weight") != std::string::npos) {
-        return tensor_category::ATTENTION_QKV;
-    }
-    if (tensor_name.find("attn_kv_b.weight") != std::string::npos) {
-        return tensor_category::ATTENTION_KV_B;
-    }
-    if (tensor_name.find("attn_v.weight") != std::string::npos) {
-        return tensor_category::ATTENTION_V;
-    }
-    if (tensor_name.find("attn_k.weight") != std::string::npos) {
-        return tensor_category::ATTENTION_K;
-    }
-    if (tensor_name.find("attn_q.weight") != std::string::npos) {
-        return tensor_category::ATTENTION_Q;
-    }
-    if (tensor_name.find("attn_output.weight") != std::string::npos) {
-        return tensor_category::ATTENTION_OUTPUT;
-    }
-    if (tensor_name.find("ffn_up") != std::string::npos) {
-        return tensor_category::FFN_UP;
-    }
-    if (tensor_name.find("ffn_gate") != std::string::npos) {
-        return tensor_category::FFN_GATE;
-    }
-    if (tensor_name.find("ffn_latent") != std::string::npos) {
-        return tensor_category::FFN_LATENT;
-    }
-    if (tensor_name.find("attn_gate.weight") != std::string::npos) {
-        return tensor_category::ATTENTION_GATE;
-    }
-    if (tensor_name.find("ffn_down") != std::string::npos) {
-        return tensor_category::FFN_DOWN;
-    }
-    return tensor_category::OTHER;
+    if (tensor_name.find("attn_qkv.weight") != std::string::npos || tensor_name.find("attn_qkv_gate.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_QKV; }
+    if (tensor_name.find("attn_kv_b.weight") != std::string::npos)   { return TENSOR_CATEGORY_ATTENTION_KV_B; }
+    if (tensor_name.find("attn_v.weight") != std::string::npos)      { return TENSOR_CATEGORY_ATTENTION_V; }
+    if (tensor_name.find("attn_k.weight") != std::string::npos)      { return TENSOR_CATEGORY_ATTENTION_K; }
+    if (tensor_name.find("attn_q.weight") != std::string::npos)      { return TENSOR_CATEGORY_ATTENTION_Q; }
+    if (tensor_name.find("attn_output.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_OUTPUT; }
+    if (tensor_name.find("ffn_up") != std::string::npos)             { return TENSOR_CATEGORY_FFN_UP; }
+    if (tensor_name.find("ffn_gate") != std::string::npos)           { return TENSOR_CATEGORY_FFN_GATE; }
+    if (tensor_name.find("ffn_latent") != std::string::npos)         { return TENSOR_CATEGORY_FFN_LATENT; }
+    if (tensor_name.find("attn_gate.weight") != std::string::npos)   { return TENSOR_CATEGORY_ATTENTION_GATE; }
+    if (tensor_name.find("ffn_down") != std::string::npos)           { return TENSOR_CATEGORY_FFN_DOWN; }
+
+    return TENSOR_CATEGORY_OTHER;
 }

 // check if tensor is a MoE expert tensor (used by GGML_OP_MUL_MAT_ID)
@@ -169,16 +150,11 @@ static bool tensor_is_expert(const std::string & tensor_name) {
 }

 // check if category is for attention-v-like tensors (more sensitive to quantization)
-static bool category_is_attn_v(tensor_category cat) {
-    return cat == tensor_category::ATTENTION_V     ||
-           cat == tensor_category::ATTENTION_QKV   ||
-           cat == tensor_category::ATTENTION_KV_B;
+static bool category_is_attn_v(const tensor_category cat) {
+    return cat == TENSOR_CATEGORY_ATTENTION_V || cat == TENSOR_CATEGORY_ATTENTION_QKV || cat == TENSOR_CATEGORY_ATTENTION_KV_B;
 }

-//
 // quantization state
-//
-
 struct quantize_state_impl {
     const llama_model                 & model;
     const llama_model_quantize_params * params;
@@ -191,29 +167,55 @@ struct quantize_state_impl {
     int i_ffn_down     = 0;
     int i_ffn_gate     = 0;
     int i_ffn_up       = 0;
-
-    int n_fallback    = 0;
-
+    int n_fallback     = 0;
     bool has_imatrix = false;

     // used to figure out if a model has tied embeddings (tok_embd shares weights with output)
     bool has_tied_embeddings = true; // assume tied until we see output.weight
+    bool has_activations = false;

-    // tensor type override patterns (compiled once, used twice)
-    std::vector<std::pair<std::regex, ggml_type>> tensor_type_patterns;
+    // tensor type override patterns (compiled once, queried via tensor_type_override_for())
+    struct tensor_type_pattern {
+        std::string pattern;
+        std::regex  regex;
+        ggml_type   type;
+    };

-    quantize_state_impl(const llama_model & model, const llama_model_quantize_params * params):
-        model(model), params(params)
-    {
+    std::vector<tensor_type_pattern> tensor_type_patterns;
+    std::array<bool, GGML_TYPE_COUNT> ignored_types{};
+    bool has_ignored_types = false;
+
+    quantize_state_impl(const llama_model & model, const llama_model_quantize_params * params) : model(model), params(params) {
         // compile regex patterns once - they are expensive
         if (params->tt_overrides) {
-            for (const auto * p = params->tt_overrides; p->pattern != nullptr; p++) {
-                tensor_type_patterns.emplace_back(std::regex(p->pattern), p->type);
+            for (const auto * o = params->tt_overrides; o->pattern != nullptr; o++) {
+                tensor_type_patterns.push_back({o->pattern, std::regex(o->pattern), o->type});
+            }
+        }
+
+        if (params->target_exclude) {
+            for (const auto * t = params->target_exclude; * t != GGML_TYPE_COUNT; t++) {
+                if (* t >= 0 && * t < GGML_TYPE_COUNT) {
+                    ignored_types[*t] = true;
+                    has_ignored_types = true;
+                }
             }
         }
     }
 };

+// the --tensor-type override for the tensor or GGML_TYPE_COUNT if none
+static ggml_type tensor_type_override_for(const quantize_state_impl & qs, const char * tensor_name) {
+    if (qs.tensor_type_patterns.empty()) { return GGML_TYPE_COUNT; }
+
+    const std::string name(tensor_name);
+    for (const auto & p : qs.tensor_type_patterns) {
+        if (std::regex_search(name, p.regex)) { return p.type; }
+    }
+
+    return GGML_TYPE_COUNT;
+}
+
 // per-tensor metadata, computed in the preliminary loop and used in the main loop
 struct tensor_metadata {
     std::string     name;
@@ -224,68 +226,55 @@ struct tensor_metadata {
     bool            requires_imatrix;
 };

-//
 // dequantization
-//
-
-static void llama_tensor_dequantize_impl(
-    ggml_type type, const void * data, float * f32_output, std::vector<std::thread> & workers,
-    const size_t nelements, const int nthread
+static void llama_tensor_dequantize_impl(ggml_type type,
+    const void * data,
+    float * f32_output,
+    std::vector<std::thread> & workers,
+    const size_t nelements,
+    const int nthread
 ) {
     const ggml_type_traits * qtype = ggml_get_type_traits(type);
     if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) {
-        if (qtype->to_float == NULL) {
+        if (qtype->to_float == nullptr) {
             throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(type)));
         }
-    } else if (type != GGML_TYPE_F16 &&
-               type != GGML_TYPE_BF16) {
+    } else if (type != GGML_TYPE_F16 && type != GGML_TYPE_BF16) {
         throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(type)));
     }

     if (nthread < 2) {
-        if (type == GGML_TYPE_F16) {
-            ggml_fp16_to_fp32_row((const ggml_fp16_t *)data, f32_output, nelements);
-        } else if (type == GGML_TYPE_BF16) {
-            ggml_bf16_to_fp32_row((const ggml_bf16_t *)data, f32_output, nelements);
-        } else if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) {
-            qtype->to_float(data, f32_output, nelements);
-        } else {
-            GGML_ABORT("fatal error"); // unreachable
-        }
+        if (type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)data, f32_output, nelements); }
+        else if (type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)data, f32_output, nelements); }
+        else if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { qtype->to_float(data, f32_output, nelements); }
+        else { GGML_ABORT("fatal error"); }
+
         return;
     }

     size_t block_size;
-    if (type == GGML_TYPE_F16 ||
-        type == GGML_TYPE_BF16) {
-        block_size = 1;
-    } else {
-        block_size = (size_t)ggml_blck_size(type);
-    }
+    if (type == GGML_TYPE_F16 || type == GGML_TYPE_BF16) { block_size = 1; }
+    else { block_size = (size_t)ggml_blck_size(type); }

-    size_t block_size_bytes = ggml_type_size(type);
+    const size_t block_size_bytes = ggml_type_size(type);

     GGML_ASSERT(nelements % block_size == 0);
-    size_t nblocks = nelements / block_size;
-    size_t blocks_per_thread = nblocks / nthread;
-    size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
+    const size_t nblocks = nelements / block_size;
+    const size_t blocks_per_thread = nblocks / nthread;
+    const size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count

     size_t in_buff_offs = 0;
     size_t out_buff_offs = 0;

     for (int tnum = 0; tnum < nthread; tnum++) {
-        size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
+        const size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
         size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
-        size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
+        const size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread

         auto compute = [qtype] (ggml_type typ, const uint8_t * inbuf, float * outbuf, int nels) {
-            if (typ == GGML_TYPE_F16) {
-                ggml_fp16_to_fp32_row((const ggml_fp16_t *)inbuf, outbuf, nels);
-            } else if (typ == GGML_TYPE_BF16) {
-                ggml_bf16_to_fp32_row((const ggml_bf16_t *)inbuf, outbuf, nels);
-            } else {
-                qtype->to_float(inbuf, outbuf, nels);
-            }
+            if (typ == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)inbuf, outbuf, nels); }
+            else if (typ == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)inbuf, outbuf, nels); }
+            else { qtype->to_float(inbuf, outbuf, nels); }
         };
         workers.emplace_back(compute, type, (const uint8_t *) data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
         in_buff_offs += thr_block_bytes;
@@ -295,21 +284,17 @@ static void llama_tensor_dequantize_impl(
     workers.clear();
 }

-//
 // do we allow this tensor to be quantized?
-//
-
 static bool tensor_allows_quantization(const llama_model_quantize_params * params, llm_arch arch, const ggml_tensor * tensor) {
-    // trivial checks first -- no string ops needed
-    if (params->only_copy)       return false;
+    if (params->only_copy) { return false; }

     // quantize only 2D+ tensors (matrices, experts, conv kernels)
-    if (ggml_n_dims(tensor) < 2) return false;
+    if (ggml_n_dims(tensor) < 2) { return false; }

     const std::string name = ggml_get_name(tensor);

-    // This used to be a regex, but <regex> has an extreme cost to compile times.
-    bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
+    // ends with 'weight'?
+    bool quantize = name.rfind("weight") == name.size() - 6;

     // do not quantize norm tensors
     quantize &= name.find("_norm.weight") == std::string::npos;
@@ -317,7 +302,6 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param
     quantize &= params->quantize_output_tensor || name != "output.weight";

     // do not quantize expert gating tensors
-    // NOTE: can't use LLM_TN here because the layer number is not known
     quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;

     // do not quantize the i32 token-id -> expert-id routing table (DeepSeek-V4)
@@ -360,7 +344,6 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param
     quantize &= name != LLM_TN(arch)(LLM_TENSOR_TOKEN_TYPES, "weight");

     // do not quantize Mamba/Kimi's small conv1d weights
-    // NOTE: can't use LLM_TN here because the layer number is not known
     quantize &= name.find("ssm_conv1d") == std::string::npos;
     quantize &= name.find("shortconv.conv.weight") == std::string::npos;

@@ -458,90 +441,77 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param
     return quantize;
 }

-//
-// tensor type selection
-//
+// mapping from an incompatible target type to its block-size-32 substitute
+static ggml_type fallback_type_for(const ggml_type target_type) {
+    switch (target_type) {
+        // types on the left, block size 256; types on the right, block size 32
+        case GGML_TYPE_IQ1_S:
+        case GGML_TYPE_IQ1_M:
+        case GGML_TYPE_IQ2_XXS:
+        case GGML_TYPE_IQ2_XS:
+        case GGML_TYPE_IQ2_S:
+        case GGML_TYPE_IQ3_XXS:
+        case GGML_TYPE_IQ3_S:
+        case GGML_TYPE_IQ4_XS: return GGML_TYPE_IQ4_NL;
+        case GGML_TYPE_Q2_0:
+        case GGML_TYPE_Q2_K:
+        case GGML_TYPE_Q3_K:
+        case GGML_TYPE_TQ1_0:
+        case GGML_TYPE_TQ2_0:  return GGML_TYPE_Q4_0;
+        case GGML_TYPE_Q4_K:   return GGML_TYPE_Q5_0;
+        case GGML_TYPE_Q5_K:   return GGML_TYPE_Q5_1;
+        case GGML_TYPE_Q6_K:   return GGML_TYPE_Q8_0;
+        default:
+            if (ggml_blck_size(target_type) <= 32) { return GGML_TYPE_COUNT; } // nothing smaller to demote to
+            throw std::runtime_error(format("no tensor type fallback is defined for type %s", ggml_type_name(target_type)));
+    }
+}

 // incompatible tensor shapes are handled here - fallback to a compatible type
 static ggml_type tensor_type_fallback(quantize_state_impl & qs, const ggml_tensor * t, const ggml_type target_type) {
-    ggml_type return_type = target_type;
-
     const int64_t ncols = t->ne[0];
     const int64_t qk_k = ggml_blck_size(target_type);
-
-    if (ncols % qk_k != 0) { // this tensor's shape is incompatible with this quant
-        LLAMA_LOG_WARN("warning: %-36s - ncols %6" PRId64 " not divisible by %3" PRId64 " (required for type %7s) ",
-                        t->name, ncols, qk_k, ggml_type_name(target_type));
-        ++qs.n_fallback;
-
-        switch (target_type) {
-            // types on the left: block size 256
-            case GGML_TYPE_IQ1_S:
-            case GGML_TYPE_IQ1_M:
-            case GGML_TYPE_IQ2_XXS:
-            case GGML_TYPE_IQ2_XS:
-            case GGML_TYPE_IQ2_S:
-            case GGML_TYPE_IQ3_XXS:
-            case GGML_TYPE_IQ3_S:   // types on the right: block size 32
-            case GGML_TYPE_IQ4_XS:  return_type = GGML_TYPE_IQ4_NL; break;
-            case GGML_TYPE_Q2_0:
-            case GGML_TYPE_Q2_K:
-            case GGML_TYPE_Q3_K:
-            case GGML_TYPE_TQ1_0:
-            case GGML_TYPE_TQ2_0:   return_type = GGML_TYPE_Q4_0;   break;
-            case GGML_TYPE_Q4_K:    return_type = GGML_TYPE_Q5_0;   break;
-            case GGML_TYPE_Q5_K:    return_type = GGML_TYPE_Q5_1;   break;
-            case GGML_TYPE_Q6_K:    return_type = GGML_TYPE_Q8_0;   break;
-            default:
-                if (qk_k <= 32) {
-                    // the target is already a 32-block type, so there is no smaller block to demote to
-                    // the check below turns it into F16, as a 256-block type does when its fallback does not fit
-                    return_type = target_type;
-                    break;
-                }
-                throw std::runtime_error(format("no tensor type fallback is defined for type %s",
-                                                ggml_type_name(target_type)));
-        }
-        if (ncols % ggml_blck_size(return_type) != 0) {
-            //
-            // the fallback return type is still not compatible for this tensor!
-            //
-            // most likely, this tensor's first dimension is not divisible by 32.
-            // this is very rare. we can either abort the quantization, or
-            // fallback to F16 / F32.
-            //
-            LLAMA_LOG_WARN("(WARNING: must use F16 due to unusual shape) ");
-            return_type = GGML_TYPE_F16;
-        }
-        LLAMA_LOG_WARN("-> falling back to %7s\n", ggml_type_name(return_type));
-    }
-    return return_type;
+    if (ncols % qk_k == 0) { return target_type; } // this tensor's shape is compatible with this quant
+    ++qs.n_fallback;
+    LLAMA_LOG_WARN("warning: %-36s - ncols %6" PRId64 " not divisible by %3" PRId64 " (required for type %7s) ",
+        t->name, ncols, qk_k, ggml_type_name(target_type));
+
+    ggml_type fallback_type = fallback_type_for(target_type);
+    if (fallback_type == GGML_TYPE_COUNT || ncols % ggml_blck_size(fallback_type) != 0) {
+        //
+        // the fallback return type is still not compatible for this tensor!
+        //
+        // most likely, this tensor's first dimension is not divisible by 32.
+        // this is very rare. we can either abort the quantization, or
+        // fallback to F16 / F32.
+        //
+        LLAMA_LOG_WARN("(WARNING: must use F16 due to unusual shape) ");
+        fallback_type = GGML_TYPE_F16;
+    }
+    LLAMA_LOG_WARN("-> falling back to %7s\n", ggml_type_name(fallback_type));
+
+    return fallback_type;
 }

-// internal standard logic for selecting the target tensor type based on tensor category, ftype, and model arch
+// select the target tensor type based on tensor category, ftype, and model arch
 static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype, tensor_category category) {
     const std::string name = ggml_get_name(tensor);

     // TODO: avoid hardcoded tensor names - use the TN_* constants
     const llm_arch arch = qs.model.arch;
-
-    auto use_more_bits = [](int i_layer, int n_layers) -> bool {
-        return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
+    auto use_more_bits = [](const int i_layer, const int n_layers) -> bool {
+        return i_layer < n_layers / 8 || i_layer >= 7 * n_layers / 8 || (i_layer - n_layers / 8) % 3 == 2;
     };
+
     const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
-    auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
+    auto layer_info = [n_expert] (int i_layer, int n_layer, const char * tname) {
         if (n_expert > 1) {
-            // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
-            // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
-            // for getting the current layer as I initially thought, and we need to resort to parsing the
-            // tensor name.
-            if (sscanf(name, "blk.%d.", &i_layer) != 1) {
-                throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
-            }
-            if (i_layer < 0 || i_layer >= n_layer) {
-                throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
-            }
+            // Experts may not be consecutive and simply dividing i_ffn_down by n_expert does not work,
+            // so we need to parse the tensor name
+            if (sscanf(tname, "blk.%d.", &i_layer) != 1) { throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); }
+            if (i_layer < 0 || i_layer >= n_layer) { throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, tname, n_layer)); }
         }
+
         return std::make_pair(i_layer, n_layer);
     };

@@ -564,22 +534,16 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type
     // bumping to q8_0 is preferred since these tensors are not really big
     // TODO: nemotron 3 super shares ffn_latent and afmoe, bailingmoe3, dots3note, hy-v4, kimi-k3 and laguna share attn_gate.
     //       Widening the guard is likely a win there too, but it changes their files, so it wants a perplexity comparison per architecture first.
-    if (arch == LLM_ARCH_MUSE_SPARK &&
-        (category == tensor_category::FFN_LATENT || category == tensor_category::ATTENTION_GATE)) {
-        auto bits_per_weight = [](ggml_type t) {
-            return 8.0 * ggml_type_size(t) / ggml_blck_size(t);
-        };
-        if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) {
-            new_type = GGML_TYPE_Q8_0;
-        }
+    if (arch == LLM_ARCH_MUSE_SPARK && (category == TENSOR_CATEGORY_FFN_LATENT || category == TENSOR_CATEGORY_ATTENTION_GATE)) {
+        auto bits_per_weight = [](ggml_type t) { return 8.0 * ggml_type_size(t) / ggml_blck_size(t); };
+        if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) { new_type = GGML_TYPE_Q8_0; }
     }

-    // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
-    // with the quantization of the output tensor
-    if (category == tensor_category::OUTPUT || (qs.has_tied_embeddings && category == tensor_category::TOKEN_EMBD)) {
-        if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
-            new_type = qs.params->output_tensor_type;
-        } else {
+    // for arches that share the same tensor between the token embeddings and the output,
+    // we quantize the token embeddings with the quantization of the output tensor
+    if (category == TENSOR_CATEGORY_OUTPUT || (qs.has_tied_embeddings && category == TENSOR_CATEGORY_TOKEN_EMBD)) {
+        if (qs.params->output_tensor_type < GGML_TYPE_COUNT) { new_type = qs.params->output_tensor_type; }
+        else {
             const int64_t nx = tensor->ne[0];
             const int64_t qk_k = ggml_blck_size(new_type);

@@ -599,14 +563,14 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type
             }
         }
     } else if (ftype == LLAMA_FTYPE_MOSTLY_MXFP4_MOE) {
-        // MoE   tensors -> MXFP4
-        // other tensors -> Q8_0
         if (tensor_is_expert(name)) {
+            // MoE   tensors -> MXFP4
             new_type = GGML_TYPE_MXFP4;
         } else {
+            // other tensors -> Q8_0
             new_type = GGML_TYPE_Q8_0;
         }
-    } else if (category == tensor_category::TOKEN_EMBD) {
+    } else if (category == TENSOR_CATEGORY_TOKEN_EMBD) {
         if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
             new_type = qs.params->token_embedding_type;
         } else {
@@ -627,242 +591,189 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type
     } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
                ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M    || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
         if (category_is_attn_v(category)) {
-            if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
-            else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
+            if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) { new_type = GGML_TYPE_Q4_K; }
+            else { new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K; }
+
             ++qs.i_attention_wv;
         }
-        else if (qs.model.hparams.n_expert == 8 && category == tensor_category::ATTENTION_K) {
-            new_type = GGML_TYPE_Q4_K;
-        }
-        else if (category == tensor_category::FFN_DOWN) {
+        else if (qs.model.hparams.n_expert == 8 && category == TENSOR_CATEGORY_ATTENTION_K) { new_type = GGML_TYPE_Q4_K; }
+        else if (category == TENSOR_CATEGORY_FFN_DOWN) {
             if (qs.i_ffn_down < qs.n_ffn_down/8) {
                 new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
             }
+
             ++qs.i_ffn_down;
         }
-        else if (category == tensor_category::ATTENTION_OUTPUT) {
-            if (qs.model.hparams.n_expert == 8) {
-                new_type = GGML_TYPE_Q5_K;
-            } else {
-                if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
-                else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
+        else if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT) {
+            if (qs.model.hparams.n_expert == 8) { new_type = GGML_TYPE_Q5_K; }
+            else {
+                if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) { new_type = GGML_TYPE_IQ2_XXS; }
+                else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) { new_type = GGML_TYPE_IQ3_S; }
             }
         }
     } else if (category_is_attn_v(category)) {
-        if      (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
-            new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
-            new_type = GGML_TYPE_Q4_K;
-        }
+        if      (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q4_K; }
         else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
             new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
         }
-        else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
-            new_type = GGML_TYPE_Q4_K;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
-            new_type = GGML_TYPE_Q4_K;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
-            new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
-        else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
-            new_type = GGML_TYPE_Q5_K;
-        }
+        else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q4_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { new_type = GGML_TYPE_Q4_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) { new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = GGML_TYPE_Q5_K; }
+        else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q5_K; }
         else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
-                use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
+                use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) { new_type = GGML_TYPE_Q6_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) { new_type = GGML_TYPE_Q5_K; }
         if (qs.model.type == LLM_TYPE_70B) {
             // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
             // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
             // nearly negligible increase in model size by quantizing this tensor with more bits:
-            if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
+            if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) { new_type = GGML_TYPE_Q5_K; }
         }
         if (qs.model.hparams.n_expert == 8) {
             // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
             // TODO: explore better strategies
             new_type = GGML_TYPE_Q8_0;
         }
+
         ++qs.i_attention_wv;
-    } else if (category == tensor_category::ATTENTION_K) {
+    } else if (category == TENSOR_CATEGORY_ATTENTION_K) {
         if (qs.model.hparams.n_expert == 8) {
-            // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
             // TODO: explore better strategies
             new_type = GGML_TYPE_Q8_0;
         }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
-            new_type = GGML_TYPE_IQ3_XXS;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
-            new_type = GGML_TYPE_IQ2_S;
-        }
-    } else if (category == tensor_category::ATTENTION_Q) {
-        if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
-            new_type = GGML_TYPE_IQ3_XXS;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
-            new_type = GGML_TYPE_IQ2_S;
-        }
-    } else if (category == tensor_category::FFN_DOWN) {
+        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { new_type = GGML_TYPE_IQ3_XXS; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ2_S; }
+    } else if (category == TENSOR_CATEGORY_ATTENTION_Q) {
+        if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { new_type = GGML_TYPE_IQ3_XXS; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ2_S; }
+    } else if (category == TENSOR_CATEGORY_FFN_DOWN) {
         auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
         int i_layer = info.first, n_layer = info.second;
-        if      (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
-            if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
-            new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
-        }
+        if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { new_type = GGML_TYPE_Q3_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) { if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) { new_type = i_layer < n_layer / 8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; }
         else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
             new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
                      : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
                      : GGML_TYPE_Q3_K;
         }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
-                    (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
+        else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer / 8 || (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
             new_type = GGML_TYPE_Q4_K;
         }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
-            new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
-        }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K; }
         else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
             if (arch == LLM_ARCH_FALCON) {
-                new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
-                           use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
-            } else {
-                if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
-            }
+                new_type = i_layer < n_layer / 16 ? GGML_TYPE_Q6_K : use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
+            } else if (use_more_bits(i_layer, n_layer)) { new_type = GGML_TYPE_Q6_K; }
         }
-        else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
+        else if (i_layer < n_layer / 8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
             new_type = GGML_TYPE_Q5_K;
         }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
-            new_type = GGML_TYPE_Q5_K;
-        }
-        else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
-                && qs.has_imatrix && i_layer < n_layer/8) {
-            // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
-            // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
-            // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) { new_type = GGML_TYPE_Q6_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) { new_type = GGML_TYPE_Q5_K; }
+        else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0) && qs.has_imatrix && i_layer < n_layer / 8) {
+            // Safeguard against instability in the initial ffn_down layers, which can occur with Q4_0/Q5_0 quantization even when an imatrix is used.
+            // The rationale is two-fold: first, to guarantee that the resulting quantization remains consistent with the pre-imatrix state,
+            // and second, because Q4_1/Q5_1 tend to exhibit instability in ffn_down layers without an imatrix.
             new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
         }
+
         ++qs.i_ffn_down;
-    } else if (category == tensor_category::ATTENTION_OUTPUT) {
+    } else if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT) {
         if (arch != LLM_ARCH_FALCON) {
             if (qs.model.hparams.n_expert == 8) {
                 if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K   || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
                     ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M  || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL  ||
                     ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M  || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S  ||
-                    ftype == LLAMA_FTYPE_MOSTLY_IQ3_M  || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
-                    new_type = GGML_TYPE_Q5_K;
-                }
+                    ftype == LLAMA_FTYPE_MOSTLY_IQ3_M  || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) { new_type = GGML_TYPE_Q5_K; }
             } else {
-                if      (ftype == LLAMA_FTYPE_MOSTLY_Q2_K   ) new_type = GGML_TYPE_Q3_K;
-                else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
-                else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
-                else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
-                else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M  ) new_type = GGML_TYPE_Q4_K;
+                if      (ftype == LLAMA_FTYPE_MOSTLY_Q2_K   ) { new_type = GGML_TYPE_Q3_K; }
+                else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ3_S; }
+                else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) { new_type = GGML_TYPE_Q4_K; }
+                else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) { new_type = GGML_TYPE_Q5_K; }
+                else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M  ) { new_type = GGML_TYPE_Q4_K; }
             }
-        } else {
-            if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
-        }
+        } else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = GGML_TYPE_Q4_K; }
     }
-    else if (category == tensor_category::ATTENTION_QKV) {
-        if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
-            new_type = GGML_TYPE_Q4_K;
-        }
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
-        else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
+    else if (category == TENSOR_CATEGORY_ATTENTION_QKV) {
+        if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { new_type = GGML_TYPE_Q4_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) { new_type = GGML_TYPE_Q5_K; }
+        else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) { new_type = GGML_TYPE_Q6_K; }
     }
-    else if (category == tensor_category::FFN_GATE) {
+    else if (category == TENSOR_CATEGORY_FFN_GATE) {
         auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
         int i_layer = info.first, n_layer = info.second;
-        if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
-            new_type = GGML_TYPE_IQ3_XXS;
-        }
+        if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && i_layer >= n_layer / 8 && i_layer < 7 * n_layer / 8) { new_type = GGML_TYPE_IQ3_XXS; }
+
         ++qs.i_ffn_gate;
     }
-    else if (category == tensor_category::FFN_UP) {
+    else if (category == TENSOR_CATEGORY_FFN_UP) {
         auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
         int i_layer = info.first, n_layer = info.second;
-        if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
-            new_type = GGML_TYPE_IQ3_XXS;
-        }
+        if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && i_layer >= n_layer / 8 && i_layer < 7 * n_layer / 8) { new_type = GGML_TYPE_IQ3_XXS; }
+
         ++qs.i_ffn_up;
     }

     return new_type;
 }

-// outer wrapper: determine the ggml_type that this tensor should be quantized to
-static ggml_type llama_tensor_get_type(quantize_state_impl & qs, const llama_model_quantize_params * params, const ggml_tensor * tensor, ggml_type default_type, const tensor_metadata & tm) {
-    if (!tensor_allows_quantization(params, qs.model.arch, tensor)) {
-        return tensor->type;
-    }
-    if (params->token_embedding_type < GGML_TYPE_COUNT && tm.category == tensor_category::TOKEN_EMBD) {
+// determine the ggml_type that this tensor should be quantized to
+static ggml_type llama_tensor_get_type(quantize_state_impl & qs,
+    const llama_model_quantize_params * params,
+    const ggml_tensor * tensor,
+    const ggml_type default_type,
+    const tensor_metadata & tm
+) {
+    if (params->target_bpw != -1.0f || params->target_size != -1) { return tensor->type; }
+    if (!tensor_allows_quantization(params, qs.model.arch, tensor)) { return tensor->type; }
+    if (params->token_embedding_type < GGML_TYPE_COUNT && tm.category == TENSOR_CATEGORY_TOKEN_EMBD) {
         // per_layer_token_embd follows --token-embedding-type by default, but it is a large
         // separate table, so let an explicit --tensor-type name it
-        bool named = false;
-        if (std::strcmp(tensor->name, "per_layer_token_embd.weight") == 0) {
-            const std::string tensor_name(tensor->name);
-            for (const auto & [pattern, qtype] : qs.tensor_type_patterns) {
-                if (std::regex_search(tensor_name, pattern)) {
-                    named = true;
-                    break;
-                }
-            }
-        }
-        if (!named) {
-            return params->token_embedding_type;
-        }
-    }
-    if (params->output_tensor_type < GGML_TYPE_COUNT && tm.category == tensor_category::OUTPUT) {
-        return params->output_tensor_type;
+        const bool named = std::strcmp(tensor->name, "per_layer_token_embd.weight") == 0 && tensor_type_override_for(qs, tensor->name) != GGML_TYPE_COUNT;
+        if (!named) { return params->token_embedding_type; }
     }
+    if (params->output_tensor_type < GGML_TYPE_COUNT && tm.category == TENSOR_CATEGORY_OUTPUT) { return params->output_tensor_type; }

     ggml_type new_type = default_type;

     // get more optimal quantization type based on the tensor shape, layer, etc.
     if (ggml_is_quantized(default_type)) {
-        // if the user provided tensor types - use those
-        bool manual = false;
-        if (!qs.tensor_type_patterns.empty()) {
-            const std::string tensor_name(tensor->name);
-            for (const auto & [pattern, qtype] : qs.tensor_type_patterns) {
-                if (std::regex_search(tensor_name, pattern)) {
-                    if (qtype != new_type) {
-                        LLAMA_LOG_WARN("%s: %-36s - applying manual override: %s -> %s\n",
-                                       __func__, tensor_name.c_str(), ggml_type_name(new_type), ggml_type_name(qtype));
-                        new_type = qtype;
-                    }
-                    manual = true;
-                    break;
-                }
-            }
+        // if the user provided tensor types, use those
+        const ggml_type manual_type = tensor_type_override_for(qs, tensor->name);
+        const bool manual = manual_type != GGML_TYPE_COUNT;
+        if (manual && manual_type != new_type) {
+            LLAMA_LOG_WARN("%s: %-36s - applying manual override: %s -> %s\n",
+                __func__, tensor->name, ggml_type_name(new_type), ggml_type_name(manual_type));
+            new_type = manual_type;
         }

-        // if not manual - use the standard logic for choosing the quantization type based on the selected mixture
-        if (!manual && !params->pure) {
-            new_type = llama_tensor_get_type_impl(qs, new_type, tensor, params->ftype, tm.category);
-        }
+        // otherwise, use the standard logic
+        if (!manual && !params->pure) { new_type = llama_tensor_get_type_impl(qs, new_type, tensor, params->ftype, tm.category); }

-        // incompatible tensor shapes are handled here - fallback to a compatible type
+        // if incompatible tensor shape, fallback to a compatible type
         new_type = tensor_type_fallback(qs, tensor, new_type);
     }

     return new_type;
 }

-//
-// quantization implementation
-//
-
 // quantize rows [first_row, first_row + nrows), indexed globally across all expert matrices
 // note: chunks never cross an expert boundary since each expert has its own imatrix slice
-static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * f32_data, void * new_data, const int64_t chunk_size, int64_t first_row, int64_t nrows, int64_t nrows_per_expert, int64_t n_per_row, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
+static size_t llama_tensor_quantize_impl(ggml_type new_type,
+    const float * f32_data,
+    void * new_data,
+    const int64_t chunk_size,
+    int64_t first_row,
+    int64_t nrows,
+    int64_t nrows_per_expert,
+    int64_t n_per_row,
+    const float * imatrix,
+    std::vector<std::thread> & workers,
+    const int nthread
+) {
     const size_t row_size = ggml_row_size(new_type, n_per_row);

     auto imatrix_for_row = [=](int64_t row_global) {
@@ -877,12 +788,12 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float *
             const int64_t this_nrow  = std::min(nrows - row, nrows_per_expert - row_global % nrows_per_expert);
             void * this_data = (char *) new_data + row * row_size;
             size_t this_size = ggml_quantize_chunk(new_type, f32_data + row * n_per_row, this_data, 0, this_nrow, n_per_row, imatrix_for_row(row_global));
-            if (!ggml_validate_row_data(new_type, this_data, this_size)) {
-                throw std::runtime_error("quantized data validation failed");
-            }
+            if (!ggml_validate_row_data(new_type, this_data, this_size)) { throw std::runtime_error("quantized data validation failed"); }
+
             new_size += this_size;
             row += this_nrow;
         }
+
         return new_size;
     }

@@ -891,15 +802,13 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float *
     size_t new_size = 0;
     bool valid = true;
     auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
-            first_row, nrows, nrows_per_expert, n_per_row, row_size, imatrix_for_row]() {
+            first_row, nrows, nrows_per_expert, n_per_row, row_size, imatrix_for_row] {
         const int64_t nrows_per_chunk = chunk_size / n_per_row;
         size_t local_size = 0;
         while (true) {
             std::unique_lock<std::mutex> lock(mutex);
             if (counter >= nrows) {
-                if (local_size > 0) {
-                    new_size += local_size;
-                }
+                if (local_size > 0) { new_size += local_size; }
                 break;
             }
             const int64_t row        = counter;
@@ -921,140 +830,2346 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float *
             }
         }
     };
-    for (int it = 0; it < nthread - 1; ++it) {
-        workers.emplace_back(compute);
-    }
+
+    for (int it = 0; it < nthread - 1; ++it) { workers.emplace_back(compute); }
     compute();
     for (auto & w : workers) { w.join(); }
     workers.clear();
-    if (!valid) {
-        throw std::runtime_error("quantized data validation failed");
-    }
+    if (!valid) { throw std::runtime_error("quantized data validation failed"); }
+
     return new_size;
 }

-//
-// imatrix requirement check
-//
+// Returns tensor type overrides that meet a global file size or bpw target
+static std::unordered_map<std::string, ggml_type> target_bpw_type(
+    llama_model_loader & ml,
+    quantize_state_impl & qs,
+    const std::vector<const llama_model_loader::llama_tensor_weight *> & tensors,
+    const std::map<int, std::string> & mapped,
+    const std::unordered_map<std::string, std::vector<float>> * values_data,
+    const std::unordered_map<std::string, std::vector<float>> * activations_data,
+    const std::unordered_map<std::string, std::vector<float>> * statistics_data,
+    const std::vector<std::string> * stats_schema,
+    const std::unordered_map<std::string, ggml_type> * locked_tensors,
+    int nthread
+) {
+    bool interrupted = false;
+    std::mutex interrupt_mutex;
+    auto poll_interrupt = [&]() {
+        if (!qs.params->abort_callback) { return false; }
+        std::lock_guard<std::mutex> lock(interrupt_mutex);
+        if (!interrupted) { interrupted = qs.params->abort_callback(qs.params->abort_callback_data); }
+        return interrupted;
+    };

-static bool tensor_requires_imatrix(const char * tensor_name, const ggml_type dst_type, const llama_ftype ftype) {
-    if (tensor_name_match_token_embd(tensor_name) || tensor_name_match_output_weight(tensor_name)) {
-        return false;
-    }
-    switch (dst_type) {
-        case GGML_TYPE_IQ3_XXS:
-        case GGML_TYPE_IQ2_XXS:
-        case GGML_TYPE_IQ2_XS:
-        case GGML_TYPE_IQ2_S:
-        case GGML_TYPE_IQ1_M:
-        case GGML_TYPE_IQ1_S:
-            return true;
-        case GGML_TYPE_Q2_K:
-            // as a general rule, the k-type quantizations don't require imatrix data.
-            // the only exception is Q2_K tensors that are part of a Q2_K_S file.
-            return ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S;
-        default:
-            return false;
-    }
-}
+    // GGML_TYPE scores
+    struct type_scores {
+        ggml_type type = GGML_TYPE_COUNT;
+        float bpw = 0.0f;
+        size_t bytes = 0;
+        double error = 0.0;
+        double mse = 0.0;
+        double wce = 0.0;
+    };

-//
-// given a file type, get the default tensor type
-//
+    // Tensor quantization type choice
+    struct type_choice {
+        const llama_model_loader::llama_tensor_weight * w = nullptr;
+        std::vector<type_scores> candidates;
+        int choice = -1;
+        float min_bpw = 0.0;
+        float max_bpw = 0.0;
+        size_t n_elements = 0;
+        float boost = 1.0f;
+    };

-ggml_type llama_ftype_get_default_type(llama_ftype ftype) {
-    switch (ftype) {
-        case LLAMA_FTYPE_MOSTLY_Q4_0: return GGML_TYPE_Q4_0;
-        case LLAMA_FTYPE_MOSTLY_Q4_1: return GGML_TYPE_Q4_1;
-        case LLAMA_FTYPE_MOSTLY_Q5_0: return GGML_TYPE_Q5_0;
-        case LLAMA_FTYPE_MOSTLY_Q5_1: return GGML_TYPE_Q5_1;
-        case LLAMA_FTYPE_MOSTLY_Q8_0: return GGML_TYPE_Q8_0;
-        case LLAMA_FTYPE_MOSTLY_F16:  return GGML_TYPE_F16;
-        case LLAMA_FTYPE_MOSTLY_BF16: return GGML_TYPE_BF16;
-        case LLAMA_FTYPE_ALL_F32:     return GGML_TYPE_F32;
-        case LLAMA_FTYPE_MOSTLY_Q1_0: return GGML_TYPE_Q1_0;
-        case LLAMA_FTYPE_MOSTLY_Q2_0: return GGML_TYPE_Q2_0;
+    // Quantization types
+    constexpr ggml_type quant_types[] = {
+        GGML_TYPE_IQ1_S,
+        GGML_TYPE_IQ1_M,
+        GGML_TYPE_IQ2_XXS,
+        GGML_TYPE_IQ2_XS,
+        GGML_TYPE_IQ2_S,
+        GGML_TYPE_IQ3_XXS,
+        GGML_TYPE_IQ3_S,
+        GGML_TYPE_IQ4_XS,
+        GGML_TYPE_IQ4_NL,
+        GGML_TYPE_Q2_K,
+        GGML_TYPE_Q3_K,
+        GGML_TYPE_Q4_0,
+        GGML_TYPE_Q4_1,
+        GGML_TYPE_Q4_K,
+        GGML_TYPE_Q5_0,
+        GGML_TYPE_Q5_1,
+        GGML_TYPE_Q5_K,
+        GGML_TYPE_Q6_K,
+        GGML_TYPE_Q8_0,
+        GGML_TYPE_F16,
+        GGML_TYPE_BF16,
+    };

-        case LLAMA_FTYPE_MOSTLY_MXFP4_MOE: return GGML_TYPE_MXFP4;
+    constexpr double EPSILON = 1e-12;
+    constexpr double INFINITE = std::numeric_limits<double>::infinity();
+    constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2"
+    constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d;
+    constexpr float ffn_down_boost = 6.0f;
+    constexpr float output_boost = 3.0f;
+    constexpr float tied_embd_boost = 2.5f;
+    constexpr float attn_v_boost = 1.25f;
+    constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw
+    constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted
+    const char * func = __func__;

-        // K-quants
-        case LLAMA_FTYPE_MOSTLY_Q2_K_S:
-        case LLAMA_FTYPE_MOSTLY_Q2_K:    return GGML_TYPE_Q2_K;
-        case LLAMA_FTYPE_MOSTLY_IQ3_XS:  return GGML_TYPE_IQ3_S;
-        case LLAMA_FTYPE_MOSTLY_Q3_K_S:
-        case LLAMA_FTYPE_MOSTLY_Q3_K_M:
-        case LLAMA_FTYPE_MOSTLY_Q3_K_L:  return GGML_TYPE_Q3_K;
-        case LLAMA_FTYPE_MOSTLY_Q4_K_S:
-        case LLAMA_FTYPE_MOSTLY_Q4_K_M:  return GGML_TYPE_Q4_K;
-        case LLAMA_FTYPE_MOSTLY_Q5_K_S:
-        case LLAMA_FTYPE_MOSTLY_Q5_K_M:  return GGML_TYPE_Q5_K;
-        case LLAMA_FTYPE_MOSTLY_Q6_K:    return GGML_TYPE_Q6_K;
-        case LLAMA_FTYPE_MOSTLY_TQ1_0:   return GGML_TYPE_TQ1_0;
-        case LLAMA_FTYPE_MOSTLY_TQ2_0:   return GGML_TYPE_TQ2_0;
-        case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return GGML_TYPE_IQ2_XXS;
-        case LLAMA_FTYPE_MOSTLY_IQ2_XS:  return GGML_TYPE_IQ2_XS;
-        case LLAMA_FTYPE_MOSTLY_IQ2_S:   return GGML_TYPE_IQ2_XS;
-        case LLAMA_FTYPE_MOSTLY_IQ2_M:   return GGML_TYPE_IQ2_S;
-        case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return GGML_TYPE_IQ3_XXS;
-        case LLAMA_FTYPE_MOSTLY_IQ1_S:   return GGML_TYPE_IQ1_S;
-        case LLAMA_FTYPE_MOSTLY_IQ1_M:   return GGML_TYPE_IQ1_M;
-        case LLAMA_FTYPE_MOSTLY_IQ4_NL:  return GGML_TYPE_IQ4_NL;
-        case LLAMA_FTYPE_MOSTLY_IQ4_XS:  return GGML_TYPE_IQ4_XS;
-        case LLAMA_FTYPE_MOSTLY_IQ3_S:
-        case LLAMA_FTYPE_MOSTLY_IQ3_M:   return GGML_TYPE_IQ3_S;
+    // --target-exclude must leave at least one quant type in the pool
+    if (qs.has_ignored_types) {
+        bool all_ignored = true;
+        for (const ggml_type t : quant_types) {
+            if (!qs.ignored_types[t]) { all_ignored = false; break; }
+        }

-        default: return GGML_TYPE_COUNT;
+        if (all_ignored) { throw std::runtime_error(format("%s: --target-exclude bars every quant type in the selection pool\n", func)); }
     }
-}

+    // Tensor size in bytes for a given type
+    auto tensor_bytes = [](const ggml_tensor * gt, const ggml_type gq) -> size_t {
+        return (size_t)ggml_nrows(gt) * ggml_row_size(gq, gt->ne[0]);
+    };

-static void init_quantize_state_counters(quantize_state_impl & qs, std::vector<tensor_metadata> & metadata) {
-    for (auto & tm : metadata) {
-        tensor_category cat = tensor_get_category(tm.name);
-        tm.category = cat;
+    // Tensor bpw for a given type
+    auto tensor_bpw = [&](const ggml_tensor * gt, const ggml_type gq) -> double {
+        return (double)tensor_bytes(gt, gq) * 8.0 / (double)ggml_nelements(gt);
+    };

-        if (category_is_attn_v(cat)) {
-            ++qs.n_attention_wv;
-        }
+    // Check if tensor is compatible with quantization type
+    auto is_compatible = [](const ggml_tensor * gt, const ggml_type gq) -> bool {
+        const int64_t blck = ggml_blck_size(gq);
+        return blck <= 1 || gt->ne[0] % blck == 0;
+    };
+
+    // Get suitable fallback for type
+    auto make_compatible = [&](const ggml_tensor * gt, const ggml_type gq) -> ggml_type {
+        if (is_compatible(gt, gq)) { return gq; }
+        const ggml_type fb = fallback_type_for(gq);
+        return fb != GGML_TYPE_COUNT && is_compatible(gt, fb) ? fb : GGML_TYPE_F16;
+    };

-        if (cat == tensor_category::OUTPUT) {
-            qs.has_tied_embeddings = false;
+    // Check if tensor is an IQ type
+    auto is_iq = [](const enum ggml_type gt) {
+        switch (gt) {
+            case GGML_TYPE_IQ1_S:
+            case GGML_TYPE_IQ1_M:
+            case GGML_TYPE_IQ2_XXS:
+            case GGML_TYPE_IQ2_XS:
+            case GGML_TYPE_IQ2_S:
+            case GGML_TYPE_IQ3_XXS:
+            case GGML_TYPE_IQ3_S:
+            case GGML_TYPE_IQ4_NL:
+            case GGML_TYPE_IQ4_XS:
+                return true;
+            default:
+                return false;
         }
-    }
-    qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)qs.model.hparams.n_layer_all;
-}
+    };

-//
-// main quantization driver
-//
+    // Check if tensor can be quantized
+    auto can_quantize = [&](const ggml_tensor * gt) -> bool {
+        if (ggml_n_dims(gt) < 2 || ggml_n_dims(gt) > 3) { return false; } // skip 1D & 4D+ tensors
+        return tensor_allows_quantization(qs.params, qs.model.arch, gt);
+    };

-static void llama_model_quantize_impl(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
-    llama_ftype ftype = params->ftype;
+    // DJB2 hashing algorithm
+    auto djb2_hash = [&](const uint8_t * data, const size_t n, uint64_t h = 5381) -> uint64_t {
+        for (size_t i = 0; i < n; ++i) { h = (h << 5) + h + data[i]; }
+        return h ? h : HASH_MAGIC;
+    };

-    int nthread = params->nthread;
+    // Model ID from the metadata, the imatrix data and the pruned layers
+    const uint64_t model_id = [&] {
+        const size_t sz = gguf_get_meta_size(ml.metadata);
+        std::vector<uint8_t> buf(sz);
+        gguf_get_meta_data(ml.metadata, buf.data());
+        uint64_t h = djb2_hash(buf.data(), buf.size());
+        auto hash_bytes = [&](const void * data, const size_t n) { h = djb2_hash((const uint8_t *)data, n, h); };
+        auto hash_size = [&](const uint64_t n) { hash_bytes(& n, sizeof(n)); };
+
+        for (const auto * m : { values_data, activations_data, statistics_data }) {
+            const uint8_t present = m != nullptr;
+            hash_bytes(& present, sizeof(present));
+            if (!m) { continue; }
+
+            // the maps have no fixed order
+            std::vector<std::string> names;
+            names.reserve(m->size());
+            for (const auto & e : * m) { names.push_back(e.first); }
+            std::sort(names.begin(), names.end());
+
+            hash_size(names.size());
+            for (const auto & name : names) {
+                const std::vector<float> & v = m->at(name);
+                hash_size(name.size());
+                hash_bytes(name.data(), name.size());
+                hash_size(v.size());
+                hash_bytes(v.data(), v.size() * sizeof(float));
+            }
+        }

-    if (nthread <= 0) {
-        nthread = std::thread::hardware_concurrency();
-    }
+        const uint8_t has_schema = stats_schema != nullptr;
+        hash_bytes(& has_schema, sizeof(has_schema));
+        if (stats_schema) {
+            hash_size(stats_schema->size());
+            for (const auto & name : * stats_schema) {
+                hash_size(name.size());
+                hash_bytes(name.data(), name.size());
+            }
+        }

-    ggml_type default_type = llama_ftype_get_default_type(ftype);
-    if (default_type == GGML_TYPE_COUNT) {
-        throw std::runtime_error(format("invalid output file type %d\n", ftype));
-    }
+        for (const auto & [blk, num] : mapped) {
+            const int32_t b = blk;
+            hash_bytes(& b, sizeof(b));
+            hash_size(num.size());
+            hash_bytes(num.data(), num.size());
+        }

-    // mmap consistently increases speed on Linux, and also increases speed on Windows with
-    // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
-#if defined(__linux__) || defined(_WIN32)
-    constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_MMAP;
-#else
-    constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_NONE;
-#endif
+        return h;
+    }();

-    const llama_model_kv_override * kv_overrides = params->kv_overrides;
-    std::vector<std::string> splits = {};
-    llama_model_loader ml(/*metadata*/ nullptr, /*set_tensor_data*/ nullptr, /*set_tensor_data_ud*/ nullptr,
-        fname_inp, splits, /*file*/ nullptr, /*load_mode*/ load_mode, /*check_tensors*/ true, /*no_alloc*/ false, /*load_mtp*/ true, kv_overrides, nullptr);
-    ml.init_mappings(false); // no prefetching
+    std::string checkpoint_file;
+
+    {
+        char hex[17];
+        std::string name;
+        std::snprintf(hex, sizeof(hex), "%016" PRIx64, (uint64_t)model_id);
+        ml.get_key(LLM_KV_GENERAL_NAME, name, false);
+        name.erase(0, name.find_last_of('/') + 1);
+        std::replace(name.begin(), name.end(), ' ', '_');
+        name.empty() ? checkpoint_file = ml.arch_name : checkpoint_file = name;
+        checkpoint_file += "-" + std::string(hex) + ".bpw_state";
+
+        if (qs.params->state_file) {
+            if (qs.params->state_file[0] != '\0') { checkpoint_file = qs.params->state_file; }
+            const char * fname = checkpoint_file.c_str();
+            FILE * f = std::fopen(fname, "rb");
+            if (!f && errno == ENOENT) {
+                f = std::fopen(fname, "wbx");
+                if (!f) { throw std::runtime_error(format("%s: failed to open %s: %s\n", func, fname, std::strerror(errno))); }
+                std::fclose(f);
+                if (std::remove(fname) != 0) { LLAMA_LOG_WARN("%s: failed to remove %s: %s\n", func, fname, std::strerror(errno)); }
+            } else {
+                const bool readable = f && (std::fgetc(f) != EOF || !std::ferror(f));
+                const int err = errno;
+                if (f) { std::fclose(f); }
+                if (!readable) { throw std::runtime_error(format("%s: failed to open %s: %s\n", func, fname, std::strerror(err))); }
+            }
+        }
+    }
+
+    // Save vector<type_choice> state to disk
+    auto save_state = [&](const std::vector<type_choice> & all_tensors) {
+        const std::string tmp = checkpoint_file + ".tmp";
+        std::ofstream ofs(tmp, std::ios::binary | std::ios::trunc);
+        if (!ofs) {
+            LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (open error)\n", func, tmp.c_str());
+            return;
+        }
+        ofs.write((const char *)& STATE_MAGIC, sizeof(STATE_MAGIC));
+        ofs.write((const char *)& model_id, sizeof(model_id));
+        const uint64_t n = all_tensors.size();
+        ofs.write((const char *)& n, sizeof(n));
+        for (const auto & tn : all_tensors) {
+            const std::string name = ggml_get_name(tn.w->tensor);
+            const auto len = (uint32_t)name.size();
+            ofs.write((const char *)& len, sizeof(len));
+            ofs.write(name.data(), len);
+
+            const uint64_t sz = tn.candidates.size();
+            ofs.write((const char *)& sz, sizeof(sz));
+            ofs.write((const char *)& tn.choice, sizeof(tn.choice));
+            ofs.write((const char *)& tn.min_bpw, sizeof(tn.min_bpw));
+            ofs.write((const char *)& tn.max_bpw, sizeof(tn.max_bpw));
+            const uint64_t ne = tn.n_elements;
+            ofs.write((const char *)& ne, sizeof(ne));
+
+            for (const auto & c : tn.candidates) {
+                const int32_t tp = c.type;
+                const uint64_t bt = c.bytes;
+                ofs.write((const char *)& tp, sizeof(tp));
+                ofs.write((const char *)& c.bpw, sizeof(c.bpw));
+                ofs.write((const char *)& bt, sizeof(bt));
+                ofs.write((const char *)& c.error, sizeof(c.error));
+            }
+        }
+
+        const bool werr = ofs.fail() || ofs.bad();
+        ofs.close();
+        if (werr || ofs.fail() || ofs.bad()) {
+            std::remove(tmp.c_str());
+            LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (write error)\n", func, tmp.c_str());
+            return;
+        }
+
+        std::remove(checkpoint_file.c_str());
+        if (std::rename(tmp.c_str(), checkpoint_file.c_str()) != 0) {
+            LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (rename error), kept in %s\n", func, checkpoint_file.c_str(), tmp.c_str());
+            return;
+        }
+
+        LLAMA_LOG_INFO("\t%s: saved target progress for %zu tensors to %s\n", func, all_tensors.size(), checkpoint_file.c_str());
+    };
+
+    // Load vector<type_choice> state from disk
+    auto load_state = [&]() -> std::unordered_map<std::string, type_choice> {
+        std::ifstream ifs(checkpoint_file, std::ios::binary);
+        if (!ifs) { return {}; }
+
+        uint64_t magic = 0;
+        uint64_t id = 0;
+        ifs.read((char *)& magic, sizeof(magic));
+        ifs.read((char *)& id, sizeof(id));
+        if (id != model_id) {
+            LLAMA_LOG_WARN("%s: state file does not match this model, imatrix or pruned layers, ignoring\n", func);
+            return {};
+        }
+
+        if (magic != STATE_MAGIC) {
+            LLAMA_LOG_WARN("%s: invalid state file, ignoring\n", func);
+            return {};
+        }
+
+        std::unordered_map<std::string, type_choice> out;
+        uint64_t n = 0;
+        ifs.read((char *)& n, sizeof(n));
+        for (uint64_t i = 0; i < n; ++i) {
+            if (!ifs.good()) { break; }
+            uint32_t len = 0;
+            ifs.read((char *)& len, sizeof(len));
+            if (len >= GGML_MAX_NAME) {
+                LLAMA_LOG_WARN("%s: state file name length exceeds limits, ignoring\n", func);
+                return {};
+            }
+            std::string name(len, '\0');
+            ifs.read(name.data(), len);
+
+            type_choice si;
+            uint64_t sz = 0;
+            ifs.read((char *)& sz, sizeof(sz));
+            if (!ifs.good()) { break; }
+            if (sz == 0 || sz > std::size(quant_types)) {
+                LLAMA_LOG_WARN("%s: candidate count out of range, ignoring state file\n", func);
+                return {};
+            }
+            ifs.read((char *)& si.choice, sizeof(si.choice));
+            ifs.read((char *)& si.min_bpw, sizeof(si.min_bpw));
+            ifs.read((char *)& si.max_bpw, sizeof(si.max_bpw));
+            uint64_t ne = 0;
+            ifs.read((char *)& ne, sizeof(ne));
+            si.n_elements = (size_t)ne;
+
+            si.candidates.resize(sz);
+            for (auto & cd : si.candidates) {
+                if (!ifs.good()) { break; }
+                int32_t t = 0;
+                uint64_t b = 0;
+                ifs.read((char *)& t, sizeof(t));
+                if (!ifs.good()) { break; }
+                if (std::find(std::begin(quant_types), std::end(quant_types), t) == std::end(quant_types)) {
+                    LLAMA_LOG_WARN("%s: candidate type is not in the selection pool, ignoring state file\n", func);
+                    return {};
+                }
+                cd.type = (ggml_type)t;
+                ifs.read((char *)& cd.bpw, sizeof(cd.bpw));
+                ifs.read((char *)& b, sizeof(b));
+                cd.bytes = (size_t)b;
+                ifs.read((char *)& cd.error, sizeof(cd.error));
+            }
+
+            out.emplace(std::move(name), std::move(si));
+        }
+
+        if (!ifs.good()) {
+            LLAMA_LOG_WARN("%s: state file truncated or read error, ignoring\n", func);
+            return {};
+        }
+
+        LLAMA_LOG_INFO("\t%s: using %s (data for %zu tensors loaded)\n", func, checkpoint_file.c_str(), out.size());
+        return out;
+    };
+
+    // Check for interruptions and try save progress
+    auto throw_if_aborted = [&](const std::vector<type_choice> & all_tensors) {
+        if (interrupted) {
+            if (qs.params->state_file) {
+                if (qs.has_ignored_types) {
+                    LLAMA_LOG_WARN("\n\t%s: interrupted; state checkpoint is not written while --target-exclude is active\n", func);
+                } else {
+                    LLAMA_LOG_INFO("\n\t%s: interrupted, saving progress for %zu tensors to %s\n", func, all_tensors.size(), checkpoint_file.c_str());
+                    save_state(all_tensors);
+                }
+            } else {
+                LLAMA_LOG_INFO("\n\t%s: interrupted\n", func);
+            }
+
+            throw std::runtime_error("interrupted");
+        }
+    };
+
+    // Quality metrics
+    struct quant_error {
+        double error = std::numeric_limits<double>::infinity();
+        double mse = 0.0;
+        double wce = 0.0;
+    };
+
+    // Pre-calculated stats for MSE
+    struct mse_cache {
+        std::vector<double> row_sq_norm;
+    };
+
+    // Pre-calculated stats for WCE
+    struct wce_cache {
+        std::vector<double> row_sq_norm;
+    };
+
+    // Determine optimization strategy
+    auto is_angle_sensitive = [](const std::string & name) -> bool {
+        return name.find("attn_q.weight") != std::string::npos ||
+               name.find("attn_k.weight") != std::string::npos ||
+               name.find("attn_qkv.weight") != std::string::npos ||
+               name.find("attn_q_a.weight") != std::string::npos ||
+               name.find("attn_q_b.weight") != std::string::npos;
+    };
+
+    // Tensors sensitive to distortion in dot-product/inner-product calculations (TurboQuant)
+    auto is_inner_product_sensitive = [](const std::string & name) -> bool {
+        // Query/Key and variants (fused, latent, and enc/dec)
+        if (name.find("attn_q") != std::string::npos || name.find("attn_k") != std::string::npos) { return true; }
+        // Attention Output and variants (standard, enc/dec, cross-attn)
+        if (name.find("attn_o") != std::string::npos) { return true; }
+        // Value and variants
+        if (name.find("attn_v") != std::string::npos) { return true; }
+
+        return false;
+    };
+
+    // Estimate error for a given type using a sampled subset of rows
+    auto compute_quant_error = [&](
+        const ggml_tensor * t,
+        const ggml_type quant_type,
+        const std::vector<float> & f32_sample,
+        const std::vector<int64_t> & rows_sample,
+        const float * values_sample,
+        const float * activations_sample,
+        std::vector<uint8_t> & quantized_buffer,
+        std::vector<float> & dequantized_buffer,
+        const wce_cache * ref_wce = nullptr,
+        const mse_cache * ref_mse = nullptr,
+        const float * values_winsorized = nullptr
+    ) -> quant_error
+    {
+        const int64_t n_per_row = t->ne[0];
+        const int64_t ne2 = t->ne[2] > 0 ? t->ne[2] : 1;
+        const size_t sample_elems = f32_sample.size();
+        const size_t sample_rows = n_per_row > 0 ? sample_elems / (size_t)n_per_row : 0;
+
+        quant_error qe;
+        if (sample_rows == 0) {
+            qe.error = 0.0;
+            return qe;
+        }
+
+        const size_t row_sz = ggml_row_size(quant_type, n_per_row);
+        constexpr size_t SAFETY_PADDING = 256;
+        if (quantized_buffer.size() < row_sz + SAFETY_PADDING) { quantized_buffer.resize(row_sz + SAFETY_PADDING); }
+        if (dequantized_buffer.size() < (size_t)n_per_row) { dequantized_buffer.resize((size_t)n_per_row); }
+
+        const ggml_type_traits * traits = ggml_get_type_traits(quant_type);
+        if (!traits || !traits->to_float) { return qe; }
+
+        auto quant_dequant_row = [&](const float * src, float * dst, const float * v) {
+            ggml_quantize_chunk(quant_type, src, quantized_buffer.data(), 0, 1, n_per_row, v);
+            if (quant_type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)quantized_buffer.data(), dst, (int)n_per_row); }
+            else if (quant_type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)quantized_buffer.data(), dst, (int)n_per_row); }
+            else { traits->to_float(quantized_buffer.data(), dst, (int)n_per_row); }
+        };
+
+        const bool has_vals = values_sample != nullptr;
+        const bool has_acts = activations_sample != nullptr;
+        const bool use_wce = has_acts && has_vals && is_angle_sensitive(t->name);
+        const float * valw = values_winsorized ? values_winsorized : values_sample;
+
+        // Sampled stats for MSE
+        std::vector<double> local_row_sq_norm;
+        const std::vector<double> * ptr_row_sq_norm = nullptr;
+
+        // Setup reference stats pointers for MSE
+        if (!use_wce) {
+            if (ref_mse) {
+                ptr_row_sq_norm = & ref_mse->row_sq_norm;
+            } else {
+                local_row_sq_norm.reserve(sample_rows);
+                size_t off = 0;
+                for (int64_t s = 0; s < ne2; ++s) {
+                    const int64_t rs = rows_sample[s];
+                    const float * val = has_vals ? valw + s * n_per_row : nullptr;
+                    const float * act = has_acts ? activations_sample + s * n_per_row : nullptr;
+                    for (int64_t r = 0; r < rs; ++r) {
+                        const float * x = f32_sample.data() + off;
+                        double sum = 0.0;
+                        double bias_sum = 0.0;
+                        if (val && act) {
+                            for (int64_t j = 0; j < n_per_row; ++j) {
+                                const double act_j = act[j];
+                                const double variance = std::max(0.0, (double)val[j] - act_j * act_j);
+                                sum += variance * x[j] * x[j];
+                                bias_sum += act_j * x[j];
+                            }
+                            sum += bias_sum * bias_sum;
+                        } else if (val) {
+                            for (int64_t j = 0; j < n_per_row; ++j) { sum += std::max(0.0f, val[j]) * x[j] * x[j]; }
+                        } else {
+                            for (int64_t j = 0; j < n_per_row; ++j) { sum += x[j] * x[j]; }
+                        }
+
+                        local_row_sq_norm.push_back(sum);
+                        off += (size_t)n_per_row;
+                    }
+                }
+
+                ptr_row_sq_norm = & local_row_sq_norm;
+            }
+        }
+
+        // Helper for trimmed mean
+        auto trimmed_mean = [](std::vector<double> & v) -> double {
+            const auto n = v.size();
+            if (n == 0) { return 0.0; }
+            if (n < 100) { return std::accumulate(v.begin(), v.end(), 0.0) / (double)n; }
+            const auto k = (size_t)((double)n * 0.01); // trim 1% from each end
+            std::nth_element(v.begin(), v.begin() + k, v.end());
+            std::nth_element(v.begin() + k, v.end() - k, v.end());
+            return std::accumulate(v.begin() + k, v.end() - k, 0.0) / std::max(1.0, (double)(n - 2 * k));
+        };
+
+        // Weighted Cosine Error (WCE)
+        if (use_wce) {
+            double total_cos_error = 0.0;
+            size_t off = 0;
+            size_t sample_idx = 0;
+
+            const std::vector<double> * cached_norm_x = ref_wce && !ref_wce->row_sq_norm.empty() ? & ref_wce->row_sq_norm : nullptr;
+
+            for (int64_t s = 0; s < ne2; ++s) {
+                const int64_t rs = rows_sample[s];
+                if (rs == 0) { continue; }
+
+                const float * v  = values_sample + s * n_per_row;
+                const float * vw = valw + s * n_per_row;
+                double slice_sum = 0.0;
+
+                for (int64_t r = 0; r < rs; ++r, ++sample_idx) {
+                    const float * wx = f32_sample.data() + off;
+                    float * wy = dequantized_buffer.data();
+                    quant_dequant_row(wx, wy, v);
+
+                    double dot = 0.0;
+                    double ny = 0.0;
+                    double nx = 0.0;
+                    const bool calc_nx = !cached_norm_x;
+
+                    if (calc_nx) {
+                        for (int64_t j = 0; j < n_per_row; ++j) {
+                            const double w = std::max(0.0f, vw[j]);
+                            const double xj = wx[j];
+                            const double yj = wy[j];
+                            const double yw = yj * w;
+                            dot += xj * yw;
+                            ny += yj * yw;
+                            nx += xj * xj * w;
+                        }
+                    } else {
+                        nx = (* cached_norm_x)[sample_idx];
+                        for (int64_t j = 0; j < n_per_row; ++j) {
+                            const double w = std::max(0.0f, vw[j]);
+                            const double yj = wy[j];
+                            const double yw = yj * w;
+                            dot += (double) wx[j] * yw;
+                            ny += yj * yw;
+                        }
+                    }
+
+                    // Cosine Distance
+                    double cos_sim;
+                    const double norm_prod = nx * ny;
+
+                    if (norm_prod <= EPSILON) { cos_sim = nx <= EPSILON && ny <= EPSILON ? 1.0 : 0.0; }
+                    else { cos_sim = dot / std::sqrt(norm_prod); }
+
+                    if (cos_sim > 1.0) { cos_sim = 1.0; }
+                    else if (cos_sim < -1.0) { cos_sim = -1.0; }
+
+                    slice_sum += 1.0 - cos_sim;
+                    off += (size_t) n_per_row;
+                }
+
+                const double nrows = t->ne[1];
+                total_cos_error += slice_sum / (double)rs * (double)nrows;
+            }
+
+            qe.wce = total_cos_error;
+            qe.error = qe.wce;
+            return qe;
+        }
+
+        // Expected Output Error MSE (EOE-MSE)
+        size_t off = 0;
+        size_t row_idx = 0;
+        double total_wmse = 0.0;
+
+        for (int64_t s = 0; s < ne2; ++s) {
+            const int64_t rs = rows_sample[s];
+            if (rs == 0) { continue; }
+
+            const float * val  = has_vals ? values_sample + s * n_per_row : nullptr;
+            const float * mval = has_vals ? valw + s * n_per_row : nullptr;
+            const float * act  = has_acts ? activations_sample + s * n_per_row : nullptr;
+
+            std::vector<double> slice_mse_norm;
+            slice_mse_norm.reserve(rs);
+
+            for (int64_t r = 0; r < rs; ++r, ++row_idx) {
+                const float * x = f32_sample.data() + off;
+                float * y = dequantized_buffer.data();
+                quant_dequant_row(x, y, val);
+
+                double w_err = 0.0;
+                double bias_num = 0.0;
+
+                if (mval && act) {
+                    for (int64_t j = 0; j < n_per_row; ++j) {
+                        const double w = std::max(0.0f, mval[j]);
+                        const double a = act[j];
+                        const double e = (double)y[j] - (double)x[j];
+                        w_err += w * e * e;
+                        bias_num += a * e;
+                    }
+                    w_err += bias_num * bias_num;
+                } else if (mval) {
+                    for (int64_t j = 0; j < n_per_row; ++j) {
+                        const double w = std::max(0.0f, mval[j]);
+                        const double e = (double)y[j] - (double)x[j];
+                        w_err += w * e * e;
+                    }
+                } else {
+                    for (int64_t j = 0; j < n_per_row; ++j) {
+                        const double e = (double)y[j] - (double)x[j];
+                        w_err += e * e;
+                    }
+                }
+
+                const double rsn = (* ptr_row_sq_norm)[row_idx];
+                const double m_norm = rsn > EPSILON ? w_err / rsn : 0.0;
+                slice_mse_norm.push_back(std::isfinite(m_norm) ? m_norm : INFINITE);
+
+                off += (size_t)n_per_row;
+            }
+
+            const int64_t nrows = t->ne[1];
+            const double slice_mean_mse = trimmed_mean(slice_mse_norm) * (double)nrows;
+
+            total_wmse += slice_mean_mse;
+        }
+
+        qe.mse = total_wmse;
+        qe.error = total_wmse;
+        return qe;
+    };
+
+    std::unordered_map<std::string, type_choice> bpw_data;
+    if (qs.params->state_file && !checkpoint_file.empty()) { bpw_data = load_state(); }
+
+    auto has_side_data = [&](const auto * m, const std::string & name, const int64_t n2, const int64_t n_per_row) {
+        if (!m) { return false; }
+        auto it = m->find(name);
+        if (it == m->end()) { return false; }
+        const size_t req = (size_t) n2 * (size_t) n_per_row;
+        const size_t sz = it->second.size();
+        return sz == req || sz == (size_t) n_per_row;
+    };
+
+    // Look up stats used by CNIF
+    enum { ENERGY, H_NORM, L2_DIST, COSSIM, PCC, N_STATS };
+    const char * stat_names[N_STATS] = { "sum_sq", "h_norm", "l2_dist", "cossim", "pearson" };
+    size_t stat_pos[N_STATS] = {};
+    size_t min_stats = 0;
+    bool use_cnif = statistics_data && !statistics_data->empty();
+    for (int i = 0; use_cnif && i < N_STATS; ++i) {
+        const size_t n = stats_schema ? stats_schema->size() : 0;
+        size_t p = 0;
+        while (p < n && (* stats_schema)[p] != stat_names[i]) { ++p; }
+        if (p == n) {
+            LLAMA_LOG_WARN("%s: statistics have no %s metric, skipping CNIF; model quality may be compromised\n", func, stat_names[i]);
+            use_cnif = false;
+        }
+        stat_pos[i] = p;
+        min_stats = std::max(min_stats, p + 1);
+    }
+
+    // Precompute the Centered‑Normalized Importance Factor (CNIF)
+    std::unordered_map<std::string, float> cnif_scores;
+    if (use_cnif) {
+        struct tensor_score {
+            std::string name;
+            float score = 0.0f;
+        };
+
+        auto corr_error = [](float x) {
+            if (!std::isfinite(x)) { return 0.0f; }
+            return 1.0f - std::abs(std::clamp(x, -1.0f, 1.0f));
+        };
+
+        auto sort_scores = [](std::vector<tensor_score> & scores) {
+            std::sort(scores.begin(), scores.end(), [](const tensor_score & a, const tensor_score & b) {
+                return a.score < b.score || (a.score == b.score && a.name < b.name);
+            });
+        };
+
+        auto median = [](const auto & values, auto get_value) {
+            const size_t mid = values.size() / 2;
+            if (values.size() % 2 != 0) { return get_value(values[mid]); }
+            return 0.5f * (get_value(values[mid - 1]) + get_value(values[mid]));
+        };
+
+        auto rank = [&](std::vector<tensor_score> & scores, const float beta) {
+            if (scores.empty()) { return; }
+
+            sort_scores(scores);
+
+            if (scores.size() == 1) {
+                cnif_scores[scores[0].name] = 1.0f;
+                return;
+            }
+
+            for (size_t i = 0; i < scores.size();) {
+                size_t j = i + 1;
+                while (j < scores.size() && std::abs(scores[j].score - scores[i].score) <= 1e-6f) { ++j; }
+
+                const float p = 0.5f * (float)(i + j - 1) / (float)(scores.size() - 1);
+                const float scale = std::exp(beta * (2.0f * p - 1.0f));
+                for (size_t k = i; k < j; ++k) { cnif_scores[scores[k].name] = scale; }
+                i = j;
+            }
+        };
+
+        auto cnif = [&](std::vector<tensor_score> & scores, const float beta) {
+            constexpr size_t min_scores = 8;
+            constexpr float eps = 1e-6f;
+            constexpr float mad_factor = 1.4826f; // Median Absolute Deviation estimator for normal distributions
+
+            if (scores.size() < min_scores) {
+                rank(scores, beta);
+                return;
+            }
+
+            sort_scores(scores);
+
+            const float med = median(scores, [](const tensor_score & s) { return s.score; });
+            std::vector<float> deviations;
+            deviations.reserve(scores.size());
+            for (const auto & score : scores) { deviations.push_back(std::abs(score.score - med)); }
+
+            std::sort(deviations.begin(), deviations.end());
+            const float mad = median(deviations, [](float x) { return x; });
+            if (mad <= eps) {
+                rank(scores, beta);
+                return;
+            }
+
+            const float inv_scale = 1.0f / (mad_factor * mad + eps);
+            for (const auto & score : scores) {
+                const float z = std::clamp((score.score - med) * inv_scale, -4.0f, 4.0f);
+                cnif_scores[score.name] = std::exp(beta * std::tanh(0.8f * z));
+            }
+        };
+
+        std::vector<tensor_score> mse_scores;
+        std::vector<tensor_score> wce_scores;
+        mse_scores.reserve(tensors.size());
+        wce_scores.reserve(tensors.size());
+        cnif_scores.reserve(tensors.size());
+
+        for (const auto * tw : tensors) {
+            const ggml_tensor * tensor = tw->tensor;
+            if (!can_quantize(tensor)) { continue; }
+
+            const std::string name = remap_imatrix(ggml_get_name(tensor), mapped);
+            auto it = statistics_data->find(name);
+            if (it == statistics_data->end() || it->second.size() < min_stats) { continue; }
+
+            // Heads have no previous-layer counterpart so they stay outside the pool at cnif = 1.0
+            if (tensor_name_match_token_embd(ggml_get_name(tensor)) || tensor_name_match_output_weight(ggml_get_name(tensor))) { continue; }
+
+            const auto & ts = it->second;
+            const float h_norm = std::isfinite(ts[stat_pos[H_NORM]]) ? std::clamp(ts[stat_pos[H_NORM]], 0.0f, 100.0f) : 100.0f;
+            const float concentration = 1.0f - h_norm / 100.0f;
+            const float energy = std::isfinite(ts[stat_pos[ENERGY]]) ? std::max(0.0f, ts[stat_pos[ENERGY]]) : 0.0f;
+            const float l2_dist = std::isfinite(ts[stat_pos[L2_DIST]]) ? std::max(0.0f, ts[stat_pos[L2_DIST]]) : 0.0f;
+            const float rel_l2 = l2_dist / (std::sqrt(energy) + EPSILON);
+            const float density = rel_l2 / (1.0f + rel_l2);
+            const float fragility = 0.5f * (corr_error(ts[stat_pos[COSSIM]]) + corr_error(ts[stat_pos[PCC]]));
+
+            const int64_t n_per_row = tensor->ne[0];
+            const int64_t ne2 = tensor->ne[2] > 0 ? tensor->ne[2] : 1;
+            const bool has_vals = has_side_data(values_data, name, ne2, n_per_row);
+            const bool has_acts = has_side_data(activations_data, name, ne2, n_per_row);
+            const bool use_wce = has_vals && has_acts && is_angle_sensitive(name);
+
+            // parameters tuned for better results at low bitrates (<= 4.5 bits)
+            const float score = use_wce
+                ? 0.75f * concentration + 0.15f * density + 0.10f * fragility
+                : 0.40f * concentration + 0.35f * density + 0.25f * fragility;
+
+            auto & scores = use_wce ? wce_scores : mse_scores;
+            scores.push_back({ name, score });
+        }
+
+        cnif(mse_scores, 0.40f);
+        cnif(wce_scores, 0.25f);
+    }
+
+    // Outlier mitigation (simulate TurboQuant rotation)
+    auto outlier_smoothing = [&](const std::vector<float>& src, std::vector<float>& dst, const int64_t n_rows, const int64_t len) {
+        dst.resize(src.size());
+        for (int64_t r = 0; r < n_rows; ++r) {
+            const float* src_row = src.data() + r * len;
+            float* dst_row = dst.data() + r * len;
+
+            // Fast variance estimation
+            double mean_d = 0.0;
+            double M2 = 0.0;
+            for (int64_t i = 0; i < len; ++i) {
+                double delta = src_row[i] - mean_d;
+                mean_d += delta / (i + 1);
+                M2 += delta * (src_row[i] - mean_d);
+            }
+
+            const float mean = mean_d;
+            float variance = M2 / len;
+            const float std_dev = std::sqrt(std::max(0.0f, variance));
+
+            // Clip at 4 standard deviations to simulate the effect of rotation spreading the outlier energy
+            float clip_val = 4.0f * std_dev;
+
+            if (clip_val > 1e-4f) {
+                for (int64_t i = 0; i < len; ++i) { dst_row[i] = std::clamp(src_row[i], mean - clip_val, mean + clip_val); }
+            } else {
+                std::memcpy(dst_row, src_row, len * sizeof(float));
+            }
+        }
+    };
+
+    // HMT Randomized SVD condition number estimator: kappa = sigma 1 / sigma 20. See https://arxiv.org/abs/0909.4061
+    auto randomized_svd_condition_number = [&](const std::vector<float> & f32_sample, const int64_t n_per_row, const int64_t total_rows_sampled) -> float {
+        constexpr int64_t target_rank = 25;
+        constexpr int64_t k = 20;   // 20th singular value for condition number estimation
+        constexpr float eps_norm = 1e-8f;
+        constexpr float eps_eig = EPSILON;
+        constexpr int jacobi_sweeps = 20;
+        if (total_rows_sampled < 1 || n_per_row < 1) { return INFINITE; }
+
+        const int64_t m = total_rows_sampled;
+        const int64_t n = n_per_row;
+
+        // Jacobi eigenvalue decomposition for symmetric matrix
+        auto jacobi_diag = [&](std::vector<float> & A, const int64_t dim, const int max_sweeps) {
+            for (int sweep = 0; sweep < max_sweeps; ++sweep) {
+                bool converged = true;
+                for (int64_t p = 0; p < dim - 1; ++p) {
+                    for (int64_t q = p + 1; q < dim; ++q) {
+                        const float app = A[p * dim + p];
+                        const float aqq = A[q * dim + q];
+                        const float apq = A[p * dim + q];
+                        if (std::abs(apq) <= eps_eig) { continue; }
+                        converged = false;
+
+                        const float tau = (aqq - app) / (2.0f * apq);
+                        const float t   = tau >= 0.0f
+                            ? 1.0f / (tau + std::sqrt(1.0f + tau * tau))
+                            : -1.0f / (-tau + std::sqrt(1.0f + tau * tau));
+                        const float c   = 1.0f / std::sqrt(1.0f + t * t);
+                        const float s   = c * t;
+
+                        A[p * dim + p] = app - t * apq;
+                        A[q * dim + q] = aqq + t * apq;
+                        A[p * dim + q] = 0.0f;
+                        A[q * dim + p] = 0.0f;
+
+                        for (int64_t r = 0; r < dim; ++r) {
+                            if (r == p || r == q) { continue; }
+                            const float arp = A[r * dim + p];
+                            const float arq = A[r * dim + q];
+                            A[r * dim + p] = c * arp - s * arq;
+                            A[p * dim + r] = A[r * dim + p];
+                            A[r * dim + q] = s * arp + c * arq;
+                            A[q * dim + r] = A[r * dim + q];
+                        }
+                    }
+                }
+
+                if (converged) { break; }
+            }
+        };
+
+        auto matmul_a = [&](
+            const std::vector<float> & A, const int64_t rows_a,
+            const int64_t cols_a, const std::vector<float> & B,
+            const int64_t cols_b, std::vector<float> & C
+        )
+        {
+            C.assign((size_t)rows_a * (size_t)cols_b, 0.0f);
+            for (int64_t i = 0; i < rows_a; ++i) {
+                const size_t i_a = (size_t)i * (size_t)cols_a;
+                const size_t i_c = (size_t)i * (size_t)cols_b;
+                for (int64_t l = 0; l < cols_a; ++l) {
+                    const float aik = A[i_a + (size_t)l];
+                    if (aik == 0.0f) { continue; }
+                    const size_t k_b = (size_t)l * (size_t)cols_b;
+                    for (int64_t j = 0; j < cols_b; ++j) {
+                        C[i_c + (size_t)j] += aik * B[k_b + (size_t)j];
+                    }
+                }
+            }
+        };
+
+        // C = A^T * B  (A is rows_a x cols_a, B is rows_a x cols_b, C is cols_a x cols_b)
+        auto matmul_b = [&](
+            const std::vector<float> & A,
+            const int64_t rows_a,
+            const int64_t cols_a,
+            const std::vector<float> & B, const int64_t cols_b,
+            std::vector<float> & C
+        )
+        {
+            C.assign((size_t)cols_a * (size_t)cols_b, 0.0f);
+            for (int64_t i = 0; i < cols_a; ++i) {
+                const size_t i_c = (size_t)i * (size_t)cols_b;
+                for (int64_t l = 0; l < rows_a; ++l) {
+                    const float aki = A[(size_t)l * (size_t)cols_a + (size_t)i];
+                    if (aki == 0.0f) { continue; }
+                    const size_t k_b = (size_t)l * (size_t)cols_b;
+                    for (int64_t j = 0; j < cols_b; ++j) {
+                        C[i_c + (size_t)j] += aki * B[k_b + (size_t)j];
+                    }
+                }
+            }
+        };
+
+        // Modified Gram-Schmidt QR Decomposition. Q gets orthonormal columns from Y (Y is rows x cols)
+        auto mgs_qr = [&](
+            const std::vector<float> & Y,
+            const int64_t rows, const int64_t cols,
+            std::vector<float> & Q
+        )
+        {
+            Q.assign((size_t)rows * (size_t)cols, 0.0f);
+            std::vector<float> v(rows);
+            for (int64_t j = 0; j < cols; ++j) {
+                for (int64_t i = 0; i < rows; ++i) {
+                    v[i] = Y[(size_t)i * (size_t)cols + (size_t)j];
+                }
+
+                for (int64_t b = 0; b < j; ++b) {
+                    double dot = 0.0;
+                    for (int64_t i = 0; i < rows; ++i) {
+                        dot += (double)v[i] * (double)Q[(size_t)i * (size_t)cols + (size_t)b];
+                    }
+                    for (int64_t i = 0; i < rows; ++i) {
+                        v[i] -= (float)dot * Q[(size_t)i * (size_t)cols + (size_t)b];
+                    }
+                }
+
+                double norm_sq = 0.0;
+                for (int64_t i = 0; i < rows; ++i) {
+                    norm_sq += (double)v[i] * (double)v[i];
+                }
+
+                const float norm = std::sqrt((float)norm_sq);
+                if (norm > eps_norm) {
+                    const float inv = 1.0f / norm;
+                    for (int64_t i = 0; i < rows; ++i) {
+                        Q[(size_t)i * (size_t)cols + (size_t)j] = v[i] * inv;
+                    }
+                }
+            }
+        };
+
+        // Filter and row-normalize valid rows (exclude NaN/Inf and near zero norm rows)
+        std::vector<float> norm_matrix;
+        norm_matrix.reserve((size_t)m * (size_t)n);
+        for (int64_t r = 0; r < m; ++r) {
+            const float * row = f32_sample.data() + r * n;
+            double l2_sq = 0.0;
+            for (int64_t j = 0; j < n; ++j) {
+                const float val = row[j];
+                if (!std::isfinite(val)) { l2_sq = -1.0; break; }
+                l2_sq += (double)val * (double)val;
+            }
+
+            if (l2_sq < 0.0) { continue; }
+            const float l2 = std::sqrt((float)l2_sq);
+            if (l2 <= eps_norm) { continue; }
+            const float inv_l2 = 1.0f / l2;
+            const size_t cur = norm_matrix.size();
+            norm_matrix.resize(cur + (size_t)n);
+            float * dst = norm_matrix.data() + cur;
+            for (int64_t j = 0; j < n; ++j) { dst[j] = row[j] * inv_l2; }
+        }
+
+        const int64_t valid_m = (int64_t)norm_matrix.size() / n;
+        if (valid_m < 2) { return INFINITE; }
+        const bool hmt_direct = valid_m >= target_rank;
+        const bool hmt_transpose = !hmt_direct && n >= target_rank;
+
+        // Deterministic random Gaussian projection using Golden Ratio * Random Scrambling Hashing
+        std::mt19937 rng((uint64_t)(n_per_row * 0x9E3779B97F4A7C15ULL + valid_m * 0xBF58476D1CE4E5B9ULL));
+        std::normal_distribution<float> normal(0.0f, 1.0f);
+
+        // Estimate the condition number (kappa)
+        auto condition_number = [&](const std::vector<float> & eigenvalues) -> float {
+            if ((int64_t)eigenvalues.size() < k) { return INFINITE; }
+            const float sigma_max = std::sqrt(std::max(0.0f, eigenvalues[0]));
+            const float sigma_min = std::sqrt(std::max(0.0f, eigenvalues[k - 1]));
+            if (sigma_min <= eps_eig) { return INFINITE; }
+
+            return sigma_max / sigma_min;
+        };
+
+        if (hmt_direct) {
+            // HMT on A (valid_m x n) with q=1 power iteration
+            std::vector<float> Omega((size_t)n * (size_t)target_rank);
+            for (auto & v : Omega) { v = normal(rng); }
+
+            std::vector<float> Y0;
+            std::vector<float> Z;
+            std::vector<float> Y1;
+            std::vector<float> Q;
+            std::vector<float> B;
+            std::vector<float> C;
+            matmul_a(norm_matrix, valid_m, n, Omega, target_rank, Y0);  // Y0 = A * Omega
+            matmul_b(norm_matrix, valid_m, n, Y0, target_rank, Z);      // Z = A^T * Y0
+            matmul_a(norm_matrix, valid_m, n, Z, target_rank, Y1);      // Y1 = A * Z
+            mgs_qr(Y1, valid_m, target_rank, Q);
+            matmul_b(Q, valid_m, target_rank, norm_matrix, n, B);       // B = Q^T * A
+
+            // C = B * B^T (target_rank x target_rank)
+            C.assign((size_t)target_rank * (size_t)target_rank, 0.0f);
+            for (int64_t i = 0; i < target_rank; ++i) {
+                for (int64_t j = 0; j < target_rank; ++j) {
+                    double sum = 0.0;
+                    for (int64_t l = 0; l < n; ++l) {
+                        sum += (double)B[(size_t)i * (size_t)n + (size_t)l] * (double)B[(size_t)j * (size_t)n + (size_t)l];
+                    }
+
+                    C[(size_t)i * (size_t)target_rank + (size_t)j] = (float)sum;
+                }
+            }
+
+            jacobi_diag(C, target_rank, jacobi_sweeps);
+            std::vector<float> eigenvalues;
+            eigenvalues.reserve(target_rank);
+            for (int64_t i = 0; i < target_rank; ++i) { eigenvalues.push_back(C[i * target_rank + i]); }
+            std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater<float>());
+
+            return condition_number(eigenvalues);
+        }
+
+        if (hmt_transpose) {
+            // HMT on A^T (n x valid_m) with q=1 power iteration
+            std::vector<float> Omega((size_t)valid_m * (size_t)target_rank);
+            for (auto & v : Omega) { v = normal(rng); }
+
+            std::vector<float> Y0;
+            std::vector<float> Z;
+            std::vector<float> Y1;
+            std::vector<float> Q;
+            std::vector<float> B;
+            std::vector<float> C;
+            matmul_b(norm_matrix, valid_m, n, Omega, target_rank, Y0);   // Y0 = A^T * Omega
+            matmul_a(norm_matrix, valid_m, n, Y0, target_rank, Z);       // Z = A * Y0
+            matmul_b(norm_matrix, valid_m, n, Z, target_rank, Y1);       // Y1 = A^T * Z
+            mgs_qr(Y1, n, target_rank, Q);
+
+            // B = Q^T * A^T  (target_rank x valid_m)
+            B.assign((size_t)target_rank * (size_t)valid_m, 0.0f);
+            for (int64_t j = 0; j < target_rank; ++j) {
+                for (int64_t k = 0; k < valid_m; ++k) {
+                    double sum = 0.0;
+                    for (int64_t i = 0; i < n; ++i) {
+                        sum += (double)Q[(size_t)i * (size_t)target_rank + (size_t)j] * (double)norm_matrix[(size_t)k * (size_t)n + (size_t)i];
+                    }
+
+                    B[(size_t)j * (size_t)valid_m + (size_t)k] = (float)sum;
+                }
+            }
+
+            // C = B * B^T (target_rank x target_rank)
+            C.assign((size_t)target_rank * (size_t)target_rank, 0.0f);
+            for (int64_t i = 0; i < target_rank; ++i) {
+                for (int64_t j = 0; j < target_rank; ++j) {
+                    double sum = 0.0;
+                    for (int64_t l = 0; l < valid_m; ++l) {
+                        sum += (double)B[(size_t)i * (size_t)valid_m + (size_t)l] * (double)B[(size_t)j * (size_t)valid_m + (size_t)l];
+                    }
+
+                    C[(size_t)i * (size_t)target_rank + (size_t)j] = (float)sum;
+                }
+            }
+
+            jacobi_diag(C, target_rank, jacobi_sweeps);
+            std::vector<float> eigenvalues;
+            eigenvalues.reserve(target_rank);
+            for (int64_t i = 0; i < target_rank; ++i) { eigenvalues.push_back(C[i * target_rank + i]); }
+            std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater<float>());
+
+            return condition_number(eigenvalues);
+        }
+
+        // Fallback: full thin SVD via Gram matrix of smaller dimension + Jacobi
+        const bool gram_rows = valid_m <= n;
+        if (gram_rows) {
+            const int64_t gram_dim = valid_m;
+            std::vector<float> G((size_t)gram_dim * (size_t)gram_dim, 0.0f);
+            for (int64_t i = 0; i < gram_dim; ++i) {
+                for (int64_t j = i; j < gram_dim; ++j) {
+                    double sum = 0.0;
+                    for (int64_t l = 0; l < n; ++l) {
+                        sum += (double)norm_matrix[(size_t)i * (size_t)n + (size_t)l] * (double)norm_matrix[(size_t)j * (size_t)n + (size_t)l];
+                    }
+
+                    G[(size_t)i * (size_t)gram_dim + (size_t)j] = (float)sum;
+                    G[(size_t)j * (size_t)gram_dim + (size_t)i] = (float)sum;
+                }
+            }
+
+            jacobi_diag(G, gram_dim, jacobi_sweeps);
+            std::vector<float> eigenvalues;
+            eigenvalues.reserve(gram_dim);
+            for (int64_t i = 0; i < gram_dim; ++i) { eigenvalues.push_back(G[i * gram_dim + i]); }
+            std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater<float>());
+
+            return condition_number(eigenvalues);
+        }
+
+        // G = A^T * A (n x n)
+        const int64_t gram_dim = n;
+        std::vector<float> G((size_t)gram_dim * (size_t)gram_dim, 0.0f);
+        for (int64_t i = 0; i < gram_dim; ++i) {
+            for (int64_t j = i; j < gram_dim; ++j) {
+                double sum = 0.0;
+                for (int64_t l = 0; l < valid_m; ++l) {
+                    sum += (double)norm_matrix[(size_t)l * (size_t)n + (size_t)i] * (double)norm_matrix[(size_t)l * (size_t)n + (size_t)j];
+                }
+
+                G[(size_t)i * (size_t)gram_dim + (size_t)j] = (float)sum;
+                G[(size_t)j * (size_t)gram_dim + (size_t)i] = (float)sum;
+            }
+        }
+
+        jacobi_diag(G, gram_dim, jacobi_sweeps);
+        std::vector<float> eigenvalues;
+        eigenvalues.reserve(gram_dim);
+        for (int64_t i = 0; i < gram_dim; ++i) { eigenvalues.push_back(G[i * gram_dim + i]); }
+        std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater<float>());
+
+        return condition_number(eigenvalues);
+    };
+
+    // Map [1, ∞) to [1, M]; alpha controls mapping aggressiveness towards M
+    auto squash_kappa = [](float kappa) -> float {
+        constexpr float M = 5.0f;
+        constexpr float alpha = 0.15f;
+        if (!std::isfinite(kappa)) { return M; }
+
+        return 1.0f + (M - 1.0f) * std::tanh(alpha * std::log(kappa));
+    };
+
+    // Parallelize tensor processing (courtesy of https://github.com/ddh0)
+    const int n_workers = std::max(1, std::min(nthread, (int) tensors.size()));
+    const size_t max_buf_worker = std::max<size_t>(1, (qs.params->max_buf_size ? qs.params->max_buf_size : LLAMA_QUANT_MAX_BUF_SIZE) / n_workers);
+
+    auto process_tensor = [&](
+        const llama_model_loader::llama_tensor_weight * tw,
+        std::vector<no_init<uint8_t>> & thread_local_buffer,
+        std::vector<float> & f32_sample,
+        std::vector<float> & smoothed_sample,
+        std::vector<float> & val_cache,
+        std::vector<float> & act_cache,
+        std::mutex & loader_mutex,
+        std::mutex & log_mutex
+    ) -> std::optional<type_choice>
+    {
+        ggml_tensor * tensor = tw->tensor;
+        struct tensor_guard {
+            ggml_tensor * t;
+            void * orig;
+            ~tensor_guard() { t->data = orig; }
+        } guard{tensor, tensor->data};
+
+        const std::string name = ggml_get_name(tensor);
+        if (poll_interrupt()) { return std::nullopt; }
+
+        const std::string remapped_name = remap_imatrix(name, mapped);
+
+        // Check cache
+        if (auto tn = bpw_data.find(name); tn != bpw_data.end()) {
+            type_choice tc;
+            tc.w = tw;
+            tc.candidates = tn->second.candidates;
+            tc.choice = tn->second.choice;
+            tc.min_bpw = tn->second.min_bpw;
+            tc.max_bpw = tn->second.max_bpw;
+            tc.n_elements = tn->second.n_elements ? tn->second.n_elements : (size_t)ggml_nelements(tensor);
+            // remove ignored types
+            if (qs.has_ignored_types) {
+                tc.candidates.erase(std::remove_if(tc.candidates.begin(), tc.candidates.end(),
+                    [&](const type_scores & c) { return c.type >= 0 && c.type < GGML_TYPE_COUNT && qs.ignored_types[c.type]; }),
+                    tc.candidates.end());
+
+                if (tc.candidates.empty()) {
+                    // locked tensors are exempt
+                    const bool is_locked = locked_tensors && locked_tensors->find(name) != locked_tensors->end();
+                    if (!is_locked) {
+                        throw std::runtime_error(format("%s: tensor '%s' has %zu quant type candidates left after --target-exclude\n", func, name.c_str(), tc.candidates.size()));
+                    }
+
+                    type_scores fb;
+                    fb.type = tensor->type;
+                    fb.bytes = ggml_nbytes(tensor);
+                    fb.bpw = fb.bytes * 8.0f / tc.n_elements;
+                    tc.candidates.push_back(fb);
+                }
+
+                tc.choice = 0;
+            }
+
+            return tc;
+        }
+
+        {
+            std::lock_guard<std::mutex> lock(log_mutex);
+            LLAMA_LOG_INFO("\t%s: - processing tensor %45s \t(%12" PRId64 " elements)\n", func, name.c_str(), ggml_nelements(tensor));
+        }
+
+        const size_t tensor_nbytes = ggml_nbytes(tensor);
+        const size_t row_nbytes = ggml_row_size(tensor->type, tensor->ne[0]);
+        const bool stream_rows = !ml.use_mmap && tensor_nbytes > max_buf_worker;
+
+        if (!stream_rows) {
+            if (!ml.use_mmap && thread_local_buffer.size() < tensor_nbytes) { thread_local_buffer.resize(tensor_nbytes); }
+            std::lock_guard<std::mutex> lock(loader_mutex);
+            tensor->data = const_cast<void *>(ml.load_data_range(*tw, 0, tensor_nbytes, thread_local_buffer.data()));
+        } else if (thread_local_buffer.size() < row_nbytes) {
+            thread_local_buffer.resize(row_nbytes);
+        }
+
+        auto load_row = [&](const int64_t slice, const int64_t row) -> const uint8_t * {
+            const size_t offs = ((size_t) slice*tensor->ne[1] + row) * row_nbytes;
+            if (!stream_rows) { return (const uint8_t *) tensor->data + offs; }
+            std::lock_guard<std::mutex> lock(loader_mutex);
+            return (const uint8_t *) ml.load_data_range(*tw, offs, row_nbytes, thread_local_buffer.data());
+        };
+
+        // Sampling
+        const int64_t n_per_row = tensor->ne[0];
+        const int64_t nrows_total = tensor->ne[1];
+        const int64_t ne2 = tensor->ne[2] > 0 ? tensor->ne[2] : 1;
+
+        // Compute rows based on tensor shape and slice count
+        auto sample_count = [&](const int64_t n, const int64_t rows, const int64_t n2, const bool has_acts) {
+            constexpr double k_scale = 1.0;
+            const double tensor_budget = (has_acts ? 1.0 : 0.5) * k_scale * 1024.0 * 1024.0;
+            const double scale = std::clamp(std::sqrt(std::max(1.0, (double)rows) / 4096.0), 0.5, 2.0); // more rows for large tensors
+            const double slice_budget = tensor_budget * scale / std::max<int64_t>(1, n2);
+            const int64_t min_r = (has_acts ? 512 : 256) * (int64_t)k_scale;
+            const int64_t max_r = 4096 * (int64_t)k_scale;
+            int64_t tr = std::llround(slice_budget / std::max<int64_t>(1, n));
+            tr = std::max<int64_t>(min_r, std::min<int64_t>(tr, std::min<int64_t>(rows, max_r)));
+            if (rows <= min_r * 2) { tr = rows; }
+            return tr;
+        };
+
+        const int64_t rows_to_sample = sample_count(n_per_row, nrows_total, ne2, activations_data != nullptr);
+        f32_sample.clear();
+        f32_sample.reserve((size_t)ne2 * (size_t)std::min(nrows_total, rows_to_sample) * (size_t)n_per_row);
+        std::vector<int64_t> rows_sample(ne2, 0);
+
+        // Populate f32_sample
+        {
+            const ggml_type src_type = tensor->type;
+            const ggml_type_traits * traits = ggml_get_type_traits(src_type);
+
+            for (int64_t slice = 0; slice < ne2; ++slice) {
+                std::mt19937 rng(djb2_hash((const uint8_t*)name.data(), name.size()) ^ HASH_MAGIC ^ slice);
+                const int64_t limit = std::max<int64_t>(1, std::min<int64_t>(nrows_total, rows_to_sample));
+                const double stride = (double)nrows_total / limit;
+                int64_t offset = stride > 1.0 ? std::uniform_int_distribution<int64_t>(0, (int64_t)stride - 1)(rng) : 0;
+
+                int64_t count = 0;
+                for (int64_t i = 0; i < limit; ++i) {
+                    int64_t r = offset + std::llround(i * stride);
+                    if (r >= nrows_total) { break; }
+
+                    const uint8_t * src = load_row(slice, r);
+                    size_t cur_sz = f32_sample.size();
+                    f32_sample.resize(cur_sz + n_per_row);
+                    float * dst = f32_sample.data() + cur_sz;
+
+                    if (src_type == GGML_TYPE_F32) { std::memcpy(dst, src, n_per_row * sizeof(float)); }
+                    else if (src_type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t*)src, dst, (int)n_per_row); }
+                    else if (src_type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t*)src, dst, (int)n_per_row); }
+                    else if (traits && traits->to_float) { traits->to_float(src, dst, (int)n_per_row); }
+                    else { throw std::runtime_error(format("unsupported source type %s for sampling", ggml_type_name(src_type))); }
+
+                    ++count;
+                }
+
+                rows_sample[slice] = count;
+            }
+        }
+
+        smoothed_sample.clear();
+        bool is_outlier_heavy = remapped_name.find("ffn_down") != std::string::npos;
+        if (is_outlier_heavy) { outlier_smoothing(f32_sample, smoothed_sample, rows_to_sample * ne2, n_per_row); }
+
+        // Prepare side data
+        auto get_side_data = [&](const auto * m) {
+            if (!m) { return std::pair<const float *, size_t>{nullptr, 0}; }
+            auto it = m->find(remapped_name);
+            return it != m->end() ? std::pair{it->second.data(), it->second.size()} : std::pair<const float*, size_t>{nullptr, 0};
+        };
+
+        auto [val_ptr, val_sz] = get_side_data(values_data);
+        auto [act_ptr, act_sz] = get_side_data(activations_data);
+
+        // Cache WCE stats per tensor
+        const float * val_vec_ptr = nullptr;
+        const float * act_vec_ptr = nullptr;
+
+        auto prepare_broadcast = [&](const float* src, size_t sz, std::vector<float>& storage, const float*& out_ptr) {
+            if (!src) {
+                out_ptr = nullptr;
+                return;
+            }
+            size_t req = (size_t)ne2 * n_per_row;
+            if (sz == req) { out_ptr = src; }
+            else if (sz == (size_t)n_per_row) {
+                storage.resize(req);
+                for (int s = 0; s < ne2; ++s) { std::memcpy(storage.data() + s * n_per_row, src, n_per_row * sizeof(float)); }
+                out_ptr = storage.data();
+            } else {
+                std::lock_guard<std::mutex> lock(log_mutex);
+                out_ptr = nullptr;
+                LLAMA_LOG_WARN("%s: side data mismatch for %s\n", func, name.c_str());
+            }
+        };
+
+        prepare_broadcast(val_ptr, val_sz, val_cache, val_vec_ptr);
+        prepare_broadcast(act_ptr, act_sz, act_cache, act_vec_ptr);
+
+        // Cap (winsorize) each row-slice at exp(med + 4 * 1.4826 * mad) of ln(val) to reduce noise and prevent skewness
+        // Activation-side equivalent of the ±4 sigma weight clip in outlier_smoothing
+        std::vector<float> val_metric;
+        const float * ptr_val_metric = nullptr;
+        if (val_vec_ptr) {
+            val_metric.assign(val_vec_ptr, val_vec_ptr + (size_t)ne2 * n_per_row);
+            std::vector<float> scratch;
+            for (int64_t s = 0; s < ne2; ++s) {
+                const float * vrow = val_vec_ptr + s * n_per_row;
+                scratch.clear();
+                for (int64_t j = 0; j < n_per_row; ++j) {
+                    const float v = vrow[j];
+                    if (v > 0.0f) { scratch.push_back(std::log(v)); }
+                }
+
+                if (scratch.size() < 8 || scratch.size() < (size_t)n_per_row / 2) { continue; } // too few positive entries; leave untouched
+                auto mid = scratch.begin() + scratch.size() / 2;
+                std::nth_element(scratch.begin(), mid, scratch.end());
+                const float med = * mid;
+                for (auto & d : scratch) { d = std::fabs(d - med); }
+                std::nth_element(scratch.begin(), mid, scratch.end());
+                const float mad = * mid;
+                if (mad <= 1e-6f * std::max(1.0f, std::fabs(med))) { continue; } // abnormal row stats: leave untouched
+                const float cap = std::exp(med + 4.0f * 1.4826f * mad);
+                float * dst = val_metric.data() + s * n_per_row;
+                float row_max = -INFINITY;
+                for (int64_t j = 0; j < n_per_row; ++j) {
+                    row_max = std::max(row_max, dst[j]);
+                    dst[j] = std::min(dst[j], cap);
+                }
+            }
+
+            ptr_val_metric = val_metric.data();
+        }
+
+        const bool use_wce = val_vec_ptr && act_vec_ptr && is_angle_sensitive(remapped_name);
+
+        // Precompute WCE reference stats
+        wce_cache ref_wce;
+        mse_cache ref_mse;
+        size_t total_rows_sampled = 0;
+        for (int64_t r : rows_sample) { total_rows_sampled += r; }
+
+        if (use_wce) {
+            ref_wce.row_sq_norm.reserve(total_rows_sampled);
+            size_t off = 0;
+            for (int64_t s = 0; s < ne2; ++s) {
+                const int64_t rs = rows_sample[s];
+                if (rs == 0) { continue; }
+                const float * v = ptr_val_metric + s * n_per_row;
+                for (int64_t r = 0; r < rs; ++r) {
+                    const float * wx = f32_sample.data() + off;
+                    double norm_x = 0.0;
+                    for (int64_t j = 0; j < n_per_row; ++j) {
+                        const double w = v ? std::max(0.0f, v[j]) : 1.0;
+                        norm_x += (double)wx[j] * wx[j] * w;
+                    }
+                    ref_wce.row_sq_norm.push_back(norm_x);
+                    off += n_per_row;
+                }
+            }
+        } else {
+            // Precompute MSE reference stats
+            ref_mse.row_sq_norm.reserve(total_rows_sampled);
+            const bool has_acts = act_vec_ptr != nullptr;
+            const bool has_vals = val_vec_ptr != nullptr;
+
+            size_t off = 0;
+            for (int64_t s = 0; s < ne2; ++s) {
+                const int64_t rs = rows_sample[s];
+                const float * val = has_vals ? ptr_val_metric + s * n_per_row : nullptr;
+                const float * act = has_acts ? act_vec_ptr + s * n_per_row : nullptr;
+                for (int64_t r = 0; r < rs; ++r) {
+                    const float * x = f32_sample.data() + off;
+                    double sum = 0.0;
+                    double bias_sum = 0.0;
+                    if (val && act) {
+                        for (int64_t j = 0; j < n_per_row; ++j) {
+                            const double act_j = act[j];
+                            const double variance = std::max(0.0, (double)val[j] - act_j * act_j);
+                            sum += variance * x[j] * x[j];
+                            bias_sum += act_j * x[j];
+                        }
+                        sum += bias_sum * bias_sum;
+                    } else if (val) {
+                        for (int64_t j = 0; j < n_per_row; ++j) {
+                            sum += std::max(0.0f, val[j]) * x[j] * x[j];
+                        }
+                    } else {
+                        for (int64_t j = 0; j < n_per_row; ++j) { sum += x[j] * x[j]; }
+                    }
+
+                    ref_mse.row_sq_norm.push_back(sum);
+                    off += (size_t)n_per_row;
+                }
+            }
+        }
+
+        float kappa_raw = std::numeric_limits<float>::quiet_NaN();
+        float kappa_factor = 1.0f;
+        if (statistics_data && !statistics_data->empty()) {
+            kappa_raw = randomized_svd_condition_number(f32_sample, n_per_row, (int64_t)total_rows_sampled);
+            kappa_factor = squash_kappa(kappa_raw);
+        }
+
+        // Build candidates
+        std::vector<ggml_type> valid_types;
+        valid_types.reserve(std::size(quant_types));
+        size_t max_row_sz = 0;
+        const bool valid_matrix = val_vec_ptr != nullptr;
+
+        for (auto t : quant_types) {
+            if (is_iq(t) && !valid_matrix) { continue; }
+            if (qs.ignored_types[t]) { continue; }
+            ggml_type compat = make_compatible(tensor, t);
+            if (qs.ignored_types[compat]) { continue; }
+            if (!is_compatible(tensor, compat)) { continue; }
+            valid_types.push_back(compat);
+            max_row_sz = std::max(max_row_sz, ggml_row_size(compat, n_per_row));
+        }
+
+        std::sort(valid_types.begin(), valid_types.end());
+        valid_types.erase(std::unique(valid_types.begin(), valid_types.end()), valid_types.end());
+
+        // Evaluate candidates
+        std::vector<type_scores> evaluations;
+        evaluations.reserve(valid_types.size());
+        std::vector<uint8_t> q_buf;
+        std::vector<float> dq_buf;
+        if (total_rows_sampled > 0 && max_row_sz > 0) {
+            q_buf.reserve(max_row_sz + 256); // safety padding
+            dq_buf.reserve(n_per_row);
+        }
+
+        float cnif_score = 1.0f;
+        if (auto it = cnif_scores.find(remapped_name); it != cnif_scores.end()) { cnif_score = it->second; }
+        const float scaling_factor = cnif_score * kappa_factor;
+        const bool ip_sensitive = is_inner_product_sensitive(remapped_name);
+
+        std::vector<double> raw_errors;
+        raw_errors.reserve(valid_types.size());
+
+        for (ggml_type vt : valid_types) {
+            if (poll_interrupt()) { return std::nullopt; }
+            const wce_cache * ptr_ref_wce = use_wce && !ref_wce.row_sq_norm.empty() ? & ref_wce : nullptr;
+            const mse_cache * ptr_ref_mse = !use_wce && !ref_mse.row_sq_norm.empty() ? & ref_mse : nullptr;
+            const float bpw = (float)ggml_type_size(vt) * 8.0f / (float)ggml_blck_size(vt);
+            const std::vector<float>& eval_sample = is_outlier_heavy && bpw < 3.0f ? smoothed_sample : f32_sample;
+
+            quant_error qe = compute_quant_error(
+                tensor,
+                vt,
+                eval_sample,
+                rows_sample,
+                val_vec_ptr,
+                act_vec_ptr,
+                q_buf,
+                dq_buf,
+                ptr_ref_wce,
+                ptr_ref_mse,
+                ptr_val_metric
+            );
+
+            double error = qe.error;
+            if (ip_sensitive) { error *= 1.0f + 0.5f * std::pow(2.0f, 3.0f - bpw); } // error adjustment for inner-product sensitive tensors at low bpw
+
+            type_scores candidate;
+            candidate.type = vt;
+            candidate.bpw = (float)tensor_bpw(tensor, vt);
+            candidate.bytes = tensor_bytes(tensor, vt);
+            candidate.error = error * scaling_factor;
+            candidate.mse = qe.mse;
+            candidate.wce = qe.wce;
+            evaluations.push_back(candidate);
+            raw_errors.push_back(qe.error);
+        }
+
+        type_choice ch;
+        ch.w = tw;
+        ch.n_elements = ggml_nelements(tensor);
+
+        for (const auto & ev : evaluations) {
+            if (ev.bytes == 0) { continue; }
+            ch.candidates.push_back(ev);
+        }
+
+        if (ch.candidates.empty()) {
+            const bool is_locked = locked_tensors && locked_tensors->find(name) != locked_tensors->end();
+            if (qs.has_ignored_types && !is_locked) {
+                throw std::runtime_error(format("%s: tensor '%s' has %zu quant type candidates left after --target-exclude\n", func, name.c_str(), ch.candidates.size()));
+            }
+
+            type_scores fb;
+            fb.type = tensor->type;
+            fb.bytes = ggml_nbytes(tensor);
+            fb.bpw = fb.bytes * 8.0f / ch.n_elements;
+            ch.candidates.push_back(fb);
+        }
+
+        auto simplify_pareto = [&](std::vector<type_scores> & candidates) {
+            std::sort(candidates.begin(), candidates.end(), [](const auto& a, const auto& b) {
+                return a.bytes < b.bytes || (a.bytes == b.bytes && (a.error < b.error || (a.error == b.error && a.type < b.type)));
+            });
+            candidates.erase(std::unique(candidates.begin(), candidates.end(),
+                [](const auto & a, const auto &b) { return a.bytes == b.bytes; }), candidates.end());
+
+            std::vector<type_scores> hull;
+            double min_err = INFINITE;
+            for(const auto & c : candidates) {
+                if (c.error < min_err) {
+                    min_err = c.error;
+                    hull.push_back(c);
+                }
+            }
+            candidates = std::move(hull);
+
+            if (candidates.size() < 3) { return; }
+            std::vector<type_scores> convex;
+            auto cross = [](const auto& a, const auto& b, const auto& c) {
+                return ((double)b.bytes - (double)a.bytes) * (c.error - a.error) - ((double)c.bytes - (double)a.bytes) * (b.error - a.error);
+            };
+
+            for (const auto & c : candidates) {
+                while (convex.size() >= 2 && cross(convex[convex.size()-2], convex.back(), c) <= EPSILON) { convex.pop_back(); }
+                convex.push_back(c);
+            }
+
+            candidates = std::move(convex);
+        };
+
+        simplify_pareto(ch.candidates);
+        ch.choice = 0;
+        ch.min_bpw = ch.candidates.front().bpw;
+        ch.max_bpw = ch.candidates.back().bpw;
+        return ch;
+    };
+
+    std::vector<type_choice> all_tensors; // this vector will be populated by the parallel workers
+    {
+        std::atomic<size_t> idx{0};
+        std::mutex m_load;
+        std::mutex m_log;
+        std::mutex m_res;
+        std::exception_ptr w_exception;
+        std::atomic<bool> w_failed{false};
+        std::vector<std::thread> threads;
+        threads.reserve(n_workers);
+
+        for (int i = 0; i < n_workers; ++i) {
+            threads.emplace_back([&](){
+                try {
+                    std::vector<no_init<uint8_t>> buf;
+                    std::vector<float> f32_sample;
+                    std::vector<float> smoothed_sample;
+                    std::vector<float> val_cache;
+                    std::vector<float> act_cache;
+                    while(true) {
+                        if (w_failed.load(std::memory_order_relaxed) || poll_interrupt()) { break; }
+                        const size_t cur = idx.fetch_add(1);
+                        if (cur >= tensors.size()) { break; }
+                        if (!can_quantize(tensors[cur]->tensor)) { continue; }
+
+                        auto res = process_tensor(tensors[cur], buf, f32_sample, smoothed_sample, val_cache, act_cache, m_load, m_log);
+                        if (res) {
+                            std::lock_guard<std::mutex> lock(m_res);
+                            all_tensors.push_back(std::move(*res));
+                        } else {
+                            break;
+                        }
+                    }
+                } catch (...) {
+                    std::lock_guard<std::mutex> lock(m_res);
+                    if (!w_failed.exchange(true)) {
+                        w_exception = std::current_exception();
+                    }
+                }
+            });
+        }
+
+        for(auto& t : threads) { t.join(); }
+
+        if (w_exception) {
+            std::rethrow_exception(w_exception);
+        }
+    }
+
+    if (interrupted) {
+        std::unordered_set<std::string> reached;
+        for (const auto & tc : all_tensors) { reached.insert(ggml_get_name(tc.w->tensor)); }
+        for (const auto * tw : tensors) {
+            const std::string name = ggml_get_name(tw->tensor);
+            const auto it = bpw_data.find(name);
+            if (it == bpw_data.end() || reached.count(name)) { continue; }
+            type_choice tc = it->second;
+            tc.w = tw;
+            all_tensors.push_back(std::move(tc));
+        }
+    }
+
+    throw_if_aborted(all_tensors);
+    if (qs.params->state_file) {
+        if (qs.has_ignored_types) { LLAMA_LOG_WARN("\t%s: state checkpoint cannot be saved while --target-exclude is active\n", func); }
+        else { save_state(all_tensors); }
+    }
+
+    if (all_tensors.empty()) { return {}; }
+
+    // Compute total elements across all tensors and bytes for non-quantizable tensors
+    size_t n_elements = 0;
+    size_t nq_bytes = 0;
+    for (const auto * it : tensors) {
+        const ggml_tensor * tensor = it->tensor;
+        n_elements += (size_t)ggml_nelements(tensor);
+        if (!can_quantize(tensor)) { nq_bytes += ggml_nbytes(tensor); }
+    }
+
+    // Exclude user defined tensors (--tensor-type) from the Lagrangian optimization (courtesy of https://github.com/AesSedai)
+    std::vector<type_choice> pinned_tensors;
+    if (locked_tensors && !locked_tensors->empty()) {
+        std::vector<type_choice> variable_tensors;
+        variable_tensors.reserve(all_tensors.size());
+        for (auto & tn : all_tensors) {
+            const std::string name = ggml_get_name(tn.w->tensor);
+            auto lt = locked_tensors->find(name);
+            if (lt != locked_tensors->end()) {
+                const ggml_type mc = tensor_type_fallback(qs, tn.w->tensor, lt->second);
+                int idx = -1;
+                for (int j = 0; j < (int)tn.candidates.size(); ++j) {
+                    if (tn.candidates[j].type == mc) {
+                        idx = j;
+                        break;
+                    }
+                }
+
+                if (idx == -1) {
+                    // Pinned type was pareto-pruned or not evaluated; add with unknown error
+                    type_scores ts;
+                    ts.type = mc;
+                    ts.bpw = (float)tensor_bpw(tn.w->tensor, mc);
+                    ts.bytes = tensor_bytes(tn.w->tensor, mc);
+                    ts.error = std::numeric_limits<float>::quiet_NaN();
+                    tn.candidates.push_back(ts);
+                    idx = (int)tn.candidates.size() - 1;
+                }
+
+                tn.choice = idx;
+                pinned_tensors.push_back(std::move(tn));
+            } else {
+                variable_tensors.push_back(std::move(tn));
+            }
+        }
+
+        all_tensors = std::move(variable_tensors);
+    }
+
+    size_t pinned_bytes = 0;
+    for (const auto & tc : pinned_tensors) { pinned_bytes += tc.candidates[tc.choice].bytes; }
+
+    size_t min_total_bytes = 0;
+    size_t max_total_bytes = 0;
+    for (const auto & tn : all_tensors) {
+        min_total_bytes += tn.candidates.front().bytes;
+        max_total_bytes += tn.candidates.back().bytes;
+    }
+
+    size_t total_budget_bytes = 0;
+    size_t total_fixed_bytes = nq_bytes + pinned_bytes;
+    if (qs.params->target_size != -1) {
+        total_fixed_bytes += gguf_get_meta_size(ml.metadata);
+        total_budget_bytes = (size_t)qs.params->target_size;
+    } else {
+        total_budget_bytes = std::llround(qs.params->target_bpw * (double)n_elements / 8.0);
+    }
+
+    size_t pinned_min_bytes = 0;
+    for (const auto & tc : pinned_tensors) { pinned_min_bytes += tc.candidates.front().bytes; }
+
+    const size_t min_bytes = total_fixed_bytes + min_total_bytes;
+    const size_t unpinned_min_bytes = min_bytes - pinned_bytes + pinned_min_bytes;
+    const bool clamped = total_budget_bytes < min_bytes;
+
+    auto size_str = [&](const size_t bytes) {
+        return qs.params->target_size != -1 ? format("%zu bytes", bytes) : format("%.4f bpw", (double)bytes * 8.0 / n_elements);
+    };
+
+    const std::string requested = qs.params->target_size != -1 ? format("file size %zu", total_budget_bytes) : format("bpw %.4f", qs.params->target_bpw);
+    size_t budget_bytes = 0;
+    if (!clamped) {
+        budget_bytes = total_budget_bytes - total_fixed_bytes;
+        if (!pinned_tensors.empty() && budget_bytes > max_total_bytes) {
+            LLAMA_LOG_WARN("\t%s: target %s is not reachable with the pinned tensors (maximum ~%s); clamping to maximum\n",
+                func, requested.c_str(), size_str(total_fixed_bytes + max_total_bytes).c_str());
+        }
+    } else {
+        if (total_budget_bytes >= unpinned_min_bytes) {
+            throw std::runtime_error(format("%s: target %s is not reachable with the pinned tensors (minimum ~%s)",
+                func, requested.c_str(), size_str(min_bytes).c_str()));
+        }
+
+        const std::string pinned_min = pinned_tensors.empty() ? "" : format(" (~%s with the pinned tensors)", size_str(min_bytes).c_str());
+        LLAMA_LOG_WARN("\t%s: requested %s is smaller than minimum possible model size (~%s); clamping to minimum%s\n",
+            func, requested.c_str(), size_str(unpinned_min_bytes).c_str(), pinned_min.c_str());
+
+        budget_bytes = min_total_bytes;
+    }
+
+    // pins starve the selection process when remaining bpw is below boost_taper
+    if (!pinned_tensors.empty() && !all_tensors.empty()) {
+        size_t pinned_elements = 0;
+        for (const auto & tc : pinned_tensors) { pinned_elements += tc.n_elements; }
+        size_t rest_elements = 0;
+        for (const auto & tn : all_tensors) { rest_elements += tn.n_elements; }
+
+        const size_t other_fixed_bytes = total_fixed_bytes - pinned_bytes;
+        const double shared_bpw = std::max(0.0, 8.0 * ((double)total_budget_bytes - (double)other_fixed_bytes) / (double)(pinned_elements + rest_elements));
+        const double rest_bpw = 8.0 * (double)std::min(budget_bytes, max_total_bytes) / (double)rest_elements;
+        LLAMA_LOG_INFO("\t%s: pinning %zu tensors (%.2f%% of weights) leaves %.4f bpw available for the rest\n",
+            func, pinned_tensors.size(), 100.0 * pinned_elements / (pinned_elements + rest_elements), rest_bpw);
+
+        if (!clamped && rest_bpw < boost_taper && shared_bpw >= boost_taper) {
+            LLAMA_LOG_WARN("\t%s: remaining bpw is below the %.1f safety limit; model's quality may be severely compromised\n", func, boost_taper);
+        }
+    }
+
+    // Get the types' override
+    auto build_mix = [&]() -> std::unordered_map<std::string, ggml_type> {
+        std::unordered_map<std::string, ggml_type> quant_mix;
+        std::unordered_map<std::string, const type_choice *> optimized;
+        std::unordered_map<std::string, const type_choice *> pinned;
+        optimized.reserve(all_tensors.size());
+        for (const auto & tn : all_tensors) { optimized[ggml_get_name(tn.w->tensor)] = & tn; }
+        pinned.reserve(pinned_tensors.size());
+        for (const auto & tn : pinned_tensors) { pinned[ggml_get_name(tn.w->tensor)] = & tn; }
+
+        LLAMA_LOG_INFO("\t%s: tensor quantization mix:\n", func);
+        for (const auto * tn : tensors) {
+            const std::string name = ggml_get_name(tn->tensor);
+
+            auto pd = pinned.find(name);
+            bool is_pinned = pd != pinned.end();
+            const auto * tn_ptr = is_pinned ? pd->second : nullptr;
+
+            if (!tn_ptr) {
+                auto opt = optimized.find(name);
+                if (opt != optimized.end()) { tn_ptr = opt->second; }
+            }
+
+            if (tn_ptr) {
+                const auto & tp = * tn_ptr;
+                const auto & choice = tp.candidates[tp.choice];
+
+                LLAMA_LOG_INFO("\t%s: %45s %s\t%8s, \t%1.4f bpw,\terror: %.4f%s\n",
+                    func,
+                    name.c_str(),
+                    tp.boost > 1.0f ? "⬆︎" : "-",
+                    ggml_type_name(choice.type),
+                    choice.bpw,
+                    choice.error,
+                    is_pinned ? " (pinned)" : "");
+
+                quant_mix[name] = choice.type;
+            }
+        }
+
+        return quant_mix;
+    };
+
+    if (budget_bytes <= min_total_bytes) {
+        for(auto & tn : all_tensors) { tn.choice = 0; }
+        return build_mix();
+    }
+    if (budget_bytes >= max_total_bytes) {
+        for(auto & tn : all_tensors) { tn.choice = (int)tn.candidates.size() - 1; }
+        return build_mix();
+    }
+
+    // Certain tensors have a higher impact on model quality, so they get a boost
+    size_t total_elements = 0;
+    for (const auto & tn : all_tensors) { total_elements += tn.n_elements; }
+    const double global_bpw = 8.0 * (double)budget_bytes / (double)total_elements;
+    for (auto & tn : all_tensors) {
+        const std::string tensor_name = ggml_get_name(tn.w->tensor);
+        if (tensor_name.find("ffn_down.weight") != std::string::npos) {
+            if (global_bpw < boost_taper) {
+                for (auto & candidate : tn.candidates) { candidate.error *= 1.0 + std::pow(2.0, 3.0 - candidate.bpw); }
+            } else {
+                tn.boost = ffn_down_boost;
+            }
+        } else if (tensor_name == "output.weight") {
+            tn.boost = output_boost;
+        } else if (tensor_name.find("attn_v") != std::string::npos) {
+            tn.boost = attn_v_boost;
+        } else if (qs.has_tied_embeddings && tensor_name == "token_embd.weight" && global_bpw >= boost_taper) {
+            const double embd_share = (double)tn.n_elements / (double)total_elements;
+            tn.boost = embd_share <= 0.10 ? tied_embd_boost : (float)std::max(1.25, (double)tied_embd_boost * (1.0 - 3.0 * (embd_share - 0.10)));
+        }
+    }
+
+    // Minimize error subject to a size target constraint
+    auto lagrangian_relaxation = [&](const double mu, std::vector<int> & choices, size_t & bytes, double & cost) {
+        choices.resize(all_tensors.size());
+        bytes = 0;
+        cost = 0.0;
+        for (size_t i = 0; i < all_tensors.size(); ++i) {
+            const auto & tn = all_tensors[i];
+            const double eff_mu = mu / tn.boost; // boosted tensors get a lower penalty
+            int best = 0;
+            for(int j = 1; j < (int)tn.candidates.size(); ++j) {
+                double lr = (tn.candidates[j].error - tn.candidates[best].error) + eff_mu * ((double)tn.candidates[j].bytes - (double)tn.candidates[best].bytes) * 8.0;
+                if (lr < -EPSILON || (std::abs(lr) <= EPSILON && tn.candidates[j].bytes < tn.candidates[best].bytes)) {
+                    best = j;
+                }
+            }
+
+            choices[i] = best;
+            bytes += tn.candidates[best].bytes;
+            cost += tn.candidates[best].error;
+        }
+    };
+
+    // Binary search for mu then greedy upgrade upwards followed by greedy upgrade downwards of any leftover budget
+    auto run_auction = [&](const size_t budget) {
+        size_t min_bytes = 0;
+        size_t max_bytes = 0;
+        for (const auto & tn : all_tensors) {
+            min_bytes += tn.candidates.front().bytes;
+            max_bytes += tn.candidates.back().bytes;
+        }
+
+        if (budget <= min_bytes) {
+            for (auto & tn : all_tensors) { tn.choice = 0; }
+            return;
+        }
+
+        if (budget >= max_bytes) {
+            for (auto & tn : all_tensors) { tn.choice = (int)tn.candidates.size() - 1; }
+            return;
+        }
+
+        // Binary search for mu
+        double mu_lo = 0.0;
+        double mu_hi = 1.0;
+        std::vector<int> ch_lo;
+        std::vector<int> ch_hi;
+        std::vector<int> ch_under;
+        std::vector<int> ch_over;
+        size_t bt_lo;
+        size_t bt_hi;
+        size_t bt_mid;
+        double dummy;
+
+        lagrangian_relaxation(mu_lo, ch_lo, bt_lo, dummy);
+        int safety = 0;
+
+        do {
+            lagrangian_relaxation(mu_hi, ch_hi, bt_hi, dummy);
+            if (bt_hi <= budget || bt_hi == std::numeric_limits<size_t>::max()) { break; }
+            mu_hi *= 2.0;
+        } while(++safety < 60);
+
+        double gap_under = INFINITE;
+        double gap_over = INFINITE;
+
+        for(int i = 0; i < 40; ++i) {
+            double mu = 0.5 * (mu_lo + mu_hi);
+            std::vector<int> ch_mid;
+            double cost_mid = 0.0;
+            lagrangian_relaxation(mu, ch_mid, bt_mid, cost_mid);
+
+            double gap = std::abs((double)bt_mid - (double)budget);
+            if (bt_mid > budget) {
+                mu_lo = mu;
+                if (gap < gap_over) {
+                    gap_over = gap;
+                    ch_over = ch_mid;
+                }
+            } else {
+                mu_hi = mu;
+                if (gap < gap_under) {
+                    gap_under = gap;
+                    ch_under = ch_mid;
+                }
+            }
+        }
+
+        if (!ch_under.empty()) {
+            for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_under[i]; }
+        }
+        else if (!ch_over.empty()) {
+            for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_over[i]; }
+        }
+        else if (bt_hi <= budget && !ch_hi.empty()) {
+            for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_hi[i]; }
+        }
+        else {
+            for(auto& tn : all_tensors) { tn.choice = 0; }
+        }
+
+        auto current_bytes = [&] {
+            size_t cb = 0;
+            for(const auto & tn : all_tensors) { cb += tn.candidates[tn.choice].bytes; }
+            return cb;
+        };
+
+        struct tensor_upgrade {
+            int index;
+            int next_choice;
+            double score;
+            bool operator<(const tensor_upgrade & other) const {
+                return score < other.score;
+            }
+        };
+
+        // greedy upwards/downwards upgrades in case there is budget left
+        auto allocate_remaining = [&] {
+            size_t cb = current_bytes();
+            std::priority_queue<tensor_upgrade> queue;
+
+            auto push_next = [&](const int i) {
+                const auto & tn = all_tensors[i];
+                int next = tn.choice + 1;
+                if (next < (int)tn.candidates.size()) {
+                    const double err = std::max(0.0, tn.candidates[tn.choice].error - tn.candidates[next].error);
+                    auto bytes = (double)(tn.candidates[next].bytes - tn.candidates[tn.choice].bytes);
+                    if (bytes > EPSILON) {
+                        double ratio = err / bytes;
+                        ratio *= tn.boost; // boosted tensors get a higher priority
+                        queue.push({i, next, ratio});
+                    }
+                }
+            };
+
+            for (size_t i = 0; i < all_tensors.size(); ++i) { push_next((int)i); }
+
+            while (!queue.empty()) {
+                auto top = queue.top();
+                queue.pop();
+
+                int i = top.index;
+                int next = top.next_choice;
+                if (all_tensors[i].choice >= next) { continue; }
+
+                size_t delta_bt = all_tensors[i].candidates[next].bytes - all_tensors[i].candidates[all_tensors[i].choice].bytes;
+                if (cb + delta_bt <= budget) {
+                    cb += delta_bt;
+                    all_tensors[i].choice = next;
+                    push_next(i);
+                }
+            }
+        };
+
+        // upwards upgrade
+        allocate_remaining();
+
+        // upgrade cannot swap one large for several small so we try downwards too
+        auto total_cost = [&] {
+            double cost = 0.0;
+            for (const auto & tn : all_tensors) { cost += tn.boost * tn.candidates[tn.choice].error; }
+            return cost;
+        };
+
+        std::vector<int> under_choices(all_tensors.size());
+        for (size_t i = 0; i < all_tensors.size(); ++i) { under_choices[i] = all_tensors[i].choice; }
+        const double under_cost = total_cost();
+
+        const std::vector<int> & over = ch_over.empty() ? ch_lo : ch_over;
+        for (size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = over[i]; }
+
+        // drop the step with the least boosted error per byte, counting no more bytes than are still over budget
+        size_t cb = current_bytes();
+        while (cb > budget) {
+            int best = -1;
+            double best_score = INFINITE;
+            for (size_t i = 0; i < all_tensors.size(); ++i) {
+                const auto & tn = all_tensors[i];
+                if (tn.choice == 0) { continue; }
+                const double err = tn.boost * std::max(0.0, tn.candidates[tn.choice - 1].error - tn.candidates[tn.choice].error);
+                const size_t freed = tn.candidates[tn.choice].bytes - tn.candidates[tn.choice - 1].bytes;
+                const double score = err / (double)std::min(freed, cb - budget);
+                if (score < best_score) {
+                    best_score = score;
+                    best = (int)i;
+                }
+            }
+
+            if (best < 0) { break; }
+            auto & tn = all_tensors[best];
+            cb -= tn.candidates[tn.choice].bytes - tn.candidates[tn.choice - 1].bytes;
+            --tn.choice;
+        }
+
+        allocate_remaining();
+        if (current_bytes() > budget || total_cost() >= under_cost * (1.0 - downward_threshold)) {
+            for (size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = under_choices[i]; }
+        }
+    };
+
+    run_auction(budget_bytes);
+
+    // Dense ffn_down cap
+    if (global_bpw >= boost_taper) {
+        const std::regex dense_ffn_down("blk\\.[0-9]+\\.ffn_down\\.weight");
+        std::vector<size_t> role;
+        for (size_t i = 0; i < all_tensors.size(); ++i) {
+            if (std::regex_match(std::string(ggml_get_name(all_tensors[i].w->tensor)), dense_ffn_down)) {
+                role.push_back(i);
+            }
+        }
+
+        if (role.size() >= 8) {
+            std::vector<double> role_bpw;
+            role_bpw.reserve(role.size());
+            for (const size_t i : role) { role_bpw.push_back(all_tensors[i].candidates[all_tensors[i].choice].bpw); }
+            std::sort(role_bpw.begin(), role_bpw.end());
+            const size_t mid = role_bpw.size() / 2;
+            const double median_bpw = role_bpw.size() % 2 ? role_bpw[mid] : 0.5 * (role_bpw[mid - 1] + role_bpw[mid]);
+
+            std::vector<size_t> outlier;
+            for (const size_t i : role) {
+                if (median_bpw - (double)all_tensors[i].candidates[all_tensors[i].choice].bpw > 2.0) { outlier.push_back(i); }
+            }
+
+            if (!outlier.empty()) {
+                // nominal-bpw tie break: K-quants first, then IQ, then legacy
+                auto family_rank = [&](const ggml_type gt) {
+                    switch (gt) {
+                        case GGML_TYPE_Q2_K:
+                        case GGML_TYPE_Q3_K:
+                        case GGML_TYPE_Q4_K:
+                        case GGML_TYPE_Q5_K:
+                        case GGML_TYPE_Q6_K:
+                            return 0;
+                        default:
+                            return is_iq(gt) ? 1 : 2;
+                    }
+                };
+
+                ggml_type fill = GGML_TYPE_Q8_0;
+                double fill_bpw = INFINITE;
+                int fill_rank = 3;
+                for (const ggml_type t : quant_types) {
+                    if (!ggml_is_quantized(t)) { continue; }
+                    if (qs.ignored_types[t]) { continue; }
+                    const double nominal = (double)ggml_type_size(t) * 8.0 / (double)ggml_blck_size(t);
+                    if (nominal < median_bpw) { continue; }
+                    const int rank = family_rank(t);
+                    if (nominal < fill_bpw || (nominal == fill_bpw && rank < fill_rank)) {
+                        fill = t;
+                        fill_bpw = nominal;
+                        fill_rank = rank;
+                    }
+                }
+
+                if (fill_bpw == INFINITE && qs.ignored_types[fill]) {
+                    LLAMA_LOG_WARN("\t%s: ffn_down type %s is ignored by --target-exclude, keeping the auto-selected type\n", func, ggml_type_name(fill));
+                } else {
+                    size_t locked_bytes = 0;
+                    std::vector<type_choice> remaining;
+                    remaining.reserve(all_tensors.size());
+                    for (size_t i = 0; i < all_tensors.size(); ++i) {
+                        auto & tn = all_tensors[i];
+                        if (!std::binary_search(outlier.begin(), outlier.end(), i)) {
+                            remaining.push_back(std::move(tn));
+                            continue;
+                        }
+
+                        const ggml_tensor * tensor = tn.w->tensor;
+                        const ggml_type mc = make_compatible(tensor, fill);
+                        if (qs.ignored_types[mc]) {
+                            // the fill resolution is barred - keep the auction-chosen type
+                            remaining.push_back(std::move(tn));
+                            continue;
+                        }
+                        int idx = -1;
+                        for (int j = 0; j < (int)tn.candidates.size(); ++j) {
+                            if (tn.candidates[j].type == mc) { idx = j; break; }
+                        }
+
+                        if (idx == -1) {
+                            type_scores ts;
+                            ts.type = mc;
+                            ts.bpw = (float)tensor_bpw(tensor, mc);
+                            ts.bytes = tensor_bytes(tensor, mc);
+                            ts.error = std::numeric_limits<float>::quiet_NaN();
+                            tn.candidates.push_back(ts);
+                            idx = (int)tn.candidates.size() - 1;
+                        }
+
+                        tn.choice = idx;
+                        locked_bytes += tn.candidates[idx].bytes;
+                        pinned_tensors.push_back(std::move(tn));
+                    }
+
+                    all_tensors = std::move(remaining);
+                    run_auction(budget_bytes > locked_bytes ? budget_bytes - locked_bytes : 0);
+                }
+            }
+        }
+    }
+
+    // Expert down-projection cap
+    if (global_bpw < boost_taper) {
+        const std::regex expert_ffn_down("blk\\.[0-9]+\\.ffn_down_exps\\.weight");
+        const std::regex expert_ffn_gate("blk\\.[0-9]+\\.ffn_gate_exps\\.weight");
+        const std::regex expert_ffn_up  ("blk\\.[0-9]+\\.ffn_up_exps\\.weight");
+
+        // Element-weighted mean of the chosen bpw
+        auto mean_bpw = [&](const std::regex & re, std::vector<size_t> * members) -> double {
+            double num = 0.0;
+            double den = 0.0;
+            for (size_t i = 0; i < all_tensors.size(); ++i) {
+                const auto & tn = all_tensors[i];
+                if (!std::regex_match(std::string(ggml_get_name(tn.w->tensor)), re)) { continue; }
+                num += (double)tn.n_elements * (double)tn.candidates[tn.choice].bpw;
+                den += (double)tn.n_elements;
+                if (members) { members->push_back(i); }
+            }
+
+            return den > 0.0 ? num / den : -1.0;
+        };
+
+        std::vector<size_t> role;
+        std::vector<size_t> siblings;
+        const double down_bpw = mean_bpw(expert_ffn_down, &role);
+        // mean_bpw appends so siblings gets both the gate and the up tensors
+        const double gate_bpw = mean_bpw(expert_ffn_gate, &siblings);
+        const double up_bpw = mean_bpw(expert_ffn_up,   &siblings);
+        const double sibling_bpw = std::max(gate_bpw, up_bpw);
+        std::sort(siblings.begin(), siblings.end());
+        if (!role.empty() && sibling_bpw > 0.0 && down_bpw > sibling_bpw) {
+            std::vector<size_t> outliers;
+            for (const size_t i : role) {
+                if ((double)all_tensors[i].candidates[all_tensors[i].choice].bpw > sibling_bpw) { outliers.push_back(i); }
+            }
+
+            if (!outliers.empty()) {
+                size_t locked_bytes = 0;
+                std::vector<type_choice> remaining;
+                remaining.reserve(all_tensors.size());
+                for (size_t i = 0; i < all_tensors.size(); ++i) {
+                    auto & tn = all_tensors[i];
+                    if (!std::binary_search(outliers.begin(), outliers.end(), i)) {
+                        if (std::binary_search(siblings.begin(), siblings.end(), i)) {
+                            locked_bytes += tn.candidates[tn.choice].bytes;
+                            pinned_tensors.push_back(std::move(tn));
+                            continue;
+                        }
+
+                        if (std::binary_search(role.begin(), role.end(), i)) {
+                            const ggml_type chosen = tn.candidates[tn.choice].type;
+                            std::vector<type_scores> kept;
+                            kept.reserve(tn.candidates.size());
+                            for (const auto & c : tn.candidates) {
+                                if ((double)c.bpw <= sibling_bpw) { kept.push_back(c); }
+                            }
+
+                            int new_choice = -1;
+                            for (int j = 0; j < (int)kept.size(); ++j) {
+                                if (kept[j].type == chosen) { new_choice = j; break; }
+                            }
+
+                            if (new_choice >= 0) {
+                                tn.candidates = std::move(kept);
+                                tn.choice     = new_choice;
+                            }
+                        }
+
+                        remaining.push_back(std::move(tn));
+                        continue;
+                    }
+
+                    int idx = -1;
+                    for (int j = 0; j < (int)tn.candidates.size(); ++j) {
+                        if ((double)tn.candidates[j].bpw > sibling_bpw) { continue; }
+                        if (idx == -1 || tn.candidates[j].bpw > tn.candidates[idx].bpw) { idx = j; }
+                    }
+
+                    if (idx == -1) {
+                        remaining.push_back(std::move(tn));
+                        continue;
+                    }
+
+                    tn.choice = idx;
+                    locked_bytes += tn.candidates[idx].bytes;
+                    pinned_tensors.push_back(std::move(tn));
+                }
+
+                all_tensors = std::move(remaining);
+                run_auction(budget_bytes > locked_bytes ? budget_bytes - locked_bytes : 0);
+            }
+        }
+    }
+
+    return build_mix();
+}
+
+// imatrix requirement check
+static bool tensor_requires_imatrix(const char * tensor_name, const ggml_type dst_type, const llama_ftype ftype) {
+    if (tensor_name_match_token_embd(tensor_name) || tensor_name_match_output_weight(tensor_name)) { return false; }
+    switch (dst_type) {
+        case GGML_TYPE_IQ3_XXS:
+        case GGML_TYPE_IQ2_XXS:
+        case GGML_TYPE_IQ2_XS:
+        case GGML_TYPE_IQ2_S:
+        case GGML_TYPE_IQ1_M:
+        case GGML_TYPE_IQ1_S:
+            return true;
+        case GGML_TYPE_Q2_K:
+            // as a general rule, the k-type quantizations don't require imatrix data.
+            // the only exception is Q2_K tensors that are part of a Q2_K_S file.
+            return ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S;
+        default:
+            return false;
+    }
+}
+
+// given a file type, get the default tensor type
+ggml_type llama_ftype_get_default_type(const llama_ftype ftype) {
+    switch (ftype) {
+        case LLAMA_FTYPE_MOSTLY_Q4_0: return GGML_TYPE_Q4_0;
+        case LLAMA_FTYPE_MOSTLY_Q4_1: return GGML_TYPE_Q4_1;
+        case LLAMA_FTYPE_MOSTLY_Q5_0: return GGML_TYPE_Q5_0;
+        case LLAMA_FTYPE_MOSTLY_Q5_1: return GGML_TYPE_Q5_1;
+        case LLAMA_FTYPE_MOSTLY_Q8_0: return GGML_TYPE_Q8_0;
+        case LLAMA_FTYPE_MOSTLY_F16:  return GGML_TYPE_F16;
+        case LLAMA_FTYPE_MOSTLY_BF16: return GGML_TYPE_BF16;
+        case LLAMA_FTYPE_ALL_F32:     return GGML_TYPE_F32;
+        case LLAMA_FTYPE_MOSTLY_Q1_0: return GGML_TYPE_Q1_0;
+        case LLAMA_FTYPE_MOSTLY_Q2_0: return GGML_TYPE_Q2_0;
+
+        case LLAMA_FTYPE_MOSTLY_MXFP4_MOE: return GGML_TYPE_MXFP4;
+
+        // K-quants
+        case LLAMA_FTYPE_MOSTLY_Q2_K_S:
+        case LLAMA_FTYPE_MOSTLY_Q2_K:    return GGML_TYPE_Q2_K;
+        case LLAMA_FTYPE_MOSTLY_IQ3_XS:  return GGML_TYPE_IQ3_S;
+        case LLAMA_FTYPE_MOSTLY_Q3_K_S:
+        case LLAMA_FTYPE_MOSTLY_Q3_K_M:
+        case LLAMA_FTYPE_MOSTLY_Q3_K_L:  return GGML_TYPE_Q3_K;
+        case LLAMA_FTYPE_MOSTLY_Q4_K_S:
+        case LLAMA_FTYPE_MOSTLY_Q4_K_M:  return GGML_TYPE_Q4_K;
+        case LLAMA_FTYPE_MOSTLY_Q5_K_S:
+        case LLAMA_FTYPE_MOSTLY_Q5_K_M:  return GGML_TYPE_Q5_K;
+        case LLAMA_FTYPE_MOSTLY_Q6_K:    return GGML_TYPE_Q6_K;
+        // Ternary quants
+        case LLAMA_FTYPE_MOSTLY_TQ1_0:   return GGML_TYPE_TQ1_0;
+        case LLAMA_FTYPE_MOSTLY_TQ2_0:   return GGML_TYPE_TQ2_0;
+        // Lattice and Non-linear quants
+        case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return GGML_TYPE_IQ2_XXS;
+        case LLAMA_FTYPE_MOSTLY_IQ2_XS:  return GGML_TYPE_IQ2_XS;
+        case LLAMA_FTYPE_MOSTLY_IQ2_S:   return GGML_TYPE_IQ2_XS;
+        case LLAMA_FTYPE_MOSTLY_IQ2_M:   return GGML_TYPE_IQ2_S;
+        case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return GGML_TYPE_IQ3_XXS;
+        case LLAMA_FTYPE_MOSTLY_IQ1_S:   return GGML_TYPE_IQ1_S;
+        case LLAMA_FTYPE_MOSTLY_IQ1_M:   return GGML_TYPE_IQ1_M;
+        case LLAMA_FTYPE_MOSTLY_IQ4_NL:  return GGML_TYPE_IQ4_NL;
+        case LLAMA_FTYPE_MOSTLY_IQ4_XS:  return GGML_TYPE_IQ4_XS;
+        case LLAMA_FTYPE_MOSTLY_IQ3_S:
+        case LLAMA_FTYPE_MOSTLY_IQ3_M:   return GGML_TYPE_IQ3_S;
+
+        default: return GGML_TYPE_COUNT;
+    }
+}
+
+static void init_quantize_state_counters(quantize_state_impl & qs, std::vector<tensor_metadata> & metadata) {
+    for (auto & tm : metadata) {
+        tm.category = tensor_get_category(tm.name);
+        if (category_is_attn_v(tm.category)) { ++qs.n_attention_wv; }
+        if (tm.category == TENSOR_CATEGORY_OUTPUT) { qs.has_tied_embeddings = false; }
+    }
+
+    qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)qs.model.hparams.n_layer_all;
+}
+
+// main quantization driver
+static void llama_model_quantize_impl(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
+    llama_ftype ftype = params->ftype;
+    int nthread = params->nthread;
+    if (nthread <= 0) { nthread = (int)std::thread::hardware_concurrency(); }
+
+    const ggml_type default_type = llama_ftype_get_default_type(ftype);
+    if (default_type == GGML_TYPE_COUNT) { throw std::runtime_error(format("invalid output file type %d\n", ftype)); }
+
+    // mmap consistently increases speed on Linux, and also increases speed on Windows with
+    // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
+#if defined(__linux__) || defined(_WIN32)
+    constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_MMAP;
+#else
+    constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_NONE;
+#endif
+
+    const llama_model_kv_override * kv_overrides = params->kv_overrides;
+    std::vector<std::string> splits = {};
+    llama_model_loader ml(/*metadata*/ nullptr, /*set_tensor_data*/ nullptr, /*set_tensor_data_ud*/ nullptr,
+        fname_inp, splits, /*file*/ nullptr, /*load_mode*/ load_mode, /*check_tensors*/ true, /*no_alloc*/ false, /*load_mtp*/ true, kv_overrides, nullptr);
+    ml.init_mappings(false); // no prefetching

     auto mparams = llama_model_default_params();
     std::unique_ptr<llama_model> model_ptr(llama_model_create(ml, mparams));
@@ -1069,39 +3184,70 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::

     quantize_state_impl qs(*model, params);

-    if (params->only_copy) {
-        ftype = ml.ftype;
-    }
-    std::unordered_map<std::string, std::vector<float>> i_data;
-    const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
+    if (params->only_copy) { ftype = ml.ftype; }
+    const std::unordered_map<std::string, std::vector<float>> * values_data = nullptr;
+    const std::unordered_map<std::string, std::vector<float>> * activations_data = nullptr;
+    const std::unordered_map<std::string, std::vector<float>> * statistics_data = nullptr;
+    std::unordered_map<std::string, std::vector<float>> vdata;
+    std::unordered_map<std::string, std::vector<float>> adata;
+    std::unordered_map<std::string, std::vector<float>> sdata;
+    const std::vector<std::string> * stats_schema = nullptr;
+    std::vector<std::string> sschema;
     if (params->imatrix) {
-        for (const llama_model_imatrix_data * p = params->imatrix; p->name != nullptr; p++) {
-            i_data.emplace(p->name, std::vector<float>(p->data, p->data + p->size));
+        for (const llama_model_imatrix_data * i = params->imatrix; i->name != nullptr; i++) {
+            vdata.emplace(i->name, std::vector<float>(i->data, i->data + i->size));
         }
-        imatrix_data = & i_data;
-        if (imatrix_data) {
-            LLAMA_LOG_INFO("\n%s: have importance matrix data with %d entries\n",
-                           __func__, (int)imatrix_data->size());
+
+        values_data = & vdata;
+        if (values_data) {
+            LLAMA_LOG_INFO("%s: have importance matrix data with %d entries", __func__, (int)values_data->size());
             qs.has_imatrix = true;
             // check imatrix for nans or infs
-            for (const auto & kv : *imatrix_data) {
+            for (const auto & kv : * values_data) {
                 for (float f : kv.second) {
-                    if (!std::isfinite(f)) {
-                        throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
-                    }
+                    if (!std::isfinite(f)) { throw std::runtime_error(format("imatrix contains non-finite value %f\n", f)); }
                 }
             }
         }
     }
+    if (params->activations) {
+        for (const llama_model_imatrix_data * a = params->activations; a->name != nullptr; a++) {
+            adata.emplace(a->name, std::vector<float>(a->data, a->data + a->size));
+        }
+
+        activations_data = & adata;
+        if (activations_data) {
+            LLAMA_LOG_INFO(" - %d activations", (int)activations_data->size());
+            qs.has_activations = true;
+            // check activations for nans or infs
+            for (const auto & kv : * activations_data) {
+                for (float f : kv.second) {
+                    if (!std::isfinite(f)) { throw std::runtime_error(format("activations contain non-finite value %f\n", f)); }
+                }
+            }
+        }
+    }
+    if (params->statistics) {
+        for (const llama_model_imatrix_data * s = params->statistics; s->name != nullptr; s++) {
+            sdata.emplace(s->name, std::vector<float>(s->data, s->data + s->size));
+        }
+        if (params->stats_schema) {
+            for (const char * const * s = params->stats_schema; * s != nullptr; s++) { sschema.emplace_back(* s); }
+            stats_schema = & sschema;
+        }
+
+        statistics_data = & sdata;
+        if (statistics_data) { LLAMA_LOG_INFO(" and %d statistics", (int)statistics_data->size());
+        }
+    }
+    LLAMA_LOG_INFO("\n");

     const size_t align = GGUF_DEFAULT_ALIGNMENT;
     gguf_context_ptr ctx_out { gguf_init_empty() };

     std::vector<int> prune_list = {};
     if (params->prune_layers) {
-        for (const int32_t * p = params->prune_layers; * p != -1; p++) {
-            prune_list.push_back(* p);
-        }
+        for (const int32_t * p = params->prune_layers; * p != -1; p++) { prune_list.push_back(* p); }
     }

     // copy the KV pairs from the input file
@@ -1115,27 +3261,38 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
     gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());

     if (params->kv_overrides) {
-        for (const llama_model_kv_override * o = params->kv_overrides; o->key[0] != 0; ++o) {
-            if (o->tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
-                gguf_set_val_f32(ctx_out.get(), o->key, o->val_f64);
-            } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
+        for (const llama_model_kv_override * kvo = params->kv_overrides; kvo->key[0] != 0; ++kvo) {
+            if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
+                gguf_set_val_f32(ctx_out.get(), kvo->key, kvo->val_f64);
+            } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
                 // Setting type to UINT32. See https://github.com/ggml-org/llama.cpp/pull/14182 for context
-                gguf_set_val_u32(ctx_out.get(), o->key, (uint32_t)std::abs(o->val_i64));
-            } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
-                gguf_set_val_bool(ctx_out.get(), o->key, o->val_bool);
-            } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
-                gguf_set_val_str(ctx_out.get(), o->key, o->val_str);
+                gguf_set_val_u32(ctx_out.get(), kvo->key, (uint32_t)std::abs(kvo->val_i64));
+            } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
+                gguf_set_val_bool(ctx_out.get(), kvo->key, kvo->val_bool);
+            } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
+                gguf_set_val_str(ctx_out.get(), kvo->key, kvo->val_str);
             } else {
-                LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o->key);
+                LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, kvo->key);
             }
         }
     }

+    // first layer without its own kv cache
+    int n_unused_kv_from = -1;
+    {
+        uint32_t n_block = 0;
+        uint32_t n_shared = 0;
+        ml.get_key(LLM_KV_BLOCK_COUNT, n_block, false);
+        ml.get_key(LLM_KV_ATTENTION_SHARED_KV_LAYERS, n_shared, false);
+        if (n_shared > 0 && n_shared <= n_block) { n_unused_kv_from = (int)(n_block - n_shared); }
+    }
+
     std::map<int, std::string> mapped;
     int blk_id = 0;

     // make a list of weights
     std::vector<const llama_model_loader::llama_tensor_weight *> tensors;
+    std::unordered_set<std::string> unused_kv_tensors;
     tensors.reserve(ml.weights_map.size());
     for (const auto & it : ml.weights_map) {
         const std::string remapped_name(remap_layer(it.first, prune_list, mapped, blk_id));
@@ -1143,32 +3300,28 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
             LLAMA_LOG_DEBUG("%s: pruning tensor %s\n", __func__, it.first.c_str());
             continue;
         }
-
         if (remapped_name != it.first) {
             ggml_set_name(it.second.tensor, remapped_name.c_str());
             LLAMA_LOG_DEBUG("%s: tensor %s remapped to %s\n", __func__, it.first.c_str(), ggml_get_name(it.second.tensor));
         }
+        if (tensor_name_match_unused_kv(it.first, n_unused_kv_from)) { unused_kv_tensors.insert(remapped_name); }
+
         tensors.push_back(&it.second);
     }
-    if (!prune_list.empty()) {
-        gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), blk_id);
-    }
+
+    if (!prune_list.empty()) { gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), blk_id); }

     // keep_split requires that the weights are sorted by split index
     if (params->keep_split) {
         std::sort(tensors.begin(), tensors.end(), [](const llama_model_loader::llama_tensor_weight * a, const llama_model_loader::llama_tensor_weight * b) {
-            if (a->idx == b->idx) {
-                return a->offs < b->offs;
-            }
+            if (a->idx == b->idx) { return a->offs < b->offs; }
             return a->idx < b->idx;
         });
     }

     // compute tensor metadata once and cache it
     std::vector<tensor_metadata> metadata(tensors.size());
-    for (size_t i = 0; i < tensors.size(); ++i) {
-        metadata[i].name = ggml_get_name(tensors[i]->tensor);
-    }
+    for (size_t i = 0; i < tensors.size(); ++i) { metadata[i].name = ggml_get_name(tensors[i]->tensor); }

     // initialize quantization state counters and metadata categories
     init_quantize_state_counters(qs, metadata);
@@ -1178,46 +3331,41 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::

     // Assume split index is continuous
     if (params->keep_split) {
-        for (const auto * it : tensors) {
-            n_split = std::max(uint16_t(it->idx + 1), n_split);
-        }
+        for (const auto * it : tensors) { n_split = std::max((uint16_t)(it->idx + 1), n_split); }
     }
+
     std::vector<gguf_context_ptr> ctx_outs(n_split);
     ctx_outs[0] = std::move(ctx_out);

     // flag for --dry-run
     bool will_require_imatrix = false;

-    //
     // preliminary iteration over all weights
-    //
-
     for (size_t i = 0; i < tensors.size(); ++i) {
         const auto * it = tensors[i];
         const struct ggml_tensor * tensor = it->tensor;

         uint16_t i_split = params->keep_split ? it->idx : 0;
-        if (!ctx_outs[i_split]) {
-            ctx_outs[i_split].reset(gguf_init_empty());
-        }
+        if (!ctx_outs[i_split]) { ctx_outs[i_split].reset(gguf_init_empty()); }
         gguf_add_tensor(ctx_outs[i_split].get(), tensor);

         metadata[i].allows_quantization = tensor_allows_quantization(params, model->arch, tensor);

-        if (metadata[i].allows_quantization) {
-            metadata[i].target_type = llama_tensor_get_type(qs, params, tensor, default_type, metadata[i]);
-        } else {
-            metadata[i].target_type = tensor->type;
+        if (metadata[i].allows_quantization) { metadata[i].target_type = llama_tensor_get_type(qs, params, tensor, default_type, metadata[i]); }
+        else { metadata[i].target_type = tensor->type; }
+
+        if (metadata[i].allows_quantization && unused_kv_tensors.count(metadata[i].name)) {
+            metadata[i].target_type = tensor_type_fallback(qs, tensor, GGML_TYPE_Q4_0);
+            LLAMA_LOG_INFO("%s: unused tensor (%s shares an earlier layer's kv cache) - converting to %s\n",
+                __func__, metadata[i].name.c_str(), ggml_type_name(metadata[i].target_type));
         }

         metadata[i].requires_imatrix = tensor_requires_imatrix(tensor->name, metadata[i].target_type, ftype);

-        if (params->imatrix) {
-            metadata[i].remapped_imatrix_name = remap_imatrix(tensor->name, mapped);
-        } else if (metadata[i].allows_quantization && metadata[i].requires_imatrix) {
-            if (params->dry_run) {
-                will_require_imatrix = true;
-            } else {
+        if (params->imatrix) { metadata[i].remapped_imatrix_name = remap_imatrix(tensor->name, mapped); }
+        else if (metadata[i].allows_quantization && metadata[i].requires_imatrix) {
+            if (params->dry_run) { will_require_imatrix = true; }
+            else {
                 LLAMA_LOG_ERROR("\n============================================================================\n"
                                 " ERROR: this quantization requires an importance matrix!\n"
                                 "        - offending tensor: %s\n"
@@ -1229,6 +3377,22 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
         }
     }

+    // report missing imatrix coverage early
+    if (values_data) {
+        std::vector<std::string> no_imatrix;
+        for (size_t i = 0; i < tensors.size(); ++i) {
+            const char * name = metadata[i].name.c_str();
+            if (!metadata[i].allows_quantization || unused_kv_tensors.count(metadata[i].name)) { continue; }
+            if (tensor_name_match_token_embd(name) || tensor_name_match_output_weight(name)) { continue; }
+            if (!values_data->count(metadata[i].remapped_imatrix_name)) { no_imatrix.push_back(metadata[i].name); }
+        }
+
+        if (!no_imatrix.empty()) {
+            LLAMA_LOG_WARN("%s: %zu quantizable tensors have no imatrix data:\n", __func__, no_imatrix.size());
+            for (const auto & name : no_imatrix) { LLAMA_LOG_WARN("%s:     %s\n", __func__, name.c_str()); }
+        }
+    }
+
     // Set split info if needed
     if (n_split > 1) {
         for (size_t i = 0; i < ctx_outs.size(); ++i) {
@@ -1250,6 +3414,92 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::

     const size_t max_buf_size = params->max_buf_size ? params->max_buf_size : LLAMA_QUANT_MAX_BUF_SIZE;

+    std::unordered_map<std::string, ggml_type> bpw_overrides = {};
+    if ((params->target_bpw != -1.0f || params->target_size != -1) && !params->only_copy) {
+        if (params->imatrix) {
+            if (params->pure) {
+                LLAMA_LOG_WARN("%s: --target-bpw/--target-size specified with --pure, ignoring --pure\n", __func__);
+            }
+            if (params->target_size >= 0) {
+                LLAMA_LOG_INFO("%s: computing tensor quantization mix to achieve file size %.2f MiB\n", __func__, (double)params->target_size / 1024.0 / 1024.0);
+            } else {
+                LLAMA_LOG_INFO("%s: computing tensor quantization mix to achieve %.4f bpw\n", __func__, params->target_bpw);
+            }
+
+            if (qs.has_ignored_types) {
+                std::string barred;
+                for (size_t i = 0; i < qs.ignored_types.size(); ++i) {
+                    if (qs.ignored_types[i]) {
+                        if (!barred.empty()) { barred += ", "; }
+                        barred += ggml_type_name((ggml_type)i);
+                    }
+                }
+
+                LLAMA_LOG_INFO("%s: --target-exclude ignores quant types: %s\n", __func__, barred.c_str());
+
+                // pinned types have precedence over ignored
+                for (const auto & p : qs.tensor_type_patterns) {
+                    if (p.type < GGML_TYPE_COUNT && qs.ignored_types[p.type]) {
+                        LLAMA_LOG_WARN("%s: --tensor-type pattern '%s' pins type %s which is ignored by --target-exclude, keeping the pinned type\n",
+                            __func__, p.pattern.c_str(), ggml_type_name(p.type));
+                    }
+                }
+
+                const std::pair<const char *, ggml_type> type_flags[] = {
+                    { "--token-embedding-type", params->token_embedding_type },
+                    { "--output-tensor-type",   params->output_tensor_type },
+                };
+                for (const auto & [flag, type] : type_flags) {
+                    if (type < GGML_TYPE_COUNT && qs.ignored_types[type]) {
+                        LLAMA_LOG_WARN("%s: %s pins type %s which is ignored by --target-exclude, keeping the pinned type\n", __func__, flag, ggml_type_name(type));
+                    }
+                }
+            }
+
+            // Build tensor type map from --tensor-type + embedding + output flags
+            std::unordered_map<std::string, ggml_type> locked_tensors;
+            for (size_t i = 0; i < tensors.size(); ++i) {
+                if (!metadata[i].allows_quantization) { continue; }
+                const char * name = ggml_get_name(tensors[i]->tensor);
+                ggml_type locked = tensor_type_override_for(qs, name);
+                if (metadata[i].category == TENSOR_CATEGORY_TOKEN_EMBD) {
+                    const bool named = locked != GGML_TYPE_COUNT && std::strcmp(name, "per_layer_token_embd.weight") == 0;
+                    if (params->token_embedding_type < GGML_TYPE_COUNT && !named) {
+                        locked = params->token_embedding_type;
+                    } else if (locked == GGML_TYPE_COUNT && qs.has_tied_embeddings && params->output_tensor_type < GGML_TYPE_COUNT) {
+                        // tied embeddings take the output type, same as in llama_tensor_get_type_impl
+                        locked = params->output_tensor_type;
+                    }
+                } else if (metadata[i].category == TENSOR_CATEGORY_OUTPUT && params->output_tensor_type < GGML_TYPE_COUNT) {
+                    locked = params->output_tensor_type;
+                }
+
+                if (locked != GGML_TYPE_COUNT) { locked_tensors[name] = locked; }
+            }
+
+            // do not allocate budget to unused kv tensors
+            for (size_t i = 0; i < tensors.size(); ++i) {
+                if (metadata[i].allows_quantization && unused_kv_tensors.count(metadata[i].name)) {
+                    locked_tensors[metadata[i].name] = metadata[i].target_type;
+                }
+            }
+
+            // get quantization type overrides targeting a given bits per weight budget
+            const auto * lt = locked_tensors.empty() ? nullptr : & locked_tensors;
+            bpw_overrides = target_bpw_type(ml, qs, tensors, mapped, values_data, activations_data, statistics_data, stats_schema, lt, nthread);
+            for (size_t i = 0; i < tensors.size(); ++i) {
+                const std::string name = ggml_get_name(tensors[i]->tensor);
+                auto it = bpw_overrides.find(name);
+                if (it != bpw_overrides.end()) {
+                    metadata[i].target_type = it->second;
+                    metadata[i].requires_imatrix = tensor_requires_imatrix(name.c_str(), metadata[i].target_type, ftype);
+                }
+            }
+        } else {
+            throw std::runtime_error(format("--target-bpw/--target-size require an imatrix but none was provided\n"));
+        }
+    }
+
     int cur_split = -1;
     std::ofstream fout;
     auto close_ofstream = [&]() {
@@ -1280,15 +3530,11 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
     };

     // no output file for --dry-run
-    if (!params->dry_run) {
-        new_ofstream(0);
-    }
+    if (!params->dry_run) { new_ofstream(0); }

-    //
     // main loop: iterate over all weights
-    //
-
     for (size_t i = 0; i < tensors.size(); ++i) {
+        if (params->abort_callback && params->abort_callback(params->abort_callback_data)) { throw std::runtime_error("interrupted"); }
         const auto & weight = *tensors[i];
         const auto & tm = metadata[i];
         ggml_tensor * tensor = weight.tensor;
@@ -1309,16 +3555,12 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
         };

         LLAMA_LOG_INFO("[%4d/%4d] %-36s - [%s], type = %6s, ",
-               ++idx, ml.n_tensors,
-               ggml_get_name(tensor),
-               llama_format_tensor_shape(tensor).c_str(),
-               ggml_type_name(tensor->type));
+            ++idx, ml.n_tensors, ggml_get_name(tensor), llama_format_tensor_shape(tensor).c_str(), ggml_type_name(tensor->type));

         const ggml_type cur_type = tensor->type;
         const ggml_type new_type = tm.target_type;

-        // If we've decided to quantize to the same type the tensor is already
-        // in then there's nothing to do.
+        // If we've decided to quantize to the same type the tensor is already in then there's nothing to do.
         bool quantize = cur_type != new_type;

         size_t new_size;
@@ -1327,25 +3569,19 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
             // the --dry-run option calculates the final quantization size without quantizing
             if (quantize) {
                 new_size = ggml_nrows(tensor) * ggml_row_size(new_type, tensor->ne[0]);
-                LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB (%s)\n",
-                               tensor_size/1024.0/1024.0,
-                               new_size/1024.0/1024.0,
-                               ggml_type_name(new_type));
-                if (!will_require_imatrix && tm.requires_imatrix) {
-                    will_require_imatrix = true;
-                }
+                LLAMA_LOG_INFO("size = %.2f MiB -> %.2f MiB (%s)\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0, ggml_type_name(new_type));
+                if (!will_require_imatrix && tm.requires_imatrix) { will_require_imatrix = true; }
             } else {
                 new_size = tensor_size;
-                LLAMA_LOG_INFO("size = %8.3f MiB\n", new_size/1024.0/1024.0);
+                LLAMA_LOG_INFO("size = %.2f MiB\n", new_size/1024.0/1024.0);
             }
             total_size_org += tensor_size;
             total_size_new += new_size;
-            continue;
         } else {
             // no --dry-run, perform quantization
             if (!quantize) {
                 new_size = tensor_size;
-                LLAMA_LOG_INFO("size = %8.3f MiB\n", tensor_size/1024.0/1024.0);
+                LLAMA_LOG_INFO("size = %.2f MiB\n", tensor_size/1024.0/1024.0);

                 // copy in slabs of whole rows, so that each slab can be validated
                 const size_t row_size   = ggml_row_size(tensor->type, tensor->ne[0]);
@@ -1357,16 +3593,16 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
                 }
             } else {
                 const float * imatrix = nullptr;
-                if (imatrix_data) {
-                    auto it = imatrix_data->find(tm.remapped_imatrix_name);
-                    if (it == imatrix_data->end()) {
-                        LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
+                if (values_data) {
+                    auto it = values_data->find(tm.remapped_imatrix_name);
+                    if (it == values_data->end()) {
+                        LLAMA_LOG_INFO("\n====== %s: did not find imatrix data for %s\n", __func__, tensor->name);
                     } else {
                         if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]*tensor->ne[3]) {
                             imatrix = it->second.data();
                         } else {
                             LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
-                                    int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name);
+                                    (int)it->second.size(), (int)tensor->ne[0] * (int)tensor->ne[2] * (int)tensor->ne[3], tensor->name);

                             // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
                             // this is a significant error and it may be good idea to abort the process if this happens,
@@ -1374,7 +3610,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
                             // tok_embd should be ignored in this case, since it always causes this warning
                             if (!tensor_name_match_token_embd(tensor->name)) {
                                 throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
-                                        int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name));
+                                    (int)it->second.size(), (int)tensor->ne[0] * (int)tensor->ne[2] * (int)tensor->ne[3], tensor->name));
                             }
                         }
                     }
@@ -1391,7 +3627,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
                     throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
                 }

-                LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
+                LLAMA_LOG_INFO("converting to %7s ", ggml_type_name(new_type));
                 fflush(stdout);

                 const int64_t n_per_row = tensor->ne[0];
@@ -1405,7 +3641,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
                 const size_t bytes_per_row = row_size_src + row_size_dst + (tensor->type == GGML_TYPE_F32 ? 0 : n_per_row*sizeof(float));
                 const int64_t nrows_slab = std::max<int64_t>(1, std::min<int64_t>(nrows_total, max_buf_size/bytes_per_row));

-                static const int64_t min_chunk_size = 32 * 512;
+                static constexpr int64_t min_chunk_size = 32 * 512;
                 const int64_t chunk_size = (n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row));

                 // process rows across all experts in one pass to keep all threads busy
@@ -1439,7 +3675,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
                     fout.write((const char *) work.data(), size_cur);
                     new_size += size_cur;
                 }
-                LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0);
+                LLAMA_LOG_INFO("size = %.2f MiB -> %.2f MiB\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0);
             }
             total_size_org += tensor_size;
             total_size_new += new_size;
@@ -1453,33 +3689,24 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::

             // unmap the tensor to free memory
             if (ml.use_mmap) { ml.unmap_weight(weight); }
-
-        } // no --dry-run
-    } // main loop
-
-    if (!params->dry_run) {
-        close_ofstream();
+        }
     }

-    LLAMA_LOG_INFO("%s: model size  = %8.2f MiB (%.2f BPW)\n", __func__, total_size_org/1024.0/1024.0, total_size_org*8.0/ml.n_elements);
-    LLAMA_LOG_INFO("%s: quant size  = %8.2f MiB (%.2f BPW)\n", __func__, total_size_new/1024.0/1024.0, total_size_new*8.0/ml.n_elements);
+    if (!params->dry_run) { close_ofstream(); }
+
+    LLAMA_LOG_INFO("%s: model size  = %8.2f MiB (%7.4f BPW)\n", __func__, total_size_org/1024.0/1024.0, total_size_org*8.0/ml.n_elements);
+    LLAMA_LOG_INFO("%s: quant size  = %8.2f MiB (%7.4f BPW)\n", __func__, total_size_new/1024.0/1024.0, total_size_new*8.0/ml.n_elements);

     if (!params->imatrix && params->dry_run && will_require_imatrix) {
-        LLAMA_LOG_WARN("%s: WARNING: dry run completed successfully, but actually completing this quantization will require an imatrix!\n",
-                       __func__
-        );
+        LLAMA_LOG_WARN("%s: WARNING: dry run completed successfully, but actually completing this quantization will require an imatrix!\n", __func__);
     }

     if (qs.n_fallback > 0) {
-        LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
-                __func__, qs.n_fallback, ml.n_tensors);
+        LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n", __func__, qs.n_fallback, ml.n_tensors);
     }
 }

-//
 // interface implementation
-//
-
 llama_model_quantize_params llama_model_quantize_default_params() {
     llama_model_quantize_params result = {
         /*.nthread                     =*/ 0,
@@ -1494,21 +3721,26 @@ llama_model_quantize_params llama_model_quantize_default_params() {
         /*.dry_run                     =*/ false,
         /*.imatrix                     =*/ nullptr,
         /*.kv_overrides                =*/ nullptr,
-        /*.tensor_type                 =*/ nullptr,
+        /*.tt_overrides                =*/ nullptr,
         /*.prune_layers                =*/ nullptr,
-        /*.max_buf_size                =*/ LLAMA_QUANT_MAX_BUF_SIZE
+        /*.max_buf_size                =*/ LLAMA_QUANT_MAX_BUF_SIZE,
+        /*.activations                 =*/ nullptr,
+        /*.statistics                  =*/ nullptr,
+        /*.stats_schema                =*/ nullptr,
+        /*.target_bpw                  =*/ -1.0f,
+        /*.target_size                 =*/ -1,
+        /*.state_file                  =*/ nullptr,
+        /*.target_exclude              =*/ nullptr,
+        /*.abort_callback              =*/ nullptr,
+        /*.abort_callback_data         =*/ nullptr
     };

     return result;
 }

-uint32_t llama_model_quantize(
-        const char * fname_inp,
-        const char * fname_out,
-        const llama_model_quantize_params * params) {
-    try {
-        llama_model_quantize_impl(fname_inp, fname_out, params);
-    } catch (const std::exception & err) {
+uint32_t llama_model_quantize(const char * fname_inp, const char * fname_out, const llama_model_quantize_params * params) {
+    try { llama_model_quantize_impl(fname_inp, fname_out, params); }
+    catch (const std::exception & err) {
         LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
         return 1;
     }
@@ -1516,32 +3748,25 @@ uint32_t llama_model_quantize(
     return 0;
 }

-//
 // Helper functions for external tools exposed in llama-ext.h
-//
-
-quantize_state_impl * llama_quant_init(
-        const llama_model * model,
-        const llama_model_quantize_params * params) {
+quantize_state_impl * llama_quant_init(const llama_model * model, const llama_model_quantize_params * params) {
     return new quantize_state_impl(*model, params);
 }

-void llama_quant_free(quantize_state_impl * qs) {
+void llama_quant_free(const quantize_state_impl * qs) {
     delete qs;
 }

 llama_model * llama_quant_model_from_metadata(const llama_quant_model_desc * desc) {
     struct llama_model_params mparams = llama_model_default_params();
-    auto arch = llm_arch_from_string(desc->architecture);
+    const auto arch = llm_arch_from_string(desc->architecture);
     auto * model = llama_model_create(arch, mparams);
     model->arch = arch;

     // infer llm_type: only LLM_TYPE_70B matters for quantization logic
-    if (model->arch == LLM_ARCH_LLAMA && desc->n_layer == 80 && desc->n_head != desc->n_head_kv) {
-        model->type = LLM_TYPE_70B;
-    }
+    if (model->arch == LLM_ARCH_LLAMA && desc->n_layer == 80 && desc->n_head != desc->n_head_kv) { model->type = LLM_TYPE_70B; }

-    model->hparams.n_embd             = desc->n_embd;
+    model->hparams.n_embd = desc->n_embd;
     model->hparams.n_embd_head_k_full = desc->n_embd_head_k;
     model->hparams.n_embd_head_v_full = desc->n_embd_head_v;
     model->hparams.n_layer_all        = desc->n_layer;
@@ -1549,44 +3774,41 @@ llama_model * llama_quant_model_from_metadata(const llama_quant_model_desc * des
     model->hparams.n_expert           = desc->n_expert;

     for (uint32_t i = 0; i < desc->n_layer; i++) {
-        model->hparams.n_head_arr[i]    = desc->n_head;
+        model->hparams.n_head_arr[i] = desc->n_head;
         model->hparams.n_head_kv_arr[i] = desc->n_head_kv;
-        model->hparams.n_ff_arr[i]      = desc->n_ff;
+        model->hparams.n_ff_arr[i] = desc->n_ff;
     }

     return model;
 }

-bool llama_quant_tensor_allows_quantization(
-        const quantize_state_impl * qs,
-        const ggml_tensor * tensor) {
+bool llama_quant_tensor_allows_quantization(const quantize_state_impl * qs, const ggml_tensor * tensor) {
     return tensor_allows_quantization(qs->params, qs->model.arch, tensor);
 }

 void llama_quant_compute_types(
-        quantize_state_impl * qs,
-        llama_ftype ftype,
-        ggml_tensor ** tensors,
-        ggml_type * result_types,
-        size_t n_tensors) {
+    quantize_state_impl * qs,
+    const llama_ftype ftype,
+    ggml_tensor ** tensors,
+    ggml_type * result_types,
+    const size_t n_tensors
+) {
     // reset per-computation state
-    qs->n_attention_wv      = 0;
-    qs->n_ffn_down          = 0;
-    qs->n_ffn_gate          = 0;
-    qs->n_ffn_up            = 0;
-    qs->i_attention_wv      = 0;
-    qs->i_ffn_down          = 0;
-    qs->i_ffn_gate          = 0;
-    qs->i_ffn_up            = 0;
-    qs->n_fallback          = 0;
-    qs->has_imatrix         = false;
+    qs->n_attention_wv = 0;
+    qs->n_ffn_down = 0;
+    qs->n_ffn_gate = 0;
+    qs->n_ffn_up = 0;
+    qs->i_attention_wv = 0;
+    qs->i_ffn_down = 0;
+    qs->i_ffn_gate = 0;
+    qs->i_ffn_up = 0;
+    qs->n_fallback = 0;
+    qs->has_imatrix = false;
     qs->has_tied_embeddings = true;

     // build metadata from tensor names
     std::vector<tensor_metadata> metadata(n_tensors);
-    for (size_t i = 0; i < n_tensors; i++) {
-        metadata[i].name = ggml_get_name(tensors[i]);
-    }
+    for (size_t i = 0; i < n_tensors; i++) { metadata[i].name = ggml_get_name(tensors[i]); }

     // initialize counters and categories
     init_quantize_state_counters(*qs, metadata);
@@ -1595,10 +3817,8 @@ void llama_quant_compute_types(
     llama_model_quantize_params local_params = *qs->params;
     local_params.ftype = ftype;

-    ggml_type default_type = llama_ftype_get_default_type(ftype);
+    const ggml_type default_type = llama_ftype_get_default_type(ftype);

     // compute types
-    for (size_t i = 0; i < n_tensors; i++) {
-        result_types[i] = llama_tensor_get_type(*qs, &local_params, tensors[i], default_type, metadata[i]);
-    }
+    for (size_t i = 0; i < n_tensors; i++) { result_types[i] = llama_tensor_get_type(*qs, &local_params, tensors[i], default_type, metadata[i]); }
 }
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 5b997e91b..2e0edcb49 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -350,6 +350,7 @@ llama_build_and_test(test-thread-safety.cpp  LABEL "main backend"  ARGS -m "${MO
 set_tests_properties(test-thread-safety PROPERTIES FIXTURES_REQUIRED test-download-model)

 llama_build_and_test(test-arg-parser.cpp  LABEL behavior)
+llama_build_and_test(test-quantize-target.cpp  LABEL "main behavior backend"  LINK llama)
 llama_build_and_test(test-model-resolution.cpp  LABEL behavior)
 # the test serves its repos from an httplib server, and the library links it privately
 target_link_libraries(test-model-resolution PRIVATE cpp-httplib)
diff --git a/tests/test-quantize-target.cpp b/tests/test-quantize-target.cpp
new file mode 100644
index 000000000..9b1158404
--- /dev/null
+++ b/tests/test-quantize-target.cpp
@@ -0,0 +1,938 @@
+#include "testing.h"
+
+#include "ggml-backend.h"
+#include "ggml-cpp.h"
+#include "gguf.h"
+#include "llama-cpp.h"
+#include "llama.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <map>
+#include <random>
+#include <string>
+#include <vector>
+
+#ifndef _WIN32
+#include <signal.h>
+#endif
+
+static const uint32_t n_vocab = 256;
+static const uint32_t n_embd  = 256;
+static const uint32_t n_ff    = 512;
+static const uint32_t n_head  = 2;
+static const uint32_t n_layer = 4;
+static const float target_bpw = 4.5f;
+static bool verbose = false;
+
+static void set_tensor_data(ggml_tensor * tensor, void * /*userdata*/) {
+    std::mt19937 gen(std::hash<std::string>{}(tensor->name));
+    std::normal_distribution<float> dis(0.0f, 0.1f);
+    std::vector<float> data(ggml_nelements(tensor));
+    for (float & v : data) { v = dis(gen); }
+    ggml_backend_tensor_set(tensor, data.data(), 0, ggml_nbytes(tensor));
+}
+
+// test model
+static bool save_model(const std::string & fname) {
+    gguf_context_ptr meta(gguf_init_empty());
+    gguf_set_val_str(meta.get(), "general.architecture",                   "llama");
+    gguf_set_val_u32(meta.get(), "llama.vocab_size",                       n_vocab);
+    gguf_set_val_u32(meta.get(), "llama.context_length",                   256);
+    gguf_set_val_u32(meta.get(), "llama.embedding_length",                 n_embd);
+    gguf_set_val_u32(meta.get(), "llama.feed_forward_length",              n_ff);
+    gguf_set_val_u32(meta.get(), "llama.block_count",                      n_layer);
+    gguf_set_val_u32(meta.get(), "llama.attention.head_count",             n_head);
+    gguf_set_val_u32(meta.get(), "llama.attention.head_count_kv",          n_head);
+    gguf_set_val_f32(meta.get(), "llama.attention.layer_norm_rms_epsilon", 1e-5f);
+    gguf_set_val_str(meta.get(), "tokenizer.ggml.model",                   "none");
+
+    llama_model_params mparams = llama_model_default_params();
+    ggml_backend_dev_t devs[] = { nullptr };
+    mparams.devices = devs;
+
+    llama_model_ptr model(llama_model_init_from_user(meta.get(), set_tensor_data, nullptr, mparams));
+    if (!model) { return false; }
+    llama_model_save_to_file(model.get(), fname.c_str());
+    return true;
+}
+
+// test imatrix
+struct imatrix_data {
+    std::vector<std::string>        names;
+    std::vector<std::vector<float>> values;
+    std::vector<std::vector<float>> activations;
+    std::vector<std::vector<float>> statistics;
+    std::vector<std::string>        stats_schema;
+};
+
+// stats schema
+static const std::vector<std::string> default_stats_schema = {
+    "sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance"
+};
+
+static std::vector<float> make_stats(std::mt19937 & gen, const int64_t n_per_row) {
+    std::uniform_real_distribution<float> u(0.0f, 1.0f);
+    return {
+        100.0f + 100.0f * u(gen), // sum_sq
+        0.01f * (u(gen) - 0.5f),  // mean
+        (float) n_per_row,        // elements
+        1.0f + u(gen),            // std_deviation
+        u(gen) - 0.5f,            // skewness
+        3.0f * u(gen),            // kurtosis
+        1.0f + u(gen),            // gain
+        80.0f + 20.0f * u(gen),   // h_norm
+        10.0f * u(gen),           // l2_dist
+        0.5f + 0.5f * u(gen),     // cossim
+        0.5f + 0.5f * u(gen),     // pearson
+        u(gen),                   // covariance
+    };
+}
+
+static imatrix_data make_imatrix(const std::string & fname_model, const uint32_t seed) {
+    imatrix_data im;
+
+    ggml_context * ctx_meta = nullptr;
+    const gguf_init_params params = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta };
+    gguf_context_ptr ctx(gguf_init_from_file(fname_model.c_str(), params));
+    ggml_context_ptr meta(ctx_meta);
+    if (!ctx) { return im; }
+
+    std::mt19937 gen(seed);
+    std::uniform_real_distribution<float> u(0.0f, 1.0f);
+    for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) {
+        const char * name = gguf_get_tensor_name(ctx.get(), i);
+        const ggml_tensor * tensor = ggml_get_tensor(meta.get(), name);
+        if (ggml_n_dims(tensor) < 2 || strcmp(name, "token_embd.weight") == 0) { continue; }
+
+        const int64_t n_per_row = tensor->ne[0];
+        std::vector<float> values(n_per_row);
+        std::vector<float> activations(n_per_row);
+        for (int64_t j = 0; j < n_per_row; j++) {
+            activations[j] = u(gen) - 0.5f;
+            values[j] = activations[j] * activations[j] + std::exp(2.0f * u(gen) - 1.0f);
+        }
+
+        im.names.push_back(name);
+        im.values.push_back(std::move(values));
+        im.activations.push_back(std::move(activations));
+        im.statistics.push_back(make_stats(gen, n_per_row));
+    }
+
+    im.stats_schema = default_stats_schema;
+
+    return im;
+}
+
+static std::vector<llama_model_imatrix_data> imatrix_list(const imatrix_data & im, const std::vector<std::vector<float>> & data) {
+    std::vector<llama_model_imatrix_data> list;
+    for (size_t i = 0; i < im.names.size(); i++) {
+        if (data[i].empty()) { continue; }
+        list.push_back({ im.names[i].c_str(), data[i].data(), data[i].size() });
+    }
+
+    list.push_back({ nullptr, nullptr, 0 });
+
+    return list;
+}
+
+struct quant_run {
+    uint32_t rc = 1; // 0 when quantization succeeds and output is processed
+    std::string log;
+    std::map<std::string, ggml_type> types;
+    size_t n_bytes = 0; // tensor data
+    size_t n_elements = 0;
+    size_t file_size = 0;
+};
+
+static void log_callback(ggml_log_level /*level*/, const char * text, void * user_data) {
+    if (user_data) { static_cast<std::string *>(user_data)->append(text); }
+    if (verbose) { fputs(text, stderr); }
+}
+
+static quant_run quantize(const std::string & fname_inp, const std::string & fname_out, const imatrix_data & im, llama_model_quantize_params params) {
+    const auto values      = imatrix_list(im, im.values);
+    const auto activations = imatrix_list(im, im.activations);
+    const auto statistics  = imatrix_list(im, im.statistics);
+    std::vector<const char *> stats_schema;
+    for (const auto & name : im.stats_schema) { stats_schema.push_back(name.c_str()); }
+    stats_schema.push_back(nullptr);
+    params.imatrix      = values.data();
+    params.activations  = activations.data();
+    params.statistics   = statistics.data();
+    params.stats_schema = im.stats_schema.empty() ? nullptr : stats_schema.data();
+
+    quant_run run;
+    // clear previous run's output
+    std::filesystem::remove(fname_out);
+    llama_log_set(log_callback, &run.log);
+    run.rc = llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), &params);
+    llama_log_set(log_callback, nullptr);
+    if (run.rc != 0) { return run; }
+
+    ggml_context * ctx_meta = nullptr;
+    const gguf_init_params gparams = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta };
+    gguf_context_ptr ctx(gguf_init_from_file(fname_out.c_str(), gparams));
+    ggml_context_ptr meta(ctx_meta);
+    if (!ctx) {
+        run.rc = 1;
+        return run;
+    }
+
+    for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) {
+        const char * name = gguf_get_tensor_name(ctx.get(), i);
+        run.types[name] = gguf_get_tensor_type(ctx.get(), i);
+        run.n_bytes    += gguf_get_tensor_size(ctx.get(), i);
+        run.n_elements += ggml_nelements(ggml_get_tensor(meta.get(), name));
+    }
+
+    run.file_size = std::filesystem::file_size(fname_out);
+
+    return run;
+}
+
+static size_t count_matches(const std::string & log, const std::string & text) {
+    size_t n = 0;
+    for (size_t pos = log.find(text); pos != std::string::npos; pos = log.find(text, pos + text.size())) { n++; }
+
+    return n;
+}
+
+static size_t logged_number(const std::string & log, const std::string & text) {
+    const size_t pos = log.find(text);
+    return pos == std::string::npos ? SIZE_MAX : (size_t) std::strtoull(log.c_str() + pos + text.size(), nullptr, 10);
+}
+
+static size_t count_type(const quant_run & run, const ggml_type type) {
+    size_t n = 0;
+    for (const auto & it : run.types) { n += it.second == type; }
+
+    return n;
+}
+
+static size_t count_type_changes(const quant_run & a, const quant_run & b) {
+    size_t n = 0;
+    for (const auto & it : a.types) {
+        const auto other = b.types.find(it.first);
+        n += other == b.types.end() || other->second != it.second;
+    }
+
+    return n;
+}
+
+// the type name of a tensor in a run's output, or "none" if the output has no such tensor
+static std::string type_name_of(const quant_run & run, const std::string & name) {
+    const auto it = run.types.find(name);
+    return it == run.types.end() ? "none" : ggml_type_name(it->second);
+}
+
+// tensor quantization mix rows
+static std::vector<std::string> mix_rows(const quant_run & run) {
+    std::vector<std::string> rows;
+    for (size_t pos = run.log.find("\terror: "); pos != std::string::npos; pos = run.log.find("\terror: ", pos + 1)) {
+        const size_t start = run.log.rfind('\n', pos) + 1;
+        rows.push_back(run.log.substr(start, run.log.find('\n', pos) - start));
+    }
+
+    return rows;
+}
+
+static size_t count_row_changes(const quant_run & a, const quant_run & b) {
+    const std::vector<std::string> rows_a = mix_rows(a);
+    const std::vector<std::string> rows_b = mix_rows(b);
+    if (rows_a.empty() || rows_a.size() != rows_b.size()) { return SIZE_MAX; }
+
+    size_t n = 0;
+    for (size_t i = 0; i < rows_a.size(); i++) { n += rows_a[i] != rows_b[i]; }
+
+    return n;
+}
+
+static std::string read_file(const std::string & fname) {
+    std::ifstream file(fname, std::ios::binary);
+    return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
+}
+
+static void write_file(const std::string & fname, const std::string & data) {
+    std::ofstream file(fname, std::ios::binary);
+    file << data;
+}
+
+static const size_t state_header_size    = 24; // magic, model id, tensor count
+static const size_t state_entry_size     = 28; // candidate count, choice, min and max bpw, elements
+static const size_t state_candidate_size = 24; // type, bpw, bytes, error
+
+// offset of the first tensor's candidate count; 0 if the checkpoint holds no candidate
+static size_t first_count_offset(const std::string & state) {
+    uint32_t len = 0;
+    if (state.size() < state_header_size + sizeof(len)) { return 0; }
+    memcpy(&len, state.data() + state_header_size, sizeof(len));
+    const size_t offset = state_header_size + sizeof(len) + len;
+
+    return state.size() >= offset + state_entry_size + state_candidate_size ? offset : 0;
+}
+
+struct fixture {
+    std::string  fname_model;
+    std::string  fname_out;
+    std::string  fname_state;
+    imatrix_data im;
+    quant_run    base;
+};
+
+// first run parameters
+static llama_model_quantize_params base_params(const fixture & f) {
+    llama_model_quantize_params params = llama_model_quantize_default_params();
+    params.nthread    = 4;
+    params.target_bpw = target_bpw;
+    params.state_file = f.fname_state.c_str();
+
+    return params;
+}
+
+static std::string sibling_path(const fixture & f, const std::string & name) {
+    return (std::filesystem::path(f.fname_state).parent_path() / name).string();
+}
+
+static void test_target_bpw(testing & t, const fixture & f) {
+    const double bpw = 8.0 * f.base.n_bytes / f.base.n_elements;
+    t.log("final bpw " + std::to_string(bpw));
+    t.assert_true("bpw does not exceed the target", bpw <= target_bpw);
+    t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05);
+}
+
+static void test_state_checkpoint(testing & t, const fixture & f) {
+    const size_t n_scored = count_matches(f.base.log, "processing tensor");
+    const std::string n_tensors = std::to_string(n_scored) + " tensors";
+    t.assert_true("first run scores tensors", n_scored > 0);
+    t.assert_equal("first run saves the checkpoint", (size_t) 1, count_matches(f.base.log, "saved target progress for " + n_tensors + " to " + f.fname_state));
+
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, base_params(f));
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+    t.assert_equal("second run loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)"));
+    t.assert_equal("second run scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor"));
+    t.assert_equal("tensors whose type changed", (size_t) 0, count_type_changes(f.base, run));
+}
+
+static void test_target_size(testing & t, const fixture & f) {
+    llama_model_quantize_params params = base_params(f);
+    params.target_bpw  = -1.0f;
+    params.target_size = (int64_t) f.base.file_size * 9 / 10;
+
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+
+    const int64_t diff = (int64_t) run.file_size - params.target_size;
+    t.log("file size " + std::to_string(run.file_size) + ", " + std::to_string(diff) + " bytes from the target");
+    t.assert_true("the file is within 8 KiB of the target", std::abs(diff) <= 8 * 1024);
+}
+
+static void test_excluded_type(testing & t, const fixture & f) {
+    ggml_type excluded = GGML_TYPE_COUNT;
+    for (const auto & it : f.base.types) {
+        if (it.second != GGML_TYPE_F32 && (excluded == GGML_TYPE_COUNT || count_type(f.base, it.second) > count_type(f.base, excluded))) {
+            excluded = it.second;
+        }
+    }
+
+    t.assert_true("first run selects a type", excluded != GGML_TYPE_COUNT);
+    if (excluded == GGML_TYPE_COUNT) { return; }
+    t.log(std::string("excluding ") + ggml_type_name(excluded) + ", the type of " + std::to_string(count_type(f.base, excluded)) + " tensors");
+
+    const ggml_type exclude[] = { excluded, GGML_TYPE_COUNT };
+    llama_model_quantize_params params = base_params(f);
+    params.target_exclude = exclude;
+
+    params.state_file = nullptr;
+    const quant_run scored = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, scored.rc);
+    t.assert_equal("scored with excluded types, tensors of the excluded type", (size_t) 0, count_type(scored, excluded));
+
+    params.state_file = f.fname_state.c_str();
+    const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors";
+    const quant_run loaded = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, loaded.rc);
+    t.assert_equal("run loads the checkpoint", (size_t) 1, count_matches(loaded.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)"));
+    t.assert_equal("run scores no tensor", (size_t) 0, count_matches(loaded.log, "processing tensor"));
+    t.assert_equal("loaded from checkpoint, tensors of the excluded type", (size_t) 0, count_type(loaded, excluded));
+    t.assert_equal("run warns that the checkpoint is not saved", (size_t) 1, count_matches(loaded.log, "state checkpoint cannot be saved while --target-exclude is active"));
+    t.assert_equal("checkpoint is not saved while types are excluded", (size_t) 0, count_matches(loaded.log, "saved target progress"));
+}
+
+static void test_unknown_type(testing & t, const fixture & f) {
+    std::string state = read_file(f.fname_state);
+    const size_t offset = first_count_offset(state);
+    t.assert_true("first run's checkpoint holds a candidate", offset > 0);
+    if (offset == 0) { return; }
+
+    // type 4 was Q4_2; within ggml_type range but invalid
+    const int32_t type = 4;
+    memcpy(&state[offset + state_entry_size], &type, sizeof(type));
+    const std::string fname = sibling_path(f, "unknown.bpw_state");
+    write_file(fname, state);
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+    t.assert_equal("unknown type is reported", (size_t) 1, count_matches(run.log, "candidate type is not in the selection pool, ignoring state file"));
+    t.assert_equal("unknown checkpoint is not loaded", (size_t) 0, count_matches(run.log, "using " + fname));
+    t.assert_equal("unknown checkpoint is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor"));
+    t.assert_equal("scored again, tensors whose type changed", (size_t) 0, count_type_changes(f.base, run));
+}
+
+static void test_zero_candidates(testing & t, const fixture & f) {
+    std::string state = read_file(f.fname_state);
+    const size_t offset = first_count_offset(state);
+    t.assert_true("the first run's checkpoint holds a candidate", offset > 0);
+    if (offset == 0) { return; }
+
+    // drop the first tensor's candidates
+    uint64_t n = 0;
+    memcpy(&n, &state[offset], sizeof(n));
+    state.erase(offset + state_entry_size, n * state_candidate_size);
+    n = 0;
+    memcpy(&state[offset], &n, sizeof(n));
+    const std::string fname = sibling_path(f, "zero.bpw_state");
+    write_file(fname, state);
+
+    // with a type excluded, an empty candidate list that is loaded fails the call instead of crashing the test
+    const ggml_type exclude[] = { GGML_TYPE_IQ1_S, GGML_TYPE_COUNT };
+    llama_model_quantize_params params = base_params(f);
+    params.state_file     = fname.c_str();
+    params.target_exclude = exclude;
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+    t.assert_equal("empty candidate list is reported", (size_t) 1, count_matches(run.log, "candidate count out of range, ignoring state file"));
+    t.assert_equal("checkpoint with an empty candidate list is not loaded", (size_t) 0, count_matches(run.log, "using " + fname));
+    t.assert_equal("checkpoint with an empty candidate list is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor"));
+}
+
+static void test_truncated(testing & t, const fixture & f) {
+    const std::string state = read_file(f.fname_state);
+    const size_t offset = first_count_offset(state);
+    t.assert_true("first run's checkpoint has a candidate", offset > 0);
+    if (offset == 0) { return; }
+
+    // cut before the first candidate count, then before the first candidate type
+    const std::string fname = sibling_path(f, "truncated.bpw_state");
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    write_file(fname, state.substr(0, offset));
+    const quant_run at_count = quantize(f.fname_model, f.fname_out, f.im, params);
+    write_file(fname, state.substr(0, offset + state_entry_size));
+    const quant_run at_type = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, at_count.rc);
+    t.assert_equal("checkpoint cut before a candidate count is reported as truncated", (size_t) 1, count_matches(at_count.log, "state file truncated or read error, ignoring"));
+    t.assert_equal("quantize succeeds", 0u, at_type.rc);
+    t.assert_equal("checkpoint cut before a candidate type is reported as truncated", (size_t) 1, count_matches(at_type.log, "state file truncated or read error, ignoring"));
+}
+
+static void test_missing_dir(testing & t, const fixture & f) {
+    const std::string dir   = sibling_path(f, "no-such-dir");
+    const std::string fname = (std::filesystem::path(dir) / "model.bpw_state").string();
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("path in missing directory fails", 1u, run.rc);
+    t.assert_equal("path in missing directory is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": "));
+    t.assert_equal("path in missing directory stops execution before scoring", (size_t) 0, count_matches(run.log, "processing tensor"));
+    t.assert_true("missing directory is not created", !std::filesystem::exists(dir));
+}
+
+static void test_unreadable_file(testing & t, const fixture & f) {
+#ifdef _WIN32
+    GGML_UNUSED(f);
+    t.skip("POSIX permissions only");
+#else
+    namespace fs = std::filesystem;
+    std::error_code ec;
+    const std::string fname = sibling_path(f, "locked.bpw_state");
+    write_file(fname, "forbidden");
+    // write-only, so that a probe that opens the file for writing could still damage it
+    fs::permissions(fname, fs::perms::owner_write, ec);
+    if (std::ifstream(fname).good()) {
+        fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec);
+        t.skip("the file can still be read, as by root");
+        return;
+    }
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+    const bool kept_perms = fs::status(fname, ec).permissions() == fs::perms::owner_write;
+    fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec);
+    t.assert_equal("an unreadable file fails the call", 1u, run.rc);
+    t.assert_equal("an unreadable file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": "));
+    t.assert_equal("an unreadable file stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor"));
+    t.assert_true("an unreadable file keeps its permissions", kept_perms);
+    t.assert_true("an unreadable file keeps its content", read_file(fname) == "forbidden");
+#endif
+}
+
+static void test_directory_path(testing & t, const fixture & f) {
+    const std::string fname = sibling_path(f, "dir.bpw_state");
+    std::filesystem::create_directory(fname);
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("a directory instead of a file fails the call", 1u, run.rc);
+    t.assert_equal("a directory instead of a file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": "));
+    t.assert_equal("a directory stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor"));
+    t.assert_true("the directory is left as it was", std::filesystem::is_directory(fname) && std::filesystem::is_empty(fname));
+}
+
+static void test_save_error(testing & t, const fixture & f) {
+    const std::string fname = sibling_path(f, "unsaved.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+    std::filesystem::create_directory(fname + ".tmp");
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+    t.assert_equal("a failed save is reported", (size_t) 1, count_matches(run.log, "failed to save progress to " + fname + ".tmp (open error)"));
+    t.assert_equal("a failed save logs no saved checkpoint", (size_t) 0, count_matches(run.log, "saved target progress"));
+}
+
+static void test_imatrix_swap(testing & t, const fixture & f) {
+    const imatrix_data im = make_imatrix(f.fname_model, 4321);
+    const std::string fname = sibling_path(f, "swap.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = nullptr;
+    const quant_run fresh = quantize(f.fname_model, f.fname_out, im, params);
+    params.state_file = fname.c_str();
+    const quant_run reused = quantize(f.fname_model, f.fname_out, im, params);
+    t.log(std::to_string(count_type_changes(f.base, fresh)) + " tensors change type with the other imatrix");
+    t.assert_equal("quantize succeeds", 0u, fresh.rc);
+    t.assert_equal("quantize succeeds", 0u, reused.rc);
+    t.assert_equal("a checkpoint from another imatrix is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
+    t.assert_equal("a checkpoint from another imatrix is scored again", count_matches(f.base.log, "processing tensor"), count_matches(reused.log, "processing tensor"));
+    t.assert_equal("scored again with another imatrix, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused));
+}
+
+static void test_imatrix_parts(testing & t, const fixture & f) {
+    // one float doubled in one list at a time
+    auto check = [&](const std::string & part, const imatrix_data & im) {
+        const std::string fname = sibling_path(f, part + ".bpw_state");
+        write_file(fname, read_file(f.fname_state));
+
+        llama_model_quantize_params params = base_params(f);
+        params.state_file = fname.c_str();
+        const quant_run run = quantize(f.fname_model, f.fname_out, im, params);
+        t.assert_equal("quantize succeeds", 0u, run.rc);
+        t.assert_equal("a checkpoint from other " + part + " is reported", (size_t) 1, count_matches(run.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
+        t.assert_equal("a checkpoint from other " + part + " is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor"));
+    };
+
+    imatrix_data im = f.im;
+    im.values[0][0] *= 2.0f;
+    check("values", im);
+
+    im = f.im;
+    im.activations[0][0] *= 2.0f;
+    check("activations", im);
+
+    im = f.im;
+    im.statistics[0][0] *= 2.0f;
+    check("statistics", im);
+}
+
+static void test_imatrix_order(testing & t, const fixture & f) {
+    // the same imatrix data, passed in reverse order
+    imatrix_data im = f.im;
+    std::reverse(im.names.begin(),       im.names.end());
+    std::reverse(im.values.begin(),      im.values.end());
+    std::reverse(im.activations.begin(), im.activations.end());
+    std::reverse(im.statistics.begin(),  im.statistics.end());
+    const std::string fname = sibling_path(f, "reversed.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors";
+    const quant_run run = quantize(f.fname_model, f.fname_out, im, params);
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+    t.assert_equal("the same imatrix in another order loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + fname + " (data for " + n_tensors + " loaded)"));
+    t.assert_equal("the same imatrix in another order scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor"));
+}
+
+static void test_pruned_layer(testing & t, const fixture & f) {
+    // pruning a block renumbers the ones after it
+    const int32_t prune[] = { 1, -1 };
+    const std::string fname = sibling_path(f, "pruned.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+
+    llama_model_quantize_params params = base_params(f);
+    params.prune_layers = prune;
+    params.state_file   = nullptr;
+    const quant_run fresh = quantize(f.fname_model, f.fname_out, f.im, params);
+    params.state_file = fname.c_str();
+    const quant_run reused = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("quantize succeeds", 0u, fresh.rc);
+    t.assert_equal("quantize succeeds", 0u, reused.rc);
+    t.assert_equal("a checkpoint without pruning is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
+    t.assert_equal("a checkpoint without pruning is scored again", count_matches(fresh.log, "processing tensor"), count_matches(reused.log, "processing tensor"));
+    t.assert_equal("scored again with a pruned block, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused));
+
+    // another block pruned, reusing the checkpoint saved for block 1
+    const int32_t prune_other[] = { 2, -1 };
+    params.prune_layers = prune_other;
+    const quant_run other = quantize(f.fname_model, f.fname_out, f.im, params);
+    t.assert_equal("the pruned run saves its checkpoint", (size_t) 1, count_matches(reused.log, "saved target progress"));
+    t.assert_equal("quantize succeeds", 0u, other.rc);
+    t.assert_equal("a checkpoint for another pruned block is reported", (size_t) 1, count_matches(other.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
+    t.assert_equal("a checkpoint for another pruned block is scored again", count_matches(fresh.log, "processing tensor"), count_matches(other.log, "processing tensor"));
+}
+
+static void test_stats_order(testing & t, const fixture & f) {
+    // stats in reverse order
+    imatrix_data im = f.im;
+    std::reverse(im.stats_schema.begin(), im.stats_schema.end());
+    for (auto & stats : im.statistics) { std::reverse(stats.begin(), stats.end()); }
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = nullptr;
+    const quant_run run = quantize(f.fname_model, f.fname_out, im, params);
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+    t.assert_equal("statistics in different order", (size_t) 0, count_matches(run.log, "skipping CNIF"));
+    t.assert_equal("statistics in different order, rows that changed", (size_t) 0, count_row_changes(f.base, run));
+}
+
+static void test_stats_missing(testing & t, const fixture & f) {
+    // tensor whose stats vector is cut short or left out
+    const size_t k = std::find(f.im.names.begin(), f.im.names.end(), "blk.1.ffn_down.weight") - f.im.names.begin();
+    t.assert_true("imatrix has blk.1.ffn_down.weight", k < f.im.names.size());
+    if (k == f.im.names.size()) { return; }
+
+    // pearson under another name
+    imatrix_data renamed = f.im;
+    std::replace(renamed.stats_schema.begin(), renamed.stats_schema.end(), std::string("pearson"), std::string("spearman"));
+    const std::string fname = sibling_path(f, "renamed.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+
+    llama_model_quantize_params params = base_params(f);
+    params.state_file = fname.c_str();
+    const quant_run missing = quantize(f.fname_model, f.fname_out, renamed, params);
+
+    // no names
+    imatrix_data unnamed = f.im;
+    unnamed.stats_schema.clear();
+    params.state_file = nullptr;
+    const quant_run no_names = quantize(f.fname_model, f.fname_out, unnamed, params);
+
+    // stats vector cut before pearson
+    imatrix_data cut = f.im;
+    cut.statistics[k].resize(10);
+    const quant_run short_stats = quantize(f.fname_model, f.fname_out, cut, params);
+    imatrix_data dropped = f.im;
+    dropped.statistics[k].clear();
+    const quant_run no_stats = quantize(f.fname_model, f.fname_out, dropped, params);
+
+    const size_t n_changed = count_row_changes(f.base, missing);
+    t.log(std::to_string(n_changed) + " mix rows change without CNIF");
+    t.assert_equal("quantize succeeds", 0u, missing.rc);
+    t.assert_true("missing metric changes the mix", n_changed > 0 && n_changed != SIZE_MAX);
+    t.assert_equal("missing metric is reported", (size_t) 1, count_matches(missing.log, "statistics have no pearson metric, skipping CNIF"));
+    t.assert_equal("checkpoint with different statistics names is reported", (size_t) 1, count_matches(missing.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
+    t.assert_equal("checkpoint with different statistics names is scored again", count_matches(f.base.log, "processing tensor"), count_matches(missing.log, "processing tensor"));
+    t.assert_equal("quantize succeeds", 0u, no_names.rc);
+    t.assert_equal("statistics without names are reported", (size_t) 1, count_matches(no_names.log, "statistics have no sum_sq metric, skipping CNIF"));
+    t.assert_equal("statistics without names log one line", (size_t) 1, count_matches(no_names.log, "skipping CNIF"));
+    t.assert_equal("statistics without names, rows that differ from a missing metric", (size_t) 0, count_row_changes(missing, no_names));
+    t.assert_equal("quantize succeeds", 0u, short_stats.rc);
+    t.assert_equal("a short stats vector is not reported as a missing metric", (size_t) 0, count_matches(short_stats.log, "skipping CNIF"));
+    t.assert_equal("quantize succeeds", 0u, no_stats.rc);
+    t.assert_equal("a short stats vector, rows that differ from a left-out one", (size_t) 0, count_row_changes(no_stats, short_stats));
+}
+
+// counts its calls, and asks to stop at call number stop_at only
+struct terminate_probe {
+    size_t n_calls = 0;
+    size_t stop_at = 0;
+};
+
+static bool terminate_at(void * data) {
+    auto * probe = static_cast<terminate_probe *>(data);
+    return ++probe->n_calls == probe->stop_at;
+}
+
+static void test_abort_callback(testing & t, const fixture & f) {
+    // full scoring no interruptions
+    terminate_probe counter;
+    llama_model_quantize_params params = base_params(f);
+    params.state_file          = nullptr;
+    params.abort_callback      = terminate_at;
+    params.abort_callback_data = &counter;
+    const quant_run counted = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    // interrupt at half the calls
+    terminate_probe stopper;
+    stopper.stop_at = counter.n_calls / 2;
+    const std::string fname = sibling_path(f, "interrupted.bpw_state");
+    params.state_file          = fname.c_str();
+    params.abort_callback_data = &stopper;
+    const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params);
+    const bool stopped_wrote = std::filesystem::exists(f.fname_out);
+    params.abort_callback = nullptr;
+    const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    const size_t n_total = count_matches(f.base.log, "processing tensor");
+    const size_t n_saved = logged_number(stopped.log, "interrupted, saving progress for ");
+    t.log(std::to_string(n_saved) + " of " + std::to_string(n_total) + " tensors scored before the stop at call " + std::to_string(stopper.stop_at) + " of " + std::to_string(counter.n_calls));
+    t.assert_equal("quantize succeeds", 0u, counted.rc);
+    t.assert_equal("a callback that never asks to stop, mix rows that changed", (size_t) 0, count_row_changes(f.base, counted));
+    t.assert_equal("the interrupted call fails", 1u, stopped.rc);
+    t.assert_equal("the stop is reported", (size_t) 1, count_matches(stopped.log, "failed to quantize: interrupted"));
+    t.assert_true("the stop comes part way through the scoring", n_saved > 0 && n_saved < n_total);
+    t.assert_equal("the stopped run saves what it scored", (size_t) 1, count_matches(stopped.log, "saved target progress for " + std::to_string(n_saved) + " tensors to " + fname));
+    t.assert_true("the stopped run writes no output", !stopped_wrote);
+    t.assert_equal("quantize succeeds", 0u, resumed.rc);
+    t.assert_equal("the resumed run loads the saved tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_saved) + " tensors loaded)"));
+    t.assert_equal("the resumed run scores the rest", n_total - n_saved, count_matches(resumed.log, "processing tensor"));
+    t.assert_equal("resumed, mix rows that differ from the first run", (size_t) 0, count_row_changes(f.base, resumed));
+
+    // without a target, the main loop calls it once per tensor
+    terminate_probe loop_stopper;
+    loop_stopper.stop_at = 2;
+    llama_model_quantize_params plain = llama_model_quantize_default_params();
+    plain.nthread             = 4;
+    plain.abort_callback      = terminate_at;
+    plain.abort_callback_data = &loop_stopper;
+    const quant_run main_loop = quantize(f.fname_model, f.fname_out, f.im, plain);
+    t.assert_equal("a stop in the main loop fails the call", 1u, main_loop.rc);
+    t.assert_equal("a stop in the main loop is reported", (size_t) 1, count_matches(main_loop.log, "failed to quantize: interrupted"));
+    t.assert_equal("the main loop stops at the call that asks", (size_t) 2, loop_stopper.n_calls);
+}
+
+static void test_interrupt_first_call(testing & t, const fixture & f) {
+    // a copy of the checkpoint, stopped at the first call, before the workers read it back
+    const size_t n_total = count_matches(f.base.log, "processing tensor");
+    const std::string fname = sibling_path(f, "first-call.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+    terminate_probe stopper;
+    stopper.stop_at = 1;
+    llama_model_quantize_params params = base_params(f);
+    params.state_file          = fname.c_str();
+    params.abort_callback      = terminate_at;
+    params.abort_callback_data = &stopper;
+    const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params);
+    params.abort_callback = nullptr;
+    const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    t.assert_equal("the stopped call fails", 1u, stopped.rc);
+    t.assert_equal("the checkpoint keeps its tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_total) + " tensors loaded)"));
+    t.assert_equal("the next run scores nothing", (size_t) 0, count_matches(resumed.log, "processing tensor"));
+}
+
+#ifndef _WIN32
+static void app_signal_handler(int, siginfo_t *, void *) {}
+
+// true when both have the same handler, flags and mask
+static bool same_action(const struct sigaction & a, const struct sigaction & b) {
+    if (a.sa_flags != b.sa_flags) { return false; }
+    if ((a.sa_flags & SA_SIGINFO) ? a.sa_sigaction != b.sa_sigaction : a.sa_handler != b.sa_handler) { return false; }
+    for (int sig = 1; sig < NSIG; sig++) {
+        if (sigismember(&a.sa_mask, sig) != sigismember(&b.sa_mask, sig)) { return false; }
+    }
+
+    return true;
+}
+
+// read SIGINT and SIGTERM disposition
+struct disposition_probe {
+    size_t n_calls = 0;
+    struct sigaction during[2];
+};
+
+static bool probe_dispositions(void * data) {
+    auto * probe = static_cast<disposition_probe *>(data);
+    if (probe->n_calls++ == 0) {
+        sigaction(SIGINT,  nullptr, &probe->during[0]);
+        sigaction(SIGTERM, nullptr, &probe->during[1]);
+    }
+
+    return false;
+}
+#endif
+
+static void test_signal_handlers(testing & t, const fixture & f) {
+#ifdef _WIN32
+    GGML_UNUSED(f);
+    t.skip("POSIX signals only");
+#else
+    struct sigaction app = {};
+    app.sa_sigaction = app_signal_handler;
+    app.sa_flags = SA_SIGINFO;
+    sigemptyset(&app.sa_mask);
+    sigaddset(&app.sa_mask, SIGTERM);
+
+    const int signals[] = { SIGINT, SIGTERM };
+    struct sigaction prev[2], before[2], after[2];
+    for (int i = 0; i < 2; i++) {
+        sigaction(signals[i], &app, &prev[i]);
+        sigaction(signals[i], nullptr, &before[i]);
+    }
+
+    // checkpoint exists, should not score
+    const std::string fname = sibling_path(f, "signals.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+    disposition_probe probe = {};
+    llama_model_quantize_params params = base_params(f);
+    params.state_file          = fname.c_str();
+    params.abort_callback      = probe_dispositions;
+    params.abort_callback_data = &probe;
+    const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    for (int i = 0; i < 2; i++) {
+        sigaction(signals[i], nullptr, &after[i]);
+        sigaction(signals[i], &prev[i], nullptr);
+    }
+    t.assert_equal("quantize succeeds", 0u, run.rc);
+    t.assert_true("the callback is called", probe.n_calls > 0);
+    t.assert_true("SIGINT keeps its handler, flags and mask during a call", same_action(before[0], probe.during[0]));
+    t.assert_true("SIGTERM keeps its handler, flags and mask during a call", same_action(before[1], probe.during[1]));
+    t.assert_true("SIGINT keeps its handler, flags and mask after a call", same_action(before[0], after[0]));
+    t.assert_true("SIGTERM keeps its handler, flags and mask after a call", same_action(before[1], after[1]));
+#endif
+}
+
+static void test_type_flags(testing & t, const fixture & f) {
+    t.assert_true("without the flags, neither tensor has its flag's type", type_name_of(f.base, "token_embd.weight") != "q8_0" && type_name_of(f.base, "output.weight") != "q6_K");
+
+    // a copy of the checkpoint, so that nothing is scored
+    const std::string fname = sibling_path(f, "flags.bpw_state");
+    write_file(fname, read_file(f.fname_state));
+    llama_model_quantize_params params = base_params(f);
+    params.state_file           = fname.c_str();
+    params.token_embedding_type = GGML_TYPE_Q8_0;
+    params.output_tensor_type   = GGML_TYPE_Q6_K;
+    const quant_run flags = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    // the same two tensors pinned through --tensor-type
+    const llama_model_tensor_override same[] = {
+        { "^token_embd\\.weight$", GGML_TYPE_Q8_0 }, { "^output\\.weight$", GGML_TYPE_Q6_K }, { nullptr, GGML_TYPE_COUNT },
+    };
+    llama_model_quantize_params patterns = base_params(f);
+    patterns.state_file   = fname.c_str();
+    patterns.tt_overrides = same;
+    const quant_run by_pattern = quantize(f.fname_model, f.fname_out, f.im, patterns);
+
+    // --tensor-type names both tensors too, at another type
+    const llama_model_tensor_override other[] = {
+        { "^token_embd\\.weight$", GGML_TYPE_Q5_0 }, { "^output\\.weight$", GGML_TYPE_Q5_0 }, { nullptr, GGML_TYPE_COUNT },
+    };
+    params.tt_overrides = other;
+    const quant_run named = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    // the flags' types barred
+    constexpr ggml_type exclude[] = { GGML_TYPE_Q8_0, GGML_TYPE_Q6_K, GGML_TYPE_COUNT };
+    params.tt_overrides   = nullptr;
+    params.target_exclude = exclude;
+    const quant_run barred = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    // only --output-tensor-type: the model is not tied, so the token embedding is not pinned
+    params.token_embedding_type = GGML_TYPE_COUNT;
+    params.target_exclude       = nullptr;
+    const quant_run output_only = quantize(f.fname_model, f.fname_out, f.im, params);
+
+    const double bpw = 8.0 * flags.n_bytes / flags.n_elements;
+    t.log("realised bpw with the flags " + std::to_string(bpw));
+    t.assert_equal("quantize succeeds", 0u, flags.rc);
+    t.assert_equal("--token-embedding-type sets the token embedding", std::string("q8_0"), type_name_of(flags, "token_embd.weight"));
+    t.assert_equal("--output-tensor-type sets the output", std::string("q6_K"), type_name_of(flags, "output.weight"));
+    t.assert_equal("flags pin two tensors", (size_t) 2, count_matches(flags.log, "(pinned)"));
+    t.assert_true("bpw does not exceed the target", bpw <= target_bpw);
+    t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05);
+    t.assert_equal("quantize succeeds", 0u, by_pattern.rc);
+    t.assert_equal("flags and same --tensor-type pins, mix rows that differ", (size_t) 0, count_row_changes(by_pattern, flags));
+    t.assert_equal("quantize succeeds", 0u, named.rc);
+    t.assert_equal("--token-embedding-type beats --tensor-type", std::string("q8_0"), type_name_of(named, "token_embd.weight"));
+    t.assert_equal("--output-tensor-type beats --tensor-type", std::string("q6_K"), type_name_of(named, "output.weight"));
+    t.assert_equal("quantize succeeds", 0u, barred.rc);
+    t.assert_equal("excluded --token-embedding-type is reported", (size_t) 1, count_matches(barred.log, "--token-embedding-type pins type q8_0 which is ignored by --target-exclude, keeping the pinned type"));
+    t.assert_equal("excluded --output-tensor-type is reported", (size_t) 1, count_matches(barred.log, "--output-tensor-type pins type q6_K which is ignored by --target-exclude, keeping the pinned type"));
+    t.assert_equal("excluded --token-embedding-type keeps its type", std::string("q8_0"), type_name_of(barred, "token_embd.weight"));
+    t.assert_equal("excluded --output-tensor-type keeps its type", std::string("q6_K"), type_name_of(barred, "output.weight"));
+    t.assert_equal("quantize succeeds", 0u, output_only.rc);
+    t.assert_equal("--output-tensor-type alone sets the output", std::string("q6_K"), type_name_of(output_only, "output.weight"));
+    t.assert_equal("--output-tensor-type alone pins one tensor", (size_t) 1, count_matches(output_only.log, "(pinned)"));
+}
+
+static int run_tests(testing & t, const std::filesystem::path & dir) {
+    fixture f;
+    f.fname_model = (dir / "model-f32.gguf").string();
+    f.fname_out   = (dir / "model-out.gguf").string();
+    f.fname_state = (dir / "model.bpw_state").string();
+    if (!save_model(f.fname_model)) {
+        fprintf(stderr, "failed to create the model\n");
+        return 1;
+    }
+
+    f.im = make_imatrix(f.fname_model, 1234);
+    if (f.im.names.empty()) {
+        fprintf(stderr, "failed to read the model\n");
+        return 1;
+    }
+
+    f.base = quantize(f.fname_model, f.fname_out, f.im, base_params(f));
+    if (f.base.rc != 0) {
+        fprintf(stderr, "the first quantization failed:\n%s", f.base.log.c_str());
+        return 1;
+    }
+
+    t.test("target_bpw",           [&](testing & t) { test_target_bpw(t, f); });
+    t.test("target_size",          [&](testing & t) { test_target_size(t, f); });
+    t.test("state_checkpoint",     [&](testing & t) { test_state_checkpoint(t, f); });
+    t.test("excluded_type",        [&](testing & t) { test_excluded_type(t, f); });
+    t.test("unknown_type",         [&](testing & t) { test_unknown_type(t, f); });
+    t.test("zero_candidates",      [&](testing & t) { test_zero_candidates(t, f); });
+    t.test("truncated",            [&](testing & t) { test_truncated(t, f); });
+    t.test("missing_dir",          [&](testing & t) { test_missing_dir(t, f); });
+    t.test("unreadable_file",      [&](testing & t) { test_unreadable_file(t, f); });
+    t.test("directory_path",       [&](testing & t) { test_directory_path(t, f); });
+    t.test("save_error",           [&](testing & t) { test_save_error(t, f); });
+    t.test("imatrix_swap",         [&](testing & t) { test_imatrix_swap(t, f); });
+    t.test("imatrix_parts",        [&](testing & t) { test_imatrix_parts(t, f); });
+    t.test("imatrix_order",        [&](testing & t) { test_imatrix_order(t, f); });
+    t.test("pruned_layer",         [&](testing & t) { test_pruned_layer(t, f); });
+    t.test("stats_order",          [&](testing & t) { test_stats_order(t, f); });
+    t.test("stats_missing",        [&](testing & t) { test_stats_missing(t, f); });
+    t.test("abort_callback",       [&](testing & t) { test_abort_callback(t, f); });
+    t.test("interrupt_first_call", [&](testing & t) { test_interrupt_first_call(t, f); });
+    t.test("signal_handlers",      [&](testing & t) { test_signal_handlers(t, f); });
+    t.test("type_flags",           [&](testing & t) { test_type_flags(t, f); });
+
+    return t.summary();
+}
+
+int main(int argc, char ** argv) {
+    testing t;
+
+    const char * env = getenv("LLAMA_TEST_VERBOSE");
+    verbose = env && std::string(env) == "1";
+    t.verbose = verbose;
+    llama_log_set(log_callback, nullptr);
+
+    if (argc > 1) { t.set_filter(argv[1]); }
+
+    llama_backend_init();
+    const std::filesystem::path dir = std::filesystem::temp_directory_path() / ("test-quantize-target-" + std::to_string(std::random_device{}()));
+    std::filesystem::create_directories(dir);
+    const int ret = run_tests(t, dir);
+    std::filesystem::remove_all(dir);
+    llama_backend_free();
+
+    return ret;
+}
diff --git a/tools/quantize/README.md b/tools/quantize/README.md
index 27384bebf..3d5cb72ce 100644
--- a/tools/quantize/README.md
+++ b/tools/quantize/README.md
@@ -60,11 +60,19 @@ Options:
 * `--output-tensor-type` use a specific quant type for the output.weight tensor
 * `--token-embedding-type` use a specific quant type for the token embeddings tensor
 * `--keep-split` generate the quantized model in the same shards as the input file instead of a single quantized file
+* `--dry-run` simulate the quantization process
+* `--max-buffer-size MiB` cap 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-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times.
+* `--tensor-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times
 * `--prune-layers` prune (remove) the layers in the list
-* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times.
+* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times
+* `--target-bpw` automatically choose quant types to meet an overall bits per weight (bpw) target
+* `--target-size` automatically choose quant types to meet a file size target
+* `--state-file` file 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-exclude` comma-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

@@ -92,6 +100,16 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf
 ./llama-quantize input-model-f32.gguf q4_k_m 8
 ```

+```bash
+# simulate naive Q4_K_M quantization process. No model will be generated
+./llama-quantize --dry-run input-model-f32.gguf q4_k_m 8
+```
+
+```bash
+# 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
+```
+
 ```bash
 #  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
@@ -122,59 +140,69 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf
 ./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
 ```

+```bash
+# 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
+```
+
+```bash
+# 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
+```
+
+```bash
+# 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
+```
+
+```bash
+# 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](https://huggingface.co/meta-llama/Llama-3.1-8B)

-| Measure                     | IQ1_S        | IQ1_M        | IQ2_XXS      | IQ2_XS        | IQ2_S         | IQ2_M        |
-| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ |
-| bits/weight                 |       2.0042 |       2.1460 |       2.3824 |        2.5882 |        2.7403 |       2.9294 |
-| size (GiB)                  |       1.87   |       2.01   |       2.23   |        2.42   |        2.56   |       2.74   |
-| prompt processing t/s @ 512 | 858.88 ±1.22 | 847.99 ±0.47 | 852.39 ±0.85 | 826.99 ±12.51 | 783.55 ±13.73 | 787.68 ±7.00 |
-| text generation t/s @ 128   |  79.73 ±0.79 |  72.92 ±0.14 |  79.86 ±0.22 |  78.04 ±0.46  |  77.30 ±2.47  |  74.44 ±0.15 |
-
-| Measure                     | IQ3_XXS      | IQ3_XS       | IQ3_S        | IQ3_M         | IQ4_XS        | IQ4_NL       |
-| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ |
-| bits/weight                 |       3.2548 |       3.4977 |       3.6606 |        3.7628 |        4.4597 |       4.6818 |
-| size (GiB)                  |       3.04   |       3.27   |       3.42   |        3.52   |        4.17   |       4.38   |
-| prompt processing t/s @ 512 | 813.88 ±6.53 | 708.71 ±1.26 | 798.78 ±8.81 | 768.70 ±13.73 | 771.80 ±11.38 | 806.03 ±7.07 |
-| text generation t/s @ 128   |  73.95 ±0.20 |  71.67 ±0.54 |  69.31 ±0.63 |  70.15 ±0.33  |  77.51 ±0.20  |  76.63 ±0.28 |
-
-
-| Measure                     | Q2_K_S       | Q2_K         | Q3_K_S       | Q3_K_M       | Q3_K_L       | Q4_K_S       |
-| --------------------------- | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
-| bits/weight                 |       2.9697 |       3.1593 |       3.6429 |       3.9960 |       4.2979 |       4.6672 |
-| size (GiB)                  |       2.78   |       2.95   |       3.41   |       3.74   |       4.02   |       4.36   |
-| prompt processing t/s @ 512 | 798.91 ±6.40 | 784.45 ±7.85 | 752.17 ±7.94 | 783.44 ±9.92 | 761.17 ±7.55 | 818.55 ±9.58 |
-| text generation t/s @ 128   |  90.01 ±0.12 |  79.85 ±0.20 |  69.84 ±0.18 |  71.68 ±0.22 |  69.38 ±0.49 |  76.71 ±0.20 |
-
-| Measure                     | Q4_K_S       | Q4_K_M        | Q5_K_S       | Q5_K_M       | Q6_K          | Q8_0         |
-| --------------------------- | ------------ | ------------- | ------------ | ------------ | ------------- | ------------ |
-| bits/weight                 |       4.6672 |        4.8944 |       5.5704 |       5.7036 |        6.5633 |       8.5008 |
-| size (GiB)                  |       4.36   |        4.58   |       5.21   |       5.33   |        6.14   |       7.95   |
-| prompt processing t/s @ 512 | 818.55 ±9.58 | 821.81 ±21.44 | 752.52 ±0.99 | 758.69 ±7.43 | 812.01 ±10.82 | 865.09 ±8.30 |
-| text generation t/s @ 128   |  76.71 ±0.20 |  71.93 ±1.52  |  69.53 ±0.18 |  67.23 ±1.08 |  58.67 ±3.13  |  50.93 ±0.08 |
-
-| Measure                     | F16          |
-| --------------------------- | ------------ |
-| bits/weight                 |      16.0005 |
-| size (GiB)                  |      14.96   |
-| prompt processing t/s @ 512 | 923.49 ±0.53 |
-| text generation t/s @ 128   |  29.17 ±0.04 |
+| 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

@@ -194,3 +222,4 @@ Several quantization methods are supported. They differ in the resulting model d
   - [#5060 - Q3_K_XS](https://github.com/ggml-org/llama.cpp/pull/5060)
   - [#5196 - 3-bit i-quants](https://github.com/ggml-org/llama.cpp/pull/5196)
   - [quantization tuning](https://github.com/ggml-org/llama.cpp/pull/5320), [another one](https://github.com/ggml-org/llama.cpp/pull/5334), and [another one](https://github.com/ggml-org/llama.cpp/pull/5361)
+- [target bpw/size](https://github.com/ggml-org/llama.cpp/pull/15550)
diff --git a/tools/quantize/quantize.cpp b/tools/quantize/quantize.cpp
index 0debcfdda..d58695196 100644
--- a/tools/quantize/quantize.cpp
+++ b/tools/quantize/quantize.cpp
@@ -1,24 +1,24 @@
-#include "llama.h"
-
 #include "build-info.h"
 #include "common.h"
 #include "imatrix-loader.h"

-#include "gguf.h"
-
-#include <algorithm>
-#include <cctype>
-#include <clocale>
+#include <atomic>
 #include <cmath>
-#include <cstdio>
+#include <cstdlib>
 #include <cstring>
-#include <vector>
-#include <string>
-#include <unordered_map>
-#include <fstream>
 #include <filesystem>
+#include <fstream>
+#include <signal.h>
+#include <unordered_map>
+
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#ifndef NOMINMAX
+#   define NOMINMAX
+#endif
+#include <windows.h>
+#endif

-// result of parsing --tensor-type option
 // changes to this struct must also be reflected in src/llama-quant.cpp
 struct tensor_type_option {
     std::string name;
@@ -121,8 +121,8 @@ static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftyp
 [[noreturn]]
 static void usage(const char * executable) {
     printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights]\n", executable);
-    printf("       [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file]\n");
-    printf("       [--prune-layers] [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size]\n");
+    printf("       [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file] [--prune-layers]\n");
+    printf("       [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size] [--target-bpw] [--target-size] [--target-exclude] [--state-file]\n");
     printf("       model-f32.gguf [model-quant.gguf] type [nthreads]\n\n");
     printf("  --allow-requantize\n");
     printf("                                      allow requantizing tensors that have already been quantized\n");
@@ -145,7 +145,7 @@ static void usage(const char * executable) {
     printf("                                      use this ggml_type for the token embeddings tensor\n");
     printf("  --tensor-type tensor_name=ggml_type\n");
     printf("                                      quantize this tensor to this ggml_type\n");
-    printf("                                      this is an advanced option to selectively quantize tensors. may be specified multiple times.\n");
+    printf("                                      this is an advanced option to selectively quantize tensors; may be specified multiple times.\n");
     printf("                                      example: --tensor-type attn_q=q8_0\n");
     printf("  --tensor-type-file tensor_types.txt\n");
     printf("                                      list of tensors to quantize to a specific ggml_type\n");
@@ -157,7 +157,7 @@ static void usage(const char * executable) {
     printf("  --keep-split\n");
     printf("                                      generate quantized model in the same shards as input\n");
     printf("  --override-kv KEY=TYPE:VALUE\n");
-    printf("                                      override model metadata by key in the quantized model. may be specified multiple times.\n");
+    printf("                                      override model metadata by key in the quantized model; may be specified multiple times.\n");
     printf("                                      WARNING: this is an advanced option, use with care.\n");
     printf("  --dry-run\n");
     printf("                                      calculate and show the final quantization size without performing quantization\n");
@@ -165,7 +165,21 @@ static void usage(const char * executable) {
     printf("  --max-buffer-size MiB\n");
     printf("                                      max amount of tensor rows kept in memory while quantizing one tensor (default: 8192)\n");
     printf("                                      lower it to quantize models with very large tensors on a machine with little RAM\n\n");
-    printf("note: --include-weights and --exclude-weights cannot be used together\n\n");
+    printf("  --target-bpw n\n");
+    printf("                                      target a bits per weight (bpw); must be a number between 0.0 and 16.0, 0 means the smallest possible model\n");
+    printf("                                      advanced option to automatically select quantization types to achieve a total bits per weight (bpw) target\n\n");
+    printf("  --target-size n\n");
+    printf("                                      target a file size; must be 0 or more, 0 means the smallest possible model\n");
+    printf("                                      advanced option to automatically select quantization types to achieve a total file size\n");
+    printf("                                      allowed units: b, k|kib, m|mib, g|gib, t|tib; defaults to b (bytes) if none is provided\n\n");
+    printf("  --state-file [filename]\n");
+    printf("                                      file name to use/save; if none is provided, the default name will be used\n\n");
+    printf("  --target-exclude type[,type...]\n");
+    printf("                                      comma-separated ggml_type (names or ordinals) that automatic quant type selection must ignore\n");
+    printf("                                      advanced option for --target-bpw/--target-size; may be specified multiple times\n\n");
+    printf("note: --include-weights and --exclude-weights cannot be used together\n");
+    printf("      --target-bpw and --target-size cannot be used together\n");
+    printf("      --exclude-weights excludes tensor NAMES, while --target-exclude excludes quant TYPES\n\n");
     printf("-----------------------------------------------------------------------------\n");
     printf(" allowed quantization types\n");
     printf("-----------------------------------------------------------------------------\n\n");
@@ -180,7 +194,13 @@ static void usage(const char * executable) {
     exit(1);
 }

-static int load_imatrix(const std::string & imatrix_file, std::vector<std::string> & imatrix_datasets, std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
+static int load_imatrix(const std::string & imatrix_file,
+    std::vector<std::string> & imatrix_datasets,
+    std::unordered_map<std::string, std::vector<float>> & values_data,
+    std::unordered_map<std::string, std::vector<float>> & activations_data,
+    std::unordered_map<std::string, std::vector<float>> & statistics_data,
+    std::vector<std::string> & statistics_schema)
+{
     common_imatrix loaded;
     if (!common_imatrix_load(imatrix_file, loaded)) {
         fprintf(stderr, "%s: failed to load imatrix from '%s'\n", __func__, imatrix_file.c_str());
@@ -193,59 +213,84 @@ static int load_imatrix(const std::string & imatrix_file, std::vector<std::strin
     }

     for (const auto & [name, entry] : loaded.entries) {
-        auto & e = imatrix_data[name];
-        e.resize(entry.sums.size());
+        const int64_t ncounts = (int64_t) entry.counts.size();
+        if (ncounts == 0) {
+            fprintf(stderr, "%s: no counts for entry '%s', skipping\n", __func__, name.c_str());
+            continue;
+        }

-        if (!loaded.is_legacy) {
-            // GGUF format: normalize by per-expert counts
-            const int64_t ncounts = entry.counts.size();
-            const int64_t ne0     = (int64_t) entry.sums.size() / ncounts;
+        const int64_t nsums = (int64_t) entry.sums.size();
+        if (nsums == 0) {
+            continue;
+        }
+        const int64_t ne0 = nsums / ncounts;

+        auto & values = values_data[name];
+        values.resize(nsums);
+
+        if (!loaded.is_legacy) {
             for (int64_t j = 0; j < ncounts; ++j) {
                 const float count = (float) entry.counts[j];
                 if (count > 0.0f) {
                     for (int64_t i = 0; i < ne0; ++i) {
-                        e[j*ne0 + i] = entry.sums[j*ne0 + i] / count;
+                        values[j*ne0 + i] = entry.sums[j*ne0 + i] / count;
                     }
                 } else {
                     for (int64_t i = 0; i < ne0; ++i) {
-                        e[j*ne0 + i] = 1;
+                        values[j*ne0 + i] = 1;
                     }
                 }
             }
+        } else {
+            const int64_t ncall = entry.counts[0];
+            if (ncall > 0) {
+                for (int64_t i = 0; i < nsums; ++i) {
+                    values[i] = entry.sums[i] / ncall;
+                }
+            } else {
+                for (int64_t i = 0; i < nsums; ++i) {
+                    values[i] = entry.sums[i];
+                }
+            }
+        }

-            if (getenv("LLAMA_TRACE")) {
-                float max_count = 0.0f;
+        if (!entry.activations.empty()) {
+            auto & activations = activations_data[name];
+            activations.resize(entry.activations.size());
+            if (!loaded.is_legacy) {
                 for (int64_t j = 0; j < ncounts; ++j) {
                     const float count = (float) entry.counts[j];
-                    if (count > max_count) {
-                        max_count = count;
+                    if (count > 0.0f) {
+                        for (int64_t i = 0; i < ne0; ++i) {
+                            activations[j*ne0 + i] = entry.activations[j*ne0 + i] / count;
+                        }
+                    } else {
+                        for (int64_t i = 0; i < ne0; ++i) {
+                            activations[j*ne0 + i] = 0;
+                        }
                     }
                 }
-                printf("%s: loaded data (size = %6d, n_tokens = %6d, n_chunks = %6d) for '%s'\n",
-                       __func__, int(e.size()), int(max_count), int(max_count / loaded.chunk_size), name.c_str());
-            }
-        } else {
-            // Legacy format: sums contain (raw/count)*ncall, divide by ncall
-            const int64_t ncall = entry.counts.empty() ? 0 : entry.counts[0];
-            if (ncall > 0) {
-                for (size_t i = 0; i < entry.sums.size(); ++i) {
-                    e[i] = entry.sums[i] / ncall;
-                }
             } else {
-                for (size_t i = 0; i < entry.sums.size(); ++i) {
-                    e[i] = entry.sums[i];
+                const int64_t ncall = entry.counts[0];
+                if (ncall > 0) {
+                    for (size_t i = 0; i < entry.activations.size(); ++i) {
+                        activations[i] = entry.activations[i] / ncall;
+                    }
+                } else {
+                    for (size_t i = 0; i < entry.activations.size(); ++i) {
+                        activations[i] = entry.activations[i];
+                    }
                 }
             }
+        }

-            if (getenv("LLAMA_TRACE")) {
-                printf("%s: loaded data (size = %6d, ncall = %6d) for '%s'\n",
-                       __func__, int(e.size()), int(ncall), name.c_str());
-            }
+        if (!entry.stats.empty()) {
+            statistics_data[name] = entry.stats;
         }
     }

     imatrix_datasets = std::move(loaded.datasets);
+    statistics_schema = std::move(loaded.stats_schema);

     if (!imatrix_datasets.empty()) {
         printf("%s: imatrix datasets=['%s'", __func__, imatrix_datasets[0].c_str());
@@ -255,7 +300,7 @@ static int load_imatrix(const std::string & imatrix_file, std::vector<std::strin
         printf("]\n");
     }

-    printf("%s: loaded %d importance matrix entries from %s computed on %d chunks\n", __func__, int(imatrix_data.size()), imatrix_file.c_str(), loaded.chunk_count);
+    printf("%s: loaded %d importance matrix entries from %s computed on %d chunks\n", __func__, int(values_data.size()), imatrix_file.c_str(), loaded.chunk_count);

     return loaded.chunk_count;
 }
@@ -264,41 +309,74 @@ static int prepare_imatrix(const std::string & imatrix_file,
         std::vector<std::string> & imatrix_dataset,
         const std::vector<std::string> & included_weights,
         const std::vector<std::string> & excluded_weights,
-        std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
+        std::unordered_map<std::string, std::vector<float>> & values_data,
+        std::unordered_map<std::string, std::vector<float>> & activations_data,
+        std::unordered_map<std::string, std::vector<float>> & statistics_data,
+        std::vector<std::string> & stats_schema) {
     int m_last_call = -1;
     if (!imatrix_file.empty()) {
-        m_last_call = load_imatrix(imatrix_file, imatrix_dataset, imatrix_data);
+        m_last_call = load_imatrix(imatrix_file, imatrix_dataset, values_data, activations_data, statistics_data, stats_schema);
     }
-    if (imatrix_data.empty()) {
+    if (values_data.empty()) {
         return m_last_call;
     }
     if (!excluded_weights.empty()) {
         for (const auto & name : excluded_weights) {
-            for (auto it = imatrix_data.begin(); it != imatrix_data.end();) {
-                auto pos = it->first.find(name);
+            for (auto vt = values_data.begin(); vt != values_data.end();) {
+                auto pos = vt->first.find(name);
+                if (pos != std::string::npos) {
+                    vt = values_data.erase(vt);
+                } else {
+                    ++vt;
+                }
+            }
+            for (auto at = activations_data.begin(); at != activations_data.end();) {
+                auto pos = at->first.find(name);
+                if (pos != std::string::npos) {
+                    at = activations_data.erase(at);
+                } else {
+                    ++at;
+                }
+            }
+            for (auto st = statistics_data.begin(); st != statistics_data.end();) {
+                auto pos = st->first.find(name);
                 if (pos != std::string::npos) {
-                    it = imatrix_data.erase(it);
+                    st = statistics_data.erase(st);
                 } else {
-                    ++it;
+                    ++st;
                 }
             }
         }
     }
     if (!included_weights.empty()) {
-        std::unordered_map<std::string, std::vector<float>> tmp;
+        std::unordered_map<std::string, std::vector<float>> tmp_values;
+        std::unordered_map<std::string, std::vector<float>> tmp_activations;
+        std::unordered_map<std::string, std::vector<float>> tmp_statistics;
         for (const auto & name : included_weights) {
-            for (auto & e : imatrix_data) {
+            for (auto & e : values_data) {
                 auto pos = e.first.find(name);
                 if (pos != std::string::npos) {
-                    tmp.emplace(std::move(e));
+                    tmp_values.emplace(std::move(e));
+                }
+            }
+            for (auto & a : activations_data) {
+                auto pos = a.first.find(name);
+                if (pos != std::string::npos) {
+                    tmp_activations.emplace(std::move(a));
+                }
+            }
+            for (auto & s : statistics_data) {
+                auto pos = s.first.find(name);
+                if (pos != std::string::npos) {
+                    tmp_statistics.emplace(std::move(s));
                 }
             }
         }
-        imatrix_data = std::move(tmp);
-    }
-    if (!imatrix_data.empty()) {
-        printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size()));
+        values_data = std::move(tmp_values);
+        activations_data = std::move(tmp_activations);
+        statistics_data = std::move(tmp_statistics);
     }
+
     return m_last_call;
 }

@@ -389,6 +467,139 @@ static bool parse_layer_prune(const char * data, std::vector<int> & prune_layers
     return true;
 }

+static bool parse_target_bpw(const char * data, float & target_bpw) {
+    if (!data) {
+        printf("\n%s: no target bits per weight (bpw) provided\n\n", __func__);
+        return false;
+    }
+
+    try {
+        target_bpw = std::stof(data);
+        if (!std::isfinite(target_bpw) || target_bpw < 0.0f || target_bpw > 16.0f) {
+            printf("\n%s: target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__);
+            return false;
+        }
+    }
+    catch (const std::exception & e) {
+        printf("\n%s: '%s' is not valid. Target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__, data);
+        return false;
+    }
+
+    return true;
+}
+
+static bool parse_target_size(const char * data, int64_t & target_size) {
+    if (!data) {
+        printf("\n%s: no target file size provided\n\n", __func__);
+        return false;
+    }
+
+    char * end = nullptr;
+    const double val = std::strtod(data, &end);
+    if (end == data || !std::isfinite(val) || val < 0) {
+        printf("\n%s: invalid target file size '%s'\n\n", __func__, data);
+        return false;
+    }
+
+    std::string suffix(end);
+    for (auto & c : suffix) { c = std::tolower(c); }
+
+    int64_t mul = 0;
+    if (suffix.empty() || suffix == "b") {
+        mul = 1;
+    } else if (suffix == "k" || suffix == "kib") {
+        mul = 1024;
+    } else if (suffix == "m" || suffix == "mib") {
+        mul = 1024 * 1024;
+    } else if (suffix == "g" || suffix == "gib") {
+        mul = 1024 * 1024 * 1024;
+    } else if (suffix == "t" || suffix == "tib") {
+        mul = 1024LL * 1024 * 1024 * 1024;
+    } else {
+        printf("\n%s: invalid unit '%s' in '%s'. Allowed: b, k or kib, m or mib, g or gib, t or tib\n\n", __func__, suffix.c_str(), data);
+        return false;
+    }
+
+    if (val * mul >= (double)INT64_MAX) {
+        printf("\n%s: invalid target file size '%s'\n\n", __func__, data);
+        return false;
+    }
+
+    target_size = (int64_t)(val * mul);
+    return true;
+}
+
+static bool parse_target_exclude(const char * data, std::vector<ggml_type> & target_exclude) {
+    if (!data) {
+        printf("\n%s: no quant types provided\n\n", __func__);
+        return false;
+    }
+
+    const auto tokens = string_split<std::string>(data, ',');
+    for (const auto & token : tokens) {
+        ggml_type type = GGML_TYPE_COUNT;
+        for (int i = 0; i < GGML_TYPE_COUNT; ++i) {
+            const char * name = ggml_type_name((ggml_type)i);
+            if (name && striequals(name, token.c_str())) {
+                type = (ggml_type)i;
+                break;
+            }
+        }
+
+        if (type == GGML_TYPE_COUNT) {
+            const bool numeric = !token.empty() && std::all_of(token.begin(), token.end(), [](unsigned char c) { return std::isdigit(c); });
+            const long ordinal = numeric ? std::strtol(token.c_str(), nullptr, 10) : -1;
+            if (ordinal >= 0 && ordinal < GGML_TYPE_COUNT) {
+                type = (ggml_type)ordinal;
+            }
+        }
+
+        if (type == GGML_TYPE_COUNT) {
+            printf("\n%s: invalid quant type '%s' for --target-exclude\n\n", __func__, token.c_str());
+            return false;
+        }
+
+        if (std::find(target_exclude.begin(), target_exclude.end(), type) == target_exclude.end()) {
+            target_exclude.emplace_back(type);
+        }
+    }
+
+    return true;
+}
+
+static const char * get_ftype(const float bpw) {
+    const std::map<float, const char *> quant_bpw = {
+        {1.5625, "IQ1_S"},
+        {1.7500, "IQ1_M"},
+        {2.0625, "IQ2_XXS"},
+        {2.3125, "IQ2_XS"},
+        {2.5625, "IQ2_S"},
+        {2.6250, "Q2_K"},
+        {3.0625, "IQ3_XXS"},
+        {3.4375, "Q3_K"},
+        {4.2500, "IQ4_XS"},
+        {4.5000, "Q4_K"},
+        {5.5000, "Q5_K"},
+        {6.5625, "Q6_K"},
+        {8.5000, "Q8_0"},
+        {16.0000, "F16"}
+    };
+
+    return quant_bpw.lower_bound(bpw)->second;
+}
+
+static std::atomic<int> interrupt_signal{ 0 };
+
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
+// try to save the state checkpoint if interrupted while scoring
+static void signal_handler(int signo) {
+    int expected = 0;
+    interrupt_signal.compare_exchange_strong(expected, signo);
+}
+#endif
+
+static bool is_interrupted(void * /*data*/) { return interrupt_signal.load() != 0; }
+
 // satisfies -Wmissing-declarations
 int llama_quantize(int argc, char ** argv);

@@ -402,10 +613,14 @@ int llama_quantize(int argc, char ** argv) {

     int arg_idx = 1;
     std::string imatrix_file;
-    std::vector<std::string> included_weights, excluded_weights;
+    std::vector<std::string> included_weights;
+    std::vector<std::string> excluded_weights;
     std::vector<llama_model_kv_override> kv_overrides;
     std::vector<tensor_type_option> tensor_type_opts;
     std::vector<int> prune_layers;
+    std::vector<ggml_type> target_exclude;
+    float target_bpw = -1.0f;
+    int64_t target_size = -1;

     for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
         if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) {
@@ -436,6 +651,25 @@ int llama_quantize(int argc, char ** argv) {
             if (arg_idx == argc-1 || !parse_tensor_type_file(argv[++arg_idx], tensor_type_opts)) {
                 usage(argv[0]);
             }
+        } else if (strcmp(argv[arg_idx], "--target-bpw") == 0) {
+            if (arg_idx == argc-1 || !parse_target_bpw(argv[++arg_idx], target_bpw)) {
+                usage(argv[0]);
+            }
+        } else if (strcmp(argv[arg_idx], "--target-size") == 0) {
+            if (arg_idx == argc-1 || !parse_target_size(argv[++arg_idx], target_size)) {
+                usage(argv[0]);
+            }
+        } else if (strcmp(argv[arg_idx], "--target-exclude") == 0) {
+            if (arg_idx == argc-1 || !parse_target_exclude(argv[++arg_idx], target_exclude)) {
+                usage(argv[0]);
+            }
+        } else if (strcmp(argv[arg_idx], "--state-file") == 0) {
+            if (arg_idx + 1 < argc && argv[arg_idx + 1][0] != '-') {
+                params.state_file = argv[++arg_idx];
+            } else {
+                static char empty[] = "";
+                params.state_file = empty;
+            }
         } else if (strcmp(argv[arg_idx], "--prune-layers") == 0) {
             if (arg_idx == argc-1 || !parse_layer_prune(argv[++arg_idx], prune_layers)) {
                 usage(argv[0]);
@@ -492,20 +726,28 @@ int llama_quantize(int argc, char ** argv) {
     if (!included_weights.empty() && !excluded_weights.empty()) {
         usage(argv[0]);
     }
+    if (target_bpw != -1.0f && target_size != -1) {
+        usage(argv[0]);
+    }

     std::vector<std::string> imatrix_datasets;
-    std::unordered_map<std::string, std::vector<float>> imatrix_data;
-    int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, imatrix_data);
-
-    std::vector<llama_model_imatrix_data> i_data;
-    std::vector<llama_model_tensor_override> t_override;
-    if (!imatrix_data.empty()) {
-        i_data.reserve(imatrix_data.size() + 1);
-        for (const auto & kv : imatrix_data) {
-            i_data.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()});
-        }
-        i_data.push_back({nullptr, nullptr, 0});  // array terminator
-        params.imatrix = i_data.data();
+    std::unordered_map<std::string, std::vector<float>> values_data;
+    std::unordered_map<std::string, std::vector<float>> activations_data;
+    std::unordered_map<std::string, std::vector<float>> statistics_data;
+    std::vector<std::string> stats_schema;
+    int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, values_data, activations_data, statistics_data, stats_schema);
+
+    std::vector<llama_model_imatrix_data> vdata;
+    std::vector<llama_model_imatrix_data> adata;
+    std::vector<llama_model_imatrix_data> sdata;
+    std::vector<const char *> sschema;
+    std::vector<llama_model_tensor_override> tto;
+
+    if (!values_data.empty()) {
+        vdata.reserve(values_data.size() + 1);
+        for (const auto & kv : values_data) { vdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); }
+        vdata.push_back({nullptr, nullptr, 0});  // array terminator
+        params.imatrix = vdata.data();
         {
             llama_model_kv_override kvo;
             std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE);
@@ -529,7 +771,7 @@ int llama_quantize(int argc, char ** argv) {
             llama_model_kv_override kvo;
             std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES);
             kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
-            kvo.val_i64 = imatrix_data.size();
+            kvo.val_i64 = values_data.size();
             kv_overrides.emplace_back(std::move(kvo));
         }
         if (m_last_call > 0) {
@@ -540,23 +782,47 @@ int llama_quantize(int argc, char ** argv) {
             kv_overrides.emplace_back(std::move(kvo));
         }
     }
+    if (!activations_data.empty()) {
+        adata.reserve(activations_data.size() + 1);
+        for (const auto & kv : activations_data) { adata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); }
+        adata.push_back({nullptr, nullptr, 0});  // array terminator
+        params.activations = adata.data();
+    }
+    if (!statistics_data.empty()) {
+        sdata.reserve(statistics_data.size() + 1);
+        for (const auto & kv : statistics_data) { sdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); }
+        sdata.push_back({nullptr, nullptr, 0});  // array terminator
+        params.statistics = sdata.data();
+        sschema.reserve(stats_schema.size() + 1);
+        for (const auto & name : stats_schema) { sschema.push_back(name.c_str()); }
+        sschema.push_back(nullptr);  // array terminator
+        params.stats_schema = sschema.data();
+    }
     if (!kv_overrides.empty()) {
         kv_overrides.emplace_back();
         kv_overrides.back().key[0] = 0;
         params.kv_overrides = kv_overrides.data();
     }
     if (!tensor_type_opts.empty()) {
-        t_override.reserve(tensor_type_opts.size() + 1);
-        for (const auto & tt : tensor_type_opts) {
-            t_override.push_back({tt.name.c_str(), tt.type});
-        }
-        t_override.push_back({nullptr, GGML_TYPE_COUNT});  // array terminator
-        params.tt_overrides = t_override.data();
+        tto.reserve(tensor_type_opts.size() + 1);
+        for (const auto & tt : tensor_type_opts) { tto.push_back({tt.name.c_str(), tt.type}); }
+        tto.push_back({nullptr, GGML_TYPE_COUNT});  // array terminator
+        params.tt_overrides = tto.data();
+    }
+    if (!target_exclude.empty()) {
+        target_exclude.push_back(GGML_TYPE_COUNT);  // array terminator
+        params.target_exclude = target_exclude.data();
     }
     if (!prune_layers.empty()) {
         prune_layers.push_back(-1);  // array terminator
         params.prune_layers = prune_layers.data();
     }
+    if (target_bpw != -1.0f) {
+        params.target_bpw = target_bpw;
+    }
+    if (target_size != -1) {
+        params.target_size = target_size;
+    }

     llama_backend_init();

@@ -567,6 +833,7 @@ int llama_quantize(int argc, char ** argv) {

     std::string ftype_str;
     std::string suffix = ".gguf";
+    std::vector<const char *> tmp_argv(argv, argv + argc);
     if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
         // argv[arg_idx] is the ftype directly: <input> <ftype>
         if (!params.dry_run) {
@@ -594,7 +861,22 @@ int llama_quantize(int argc, char ** argv) {
         }
         arg_idx++;

-        if (argc <= arg_idx) {
+        // If --target-bpw or --target-size are set, select a quantization type and ignore any user specified type
+        if (params.target_bpw != -1.0f || params.target_size != -1) {
+            auto * ftype = params.target_bpw != -1.0f ? const_cast<char *>(get_ftype(params.target_bpw)) : const_cast<char *>("F16");
+            bool added_type = false;
+            if (argc == arg_idx) {
+                tmp_argv.push_back(ftype);
+                added_type = true;
+            } else {
+                tmp_argv[arg_idx] = ftype;
+            }
+            tmp_argv.push_back(nullptr);
+            argv = const_cast<char **>(tmp_argv.data());
+            if (added_type) {
+                argc++;
+            }
+        } else if (argc <= arg_idx) {
             fprintf(stderr, "%s: missing ftype\n", __func__);
             return 1;
         }
@@ -639,6 +921,24 @@ int llama_quantize(int argc, char ** argv) {
     }
     fprintf(stderr, "\n");

+    // handle SIGINT and SIGTERM
+    {
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
+        struct sigaction sigint_action;
+        sigint_action.sa_handler = signal_handler;
+        sigemptyset(&sigint_action.sa_mask);
+        sigint_action.sa_flags = SA_RESTART;
+        sigaction(SIGINT, &sigint_action, nullptr);
+        sigaction(SIGTERM, &sigint_action, nullptr);
+#elif defined (_WIN32)
+        auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
+            return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
+        };
+        SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
+#endif
+        params.abort_callback = is_interrupted;
+    }
+
     const int64_t t_main_start_us = llama_time_us();

     int64_t t_quantize_us = 0;
@@ -649,7 +949,16 @@ int llama_quantize(int argc, char ** argv) {

         if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), &params)) {
             fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
-            return 1;
+            const int signo = interrupt_signal.load();
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
+            // ensure that a calling shell or script stops too...
+            if (signo) {
+                signal(signo, SIG_DFL);
+                raise(signo);
+            }
+#endif
+            // ...as a shell reports a process that the signal killed
+            return signo ? 128 + signo : 1;
         }

         t_quantize_us = llama_time_us() - t_start_us;