quantize-stats.cpp 13 KB

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