quantize-stats.cpp 16 KB

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