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
This commit is contained in:
Ed Addario 2026-11-23 17:06:26 +00:00 • committed by GitHub
parent 87f816e87f
commit 30ec35ae2e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 4235 additions and 700 deletions

View file

@ -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);

View file

@ -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;

View file

@ -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 {

View file

@ -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 {

File diff suppressed because it is too large Load diff

View file

@ -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)

View file

@ -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;
}

View file

@ -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)

View file

@ -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;
}
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) {
// GGUF format: normalize by per-expert counts
const int64_t ncounts = entry.counts.size();
const int64_t ne0 = (int64_t) entry.sums.size() / ncounts;
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;
}
}
}
if (getenv("LLAMA_TRACE")) {
float max_count = 0.0f;
for (int64_t j = 0; j < ncounts; ++j) {
const float count = (float) entry.counts[j];
if (count > max_count) {
max_count = count;
}
}
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];
const int64_t ncall = entry.counts[0];
if (ncall > 0) {
for (size_t i = 0; i < entry.sums.size(); ++i) {
e[i] = entry.sums[i] / ncall;
for (int64_t i = 0; i < nsums; ++i) {
values[i] = entry.sums[i] / ncall;
}
} else {
for (size_t i = 0; i < entry.sums.size(); ++i) {
e[i] = entry.sums[i];
for (int64_t i = 0; i < nsums; ++i) {
values[i] = entry.sums[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.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 > 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;
}
}
}
} else {
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 (!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) {
it = imatrix_data.erase(it);
vt = values_data.erase(vt);
} else {
++it;
++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) {
st = statistics_data.erase(st);
} else {
++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::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> 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::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;