1
0

quantize-stats.cpp 15 KB

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