1
0

quantize-stats.cpp 16 KB

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