quantize-stats.cpp 13 KB

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