KBaba7/llama.cpp
0
1#include "ggml.h"2#include "llama.h"3#include "llama-context.h"4#include "common.h"5 6#include <algorithm>7#include <cassert>8#include <cinttypes>9#include <cmath>10#include <cstdio>11#include <cstring>12#include <numeric>13#include <regex>14#include <string>15#include <vector>16#include <thread>17#include <mutex>18 19#if defined(_MSC_VER)20#pragma warning(disable: 4244 4267) // possible loss of data21#endif22 23struct quantize_stats_params {24 std::string model = DEFAULT_MODEL_PATH;25 bool verbose = false;26 bool per_layer_stats = false;27 bool print_histogram = false;28 bool reference = false;29 std::vector<std::string> include_layers;30 std::vector<std::string> exclude_layers;31 std::vector<enum ggml_type> include_types;32};33 34constexpr size_t HISTOGRAM_BUCKETS = 150;35constexpr double HISTOGRAM_RANGE = 0.03;36 37struct error_stats {38 size_t num_samples;39 double total_error;40 double max_error;41 uint64_t error_histogram[HISTOGRAM_BUCKETS];42};43 44static void quantize_stats_print_usage(int /*argc*/, char ** argv) {45 quantize_stats_params params;46 fprintf(stderr, "usage: %s [options]\n", argv[0]);47 fprintf(stderr, "\n");48 fprintf(stderr, "options:\n");49 fprintf(stderr, " -h, --help show this help message and exit\n");50 fprintf(stderr, " -m FNAME, --model FNAME\n");51 fprintf(stderr, " model path (default: %s)\n", params.model.c_str());52 fprintf(stderr, " -r, --reference\n");53 fprintf(stderr, " use reference implementation (default: false)\n");54 fprintf(stderr, " -v, --verbose\n");55 fprintf(stderr, " verbose output (default: false)\n");56 fprintf(stderr, " -p, --per-layer-stats\n");57 fprintf(stderr, " print stats per layer (default: false)\n");58 fprintf(stderr, " --histogram\n");59 fprintf(stderr, " print error histogram (default: false)\n");60 fprintf(stderr, " -l LAYER, --include-layer LAYER\n");61 fprintf(stderr, " only test layers matching pattern\n");62 fprintf(stderr, " -L LAYER, --exclude-layer LAYER\n");63 fprintf(stderr, " exclude layers matching pattern\n");64 fprintf(stderr, " -t TYPE, --type TYPE\n");65 fprintf(stderr, " only test given type (q4_0, q4_1)\n");66 fprintf(stderr, "\n");67}68 69// Check if a layer is included/excluded by command line70static bool layer_included(const quantize_stats_params & params, const std::string & layer) {71 for (const auto& excluded : params.exclude_layers) {72 if (std::regex_search(layer, std::regex(excluded))) {73 return false;74 }75 }76 for (const auto& included : params.include_layers) {77 if (std::regex_search(layer, std::regex(included))) {78 return true;79 }80 }81 return params.include_layers.empty();82}83 84// Update error statistics given vectors with the before/after result of quantization85static void update_error_stats(int64_t nelements, const float * input, const float * output, error_stats & stats) {86 for (int64_t i = 0; i < nelements; i++) {87 double diff = input[i] - output[i];88 stats.total_error += diff * diff;89 stats.max_error = fmax(fabs(diff), stats.max_error);90 stats.error_histogram[std::max(std::min((size_t) floor(fabs(diff) / HISTOGRAM_RANGE * HISTOGRAM_BUCKETS), HISTOGRAM_BUCKETS-1), (size_t) 0)]++;91 }92 stats.num_samples += nelements;93}94 95static void combine_error_stats(error_stats & into, const error_stats & from) {96 into.num_samples += from.num_samples;97 into.total_error += from.total_error;98 if (from.max_error > into.max_error) into.max_error = from.max_error;99 for (size_t i=0; i<HISTOGRAM_BUCKETS; ++i) into.error_histogram[i] += from.error_histogram[i];100}101 102static double find_quantile(const error_stats & stats, double quantile) {103 double sum = std::accumulate(std::begin(stats.error_histogram), std::end(stats.error_histogram), 0.0);104 105 double accum = 0;106 for (size_t i = 0; i < HISTOGRAM_BUCKETS; i++) {107 accum += stats.error_histogram[i];108 if (accum >= sum*quantile) {109 return (i+1) * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;110 }111 }112 return INFINITY;113}114 115static void print_error_stats(const std::string & name, const error_stats & stats, bool print_histogram) {116 double rmse = sqrt(stats.total_error / (double) stats.num_samples);117 double median = find_quantile(stats, .5);118 double pct95 = find_quantile(stats, .95);119 printf("%-50s: rmse %.8f, maxerr %.8f, 95pct<%.4f, median<%.4f\n", name.c_str(), rmse, stats.max_error, pct95, median);120 if (print_histogram) {121 printf("Error distribution:\n");122 for (size_t i = 0; i < HISTOGRAM_BUCKETS; i++) {123 double lower = i * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;124 double upper = (i+1) * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;125 if (i == HISTOGRAM_BUCKETS -1) upper = INFINITY;126 printf("[%3.4f, %3.4f): %11" PRIu64 "\n", lower, upper, stats.error_histogram[i]);127 }128 }129}130 131// copied from ggml.h - verify that we can access this as a flat array132static bool tensor_is_contiguous(const struct ggml_tensor * tensor) {133 static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");134 135 return136 tensor->nb[0] == ggml_type_size(tensor->type) &&137 tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&138 tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&139 tensor->nb[3] == tensor->nb[2]*tensor->ne[2];140}141 142static void test_roundtrip_on_chunk(143 const ggml_tensor * layer, int64_t offset, int64_t chunk_size, const ggml_type_traits & qfns, const ggml_type_traits_cpu & qfns_cpu, bool use_reference,144 float * input_scratch, char * quantized_scratch, float * output_scratch, error_stats & stats145) {146 if (layer->type == GGML_TYPE_F16) {147 for (int i = 0; i < chunk_size; i++) {148 input_scratch[i] = ggml_get_f32_1d(layer, i + offset);149 }150 } else {151 input_scratch = ggml_get_data_f32(layer) + offset;152 }153 154 if (use_reference) {155 qfns.from_float_ref(input_scratch, quantized_scratch, chunk_size);156 } else {157 qfns_cpu.from_float(input_scratch, quantized_scratch, chunk_size);158 }159 qfns.to_float(quantized_scratch, output_scratch, chunk_size);160 161 update_error_stats(chunk_size, input_scratch, output_scratch, stats);162}163 164 165// Run quantization function for a single layer and update error stats166static void test_roundtrip_on_layer(167 std::string & name, bool print_layer_stats, const ggml_type_traits & qfns, const ggml_type_traits_cpu & qfns_cpu, bool use_reference,168 const ggml_tensor * layer, std::vector<float> & input_scratch, std::vector<char> & quantized_scratch,169 std::vector<float> & output_scratch, error_stats & total_error, int max_thread = 0170) {171 assert(tensor_is_contiguous(layer));172 error_stats layer_error {};173 uint64_t nelements = ggml_nelements(layer);174 175 float* input_scratch_ptr = nullptr;176 if (layer->type == GGML_TYPE_F16) {177 if (input_scratch.size() < nelements) input_scratch.resize(nelements);178 input_scratch_ptr = input_scratch.data();179 }180 if (quantized_scratch.size() < 4*nelements) quantized_scratch.resize(4*nelements);181 if (output_scratch.size() < nelements) output_scratch.resize(nelements);182 183 if (max_thread < 1) max_thread = std::thread::hardware_concurrency();184 int chunk_size = 32*512;185 int num_chunks = (nelements + chunk_size - 1)/chunk_size;186 187 if (num_chunks < 2 || max_thread < 2) {188 test_roundtrip_on_chunk(layer, 0, nelements, qfns, qfns_cpu, use_reference, input_scratch_ptr, quantized_scratch.data(),189 output_scratch.data(), print_layer_stats ? layer_error : total_error);190 } else {191 auto & stats = print_layer_stats ? layer_error : total_error;192 std::mutex mutex;193 uint64_t counter = 0;194 auto compute = [&mutex, &counter, &stats, &qfns, &qfns_cpu, nelements, layer, use_reference, input_scratch_ptr,195 &quantized_scratch, &output_scratch, chunk_size] () {196 error_stats local_stats {};197 while (true) {198 std::unique_lock<std::mutex> lock(mutex);199 uint64_t offset = counter; counter += chunk_size;200 if (offset >= nelements) {201 combine_error_stats(stats, local_stats);202 break;203 }204 lock.unlock();205 uint64_t chunk = offset + chunk_size < nelements ? chunk_size : nelements - offset;206 test_roundtrip_on_chunk(layer, offset, chunk, qfns, qfns_cpu, use_reference, input_scratch_ptr + offset,207 quantized_scratch.data() + 4*offset, output_scratch.data() + offset, local_stats);208 }209 };210 int nthread = std::min(num_chunks, max_thread);211 std::vector<std::thread> workers(nthread-1);212 for (auto& w : workers) w = std::thread(compute);213 compute();214 for (auto& w : workers) w.join();215 }216 217 if (print_layer_stats) {218 print_error_stats(name, layer_error, false);219 combine_error_stats(total_error, layer_error);220 }221}222 223int main(int argc, char ** argv) {224 ggml_time_init();225 226 quantize_stats_params params;227 228 // read command line229 230 int max_thread = 0;231 bool invalid_param = false;232 std::string arg;233 for (int i = 1; i < argc; i++) {234 arg = argv[i];235 236 if (arg == "-h" || arg == "--help") {237 quantize_stats_print_usage(argc, argv);238 exit(0);239 } else if (arg == "-r" || arg == "--reference") {240 params.reference = true;241 } else if (arg == "-v") {242 params.verbose = true;243 } else if (arg == "-p" || arg == "--per-layer-stats") {244 params.per_layer_stats = true;245 } else if (arg == "--histogram") {246 params.print_histogram = true;247 } else if (arg == "-m" || arg == "--model") {248 if (++i >= argc) {249 invalid_param = true;250 break;251 }252 params.model = argv[i];253 } else if (arg == "-l" || arg == "--include-layer") {254 if (++i >= argc) {255 invalid_param = true;256 break;257 }258 params.include_layers.emplace_back(argv[i]);259 } else if (arg == "-L" || arg == "--exclude-layer") {260 if (++i >= argc) {261 invalid_param = true;262 break;263 }264 params.exclude_layers.emplace_back(argv[i]);265 } else if (arg == "-t" || arg == "--type") {266 if (++i >= argc) {267 invalid_param = true;268 break;269 }270 int j;271 for (j = 0; j < GGML_TYPE_COUNT; ++j) {272 const auto * name = ggml_type_name((ggml_type) j);273 if (name && strcmp(argv[i], name) == 0) break;274 }275 if (j < GGML_TYPE_COUNT) {276 params.include_types.push_back((ggml_type) j);277 } else {278 fprintf(stderr, "error: %s not in list of types\n", argv[i]);279 invalid_param = true;280 }281 } else if (arg == "-n" || arg == "--num-threads") {282 if (++i >= argc) {283 invalid_param = true;284 break;285 }286 max_thread = atoi(argv[i]);287 } else {288 fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());289 quantize_stats_print_usage(argc, argv);290 return 1;291 }292 }293 if (invalid_param) {294 fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());295 quantize_stats_print_usage(argc, argv);296 return 1;297 }298 299 print_build_info();300 301 // load the model302 fprintf(stderr, "Loading model\n");303 304 const int64_t t_main_start_us = ggml_time_us();305 llama_model * model;306 llama_context * ctx;307 308 {309 auto mparams = llama_model_default_params();310 mparams.use_mlock = false;311 312 model = llama_model_load_from_file(params.model.c_str(), mparams);313 314 if (model == NULL) {315 fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());316 return 1;317 }318 319 auto cparams = llama_context_default_params();320 cparams.n_ctx = 256;321 322 ctx = llama_init_from_model(model, cparams);323 324 if (ctx == NULL) {325 fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());326 llama_model_free(model);327 return 1;328 }329 }330 331 const auto & tensors = llama_internal_get_tensor_map(ctx);332 333 // check layer tensors334 int included_layers = 0;335 int64_t max_nelements = 0;336 bool is_f16 = false;337 for (const auto & kv_tensor : tensors) {338 if (!layer_included(params, kv_tensor.first)) {339 continue;340 }341 if (params.verbose) {342 printf("%s: type %s, size %" PRId64 "\n", kv_tensor.first.c_str(), ggml_type_name(kv_tensor.second->type), ggml_nelements(kv_tensor.second));343 }344 if (kv_tensor.second->type == GGML_TYPE_F16) {345 is_f16 = true;346 } else if (kv_tensor.second->type != GGML_TYPE_F32) {347 fprintf(stderr, "%s: error: Quantization should be tested with a float model, "348 "this model contains already quantized layers (%s is type %d)\n", __func__, kv_tensor.first.c_str(), kv_tensor.second->type);349 llama_free(ctx);350 llama_model_free(model);351 return 1;352 }353 included_layers++;354 max_nelements = std::max(max_nelements, ggml_nelements(kv_tensor.second));355 }356 357 if (is_f16) {358 printf("note: source model is f16\n");359 }360 printf("testing %d layers with max size %" PRId64 "\n", included_layers, max_nelements);361 // allocate scratch space362 std::vector<float> input_scratch;363 std::vector<char> quantized_scratch;364 std::vector<float> output_scratch;365 366 // loop throught quantization types367 for (int i = 0; i < GGML_TYPE_COUNT; i++) {368 const ggml_type type = (ggml_type) i;369 if (!params.include_types.empty() && std::find(params.include_types.begin(), params.include_types.end(), i) == params.include_types.end()) {370 continue;371 }372 const auto * qfns = ggml_get_type_traits(type);373 const auto * qfns_cpu = ggml_get_type_traits_cpu(type);374 if (qfns_cpu->from_float && qfns->to_float) {375 if (params.verbose) {376 printf("testing %s ...\n", ggml_type_name(type));377 }378 379 ggml_quantize_init(type);380 381 error_stats global_stats {};382 383 for (const auto & kv_tensor : tensors) {384 if (!layer_included(params, kv_tensor.first)) {385 continue;386 }387 if (params.verbose) {388 printf(" %s ...\n", kv_tensor.first.c_str());389 }390 std::string layer_name { ggml_type_name(type) };391 layer_name += "::" + kv_tensor.first;392 test_roundtrip_on_layer(393 layer_name,394 params.per_layer_stats,395 *qfns, *qfns_cpu,396 params.reference,397 kv_tensor.second,398 input_scratch,399 quantized_scratch,400 output_scratch,401 global_stats,402 max_thread403 );404 }405 406 print_error_stats(ggml_type_name(type), global_stats, params.print_histogram);407 }408 }409 410 411 llama_free(ctx);412 llama_model_free(model);413 // report timing414 {415 const int64_t t_main_end_us = ggml_time_us();416 417 printf("\n");418 printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);419 }420 421 return 0;422}423 