quantize-stats.cpp 13 KB

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