quantize-stats.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. #include "ggml.h"
  2. #include "build-info.h"
  3. #define LLAMA_API_INTERNAL
  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. struct quantize_stats_params {
  20. std::string model = "models/7B/ggml-model-f16.bin";
  21. bool verbose = false;
  22. bool per_layer_stats = false;
  23. bool print_histogram = false;
  24. bool reference = false;
  25. std::vector<std::string> include_layers;
  26. std::vector<std::string> exclude_layers;
  27. std::vector<enum ggml_type> include_types;
  28. };
  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. void combine_error_stats(error_stats & into, const error_stats & from) {
  86. into.num_samples += from.num_samples;
  87. into.total_error += from.total_error;
  88. if (from.max_error > into.max_error) into.max_error = from.max_error;
  89. for (size_t i=0; i<HISTOGRAM_BUCKETS; ++i) into.error_histogram[i] += from.error_histogram[i];
  90. }
  91. double find_quantile(const error_stats & stats, double quantile) {
  92. double sum = std::accumulate(std::begin(stats.error_histogram), std::end(stats.error_histogram), 0.0);
  93. double accum = 0;
  94. for (size_t i = 0; i < HISTOGRAM_BUCKETS; i++) {
  95. accum += stats.error_histogram[i];
  96. if (accum >= sum*quantile) {
  97. return (i+1) * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;
  98. }
  99. }
  100. return INFINITY;
  101. }
  102. void print_error_stats(const std::string & name, const error_stats & stats, bool print_histogram) {
  103. double rmse = sqrt(stats.total_error / (double) stats.num_samples);
  104. double median = find_quantile(stats, .5);
  105. double pct95 = find_quantile(stats, .95);
  106. printf("%-50s: rmse %.8f, maxerr %.8f, 95pct<%.4f, median<%.4f\n", name.c_str(), rmse, stats.max_error, pct95, median);
  107. if (print_histogram) {
  108. printf("Error distribution:\n");
  109. for (size_t i = 0; i < HISTOGRAM_BUCKETS; i++) {
  110. double lower = i * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;
  111. double upper = (i+1) * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;
  112. if (i == HISTOGRAM_BUCKETS -1) upper = INFINITY;
  113. printf("[%3.4f, %3.4f): %11" PRIu64 "\n", lower, upper, stats.error_histogram[i]);
  114. }
  115. }
  116. }
  117. // copied from ggml.h - verify that we can access this as a flat array
  118. static bool tensor_is_contiguous(const struct ggml_tensor * tensor) {
  119. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  120. return
  121. tensor->nb[0] == ggml_type_size(tensor->type) &&
  122. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  123. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  124. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  125. }
  126. void test_roundtrip_on_chunk(
  127. const ggml_tensor * layer,
  128. int64_t offset,
  129. int64_t chunk_size,
  130. const quantize_fns_t & qfns,
  131. bool use_reference,
  132. float * input_scratch,
  133. char * quantized_scratch,
  134. float * output_scratch,
  135. error_stats & stats) {
  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, stats);
  150. }
  151. // Run quantization function for a single layer and update error stats
  152. void test_roundtrip_on_layer(
  153. std::string & name,
  154. bool print_layer_stats,
  155. const quantize_fns_t & qfns,
  156. bool use_reference,
  157. const ggml_tensor * layer,
  158. std::vector<float> & input_scratch,
  159. std::vector<char> & quantized_scratch,
  160. std::vector<float> & output_scratch,
  161. error_stats & total_error,
  162. int max_thread = 0) {
  163. assert(tensor_is_contiguous(layer));
  164. error_stats layer_error {};
  165. uint64_t nelements = ggml_nelements(layer);
  166. float* input_scratch_ptr = nullptr;
  167. if (layer->type == GGML_TYPE_F16) {
  168. if (input_scratch.size() < nelements) input_scratch.resize(nelements);
  169. input_scratch_ptr = input_scratch.data();
  170. }
  171. if (quantized_scratch.size() < 4*nelements) quantized_scratch.resize(4*nelements);
  172. if (output_scratch.size() < nelements) output_scratch.resize(nelements);
  173. if (max_thread < 1) max_thread = std::thread::hardware_concurrency();
  174. int chunk_size = 32*512;
  175. int num_chunks = (nelements + chunk_size - 1)/chunk_size;
  176. if (num_chunks < 2 || max_thread < 2) {
  177. test_roundtrip_on_chunk(layer, 0, nelements, qfns, use_reference, input_scratch_ptr, quantized_scratch.data(),
  178. output_scratch.data(), print_layer_stats ? layer_error : total_error);
  179. } else {
  180. auto & stats = print_layer_stats ? layer_error : total_error;
  181. std::mutex mutex;
  182. uint64_t counter = 0;
  183. auto compute = [&mutex, &counter, &stats, &qfns, nelements, layer, use_reference, input_scratch_ptr,
  184. &quantized_scratch, &output_scratch, chunk_size] () {
  185. error_stats local_stats {};
  186. while (true) {
  187. std::unique_lock<std::mutex> lock(mutex);
  188. uint64_t offset = counter; counter += chunk_size;
  189. if (offset >= nelements) {
  190. combine_error_stats(stats, local_stats);
  191. break;
  192. }
  193. lock.unlock();
  194. uint64_t chunk = offset + chunk_size < nelements ? chunk_size : nelements - offset;
  195. test_roundtrip_on_chunk(layer, offset, chunk, qfns, use_reference, input_scratch_ptr + offset,
  196. quantized_scratch.data() + 4*offset, output_scratch.data() + offset, local_stats);
  197. }
  198. };
  199. int nthread = std::min(num_chunks, max_thread);
  200. std::vector<std::thread> workers(nthread-1);
  201. for (auto& w : workers) w = std::thread(compute);
  202. compute();
  203. for (auto& w : workers) w.join();
  204. }
  205. if (print_layer_stats) {
  206. print_error_stats(name, layer_error, false);
  207. combine_error_stats(total_error, layer_error);
  208. }
  209. }
  210. int main(int argc, char ** argv) {
  211. ggml_time_init();
  212. quantize_stats_params params;
  213. // read command line
  214. int max_thread = 0;
  215. bool invalid_param = false;
  216. std::string arg;
  217. for (int i = 1; i < argc; i++) {
  218. arg = argv[i];
  219. if (arg == "-h" || arg == "--help") {
  220. quantize_stats_print_usage(argc, argv);
  221. exit(0);
  222. } else if (arg == "-r" || arg == "--reference") {
  223. params.reference = true;
  224. } else if (arg == "-v") {
  225. params.verbose = true;
  226. } else if (arg == "-p" || arg == "--per-layer-stats") {
  227. params.per_layer_stats = true;
  228. } else if (arg == "--histogram") {
  229. params.print_histogram = true;
  230. } else if (arg == "-m" || arg == "--model") {
  231. if (++i >= argc) {
  232. invalid_param = true;
  233. break;
  234. }
  235. params.model = argv[i];
  236. } else if (arg == "-l" || arg == "--include-layer") {
  237. if (++i >= argc) {
  238. invalid_param = true;
  239. break;
  240. }
  241. params.include_layers.push_back(argv[i]);
  242. } else if (arg == "-L" || arg == "--exclude-layer") {
  243. if (++i >= argc) {
  244. invalid_param = true;
  245. break;
  246. }
  247. params.exclude_layers.push_back(argv[i]);
  248. } else if (arg == "-t" || arg == "--type") {
  249. if (++i >= argc) {
  250. invalid_param = true;
  251. break;
  252. }
  253. int j;
  254. for (j = 0; j < GGML_TYPE_COUNT; ++j) {
  255. const auto * name = ggml_type_name((ggml_type) j);
  256. if (name && strcmp(argv[i], name) == 0) break;
  257. }
  258. if (j < GGML_TYPE_COUNT) {
  259. params.include_types.push_back((ggml_type) j);
  260. } else {
  261. fprintf(stderr, "error: %s not in list of types\n", argv[i]);
  262. invalid_param = true;
  263. }
  264. } else if (arg == "-n" || arg == "--num-threads") {
  265. if (++i >= argc) {
  266. invalid_param = true;
  267. break;
  268. }
  269. max_thread = atoi(argv[i]);
  270. } else {
  271. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  272. quantize_stats_print_usage(argc, argv);
  273. return 1;
  274. }
  275. }
  276. if (invalid_param) {
  277. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  278. quantize_stats_print_usage(argc, argv);
  279. return 1;
  280. }
  281. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  282. // load the model
  283. fprintf(stderr, "Loading model\n");
  284. const int64_t t_main_start_us = ggml_time_us();
  285. llama_context * ctx;
  286. {
  287. auto lparams = llama_context_default_params();
  288. lparams.n_ctx = 256;
  289. lparams.seed = 1;
  290. lparams.f16_kv = false;
  291. lparams.use_mlock = false;
  292. ctx = llama_init_from_file(params.model.c_str(), lparams);
  293. if (ctx == NULL) {
  294. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  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. return 1;
  317. }
  318. included_layers++;
  319. max_nelements = std::max(max_nelements, ggml_nelements(kv_tensor.second));
  320. }
  321. if (is_f16) {
  322. printf("note: source model is f16\n");
  323. }
  324. printf("testing %d layers with max size %" PRId64 "\n", included_layers, max_nelements);
  325. // allocate scratch space
  326. std::vector<float> input_scratch;
  327. std::vector<char> quantized_scratch;
  328. std::vector<float> output_scratch;
  329. // loop throught quantization types
  330. for (int i = 0; i < GGML_TYPE_COUNT; i++) {
  331. const ggml_type type = (ggml_type) i;
  332. if (!params.include_types.empty() && std::find(params.include_types.begin(), params.include_types.end(), i) == params.include_types.end()) {
  333. continue;
  334. }
  335. quantize_fns_t qfns = ggml_internal_get_quantize_fn(i);
  336. if (qfns.quantize_row_q && qfns.dequantize_row_q) {
  337. if (params.verbose) {
  338. printf("testing %s ...\n", ggml_type_name(type));
  339. }
  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. // report timing
  368. {
  369. const int64_t t_main_end_us = ggml_time_us();
  370. printf("\n");
  371. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);
  372. }
  373. return 0;
  374. }