1
0

test-quantize-stats.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #include "ggml.h"
  2. #include "ggml-cpu.h"
  3. #include "llama.h"
  4. #include "common.h"
  5. #include "../src/llama-model.h"
  6. #include <algorithm>
  7. #include <cassert>
  8. #include <cinttypes>
  9. #include <cmath>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <numeric>
  13. #include <regex>
  14. #include <string>
  15. #include <vector>
  16. #include <thread>
  17. #include <mutex>
  18. #if defined(_MSC_VER)
  19. #pragma warning(disable: 4244 4267) // possible loss of data
  20. #endif
  21. struct quantize_stats_params {
  22. std::string model = "models/7B/ggml-model-f16.gguf";
  23. bool verbose = false;
  24. bool per_layer_stats = false;
  25. bool print_histogram = false;
  26. bool reference = false;
  27. std::vector<std::string> include_layers;
  28. std::vector<std::string> exclude_layers;
  29. std::vector<enum ggml_type> include_types;
  30. };
  31. constexpr size_t HISTOGRAM_BUCKETS = 150;
  32. constexpr double HISTOGRAM_RANGE = 0.03;
  33. struct error_stats {
  34. size_t num_samples;
  35. double total_error;
  36. double max_error;
  37. uint64_t error_histogram[HISTOGRAM_BUCKETS];
  38. };
  39. static void quantize_stats_print_usage(int /*argc*/, char ** argv) {
  40. quantize_stats_params params;
  41. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  42. fprintf(stderr, "\n");
  43. fprintf(stderr, "options:\n");
  44. fprintf(stderr, " -h, --help show this help message and exit\n");
  45. fprintf(stderr, " -m FNAME, --model FNAME\n");
  46. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  47. fprintf(stderr, " -r, --reference\n");
  48. fprintf(stderr, " use reference implementation (default: false)\n");
  49. fprintf(stderr, " -v, --verbose\n");
  50. fprintf(stderr, " verbose output (default: false)\n");
  51. fprintf(stderr, " -p, --per-layer-stats\n");
  52. fprintf(stderr, " print stats per layer (default: false)\n");
  53. fprintf(stderr, " --histogram\n");
  54. fprintf(stderr, " print error histogram (default: false)\n");
  55. fprintf(stderr, " -l LAYER, --include-layer LAYER\n");
  56. fprintf(stderr, " only test layers matching pattern\n");
  57. fprintf(stderr, " -L LAYER, --exclude-layer LAYER\n");
  58. fprintf(stderr, " exclude layers matching pattern\n");
  59. fprintf(stderr, " -t TYPE, --type TYPE\n");
  60. fprintf(stderr, " only test given type (q4_0, q4_1)\n");
  61. fprintf(stderr, "\n");
  62. }
  63. // Check if a layer is included/excluded by command line
  64. static bool layer_included(const quantize_stats_params & params, const std::string & layer) {
  65. for (const auto& excluded : params.exclude_layers) {
  66. if (std::regex_search(layer, std::regex(excluded))) {
  67. return false;
  68. }
  69. }
  70. for (const auto& included : params.include_layers) {
  71. if (std::regex_search(layer, std::regex(included))) {
  72. return true;
  73. }
  74. }
  75. return params.include_layers.empty();
  76. }
  77. // Update error statistics given vectors with the before/after result of quantization
  78. static void update_error_stats(int64_t nelements, const float * input, const float * output, error_stats & stats) {
  79. for (int64_t i = 0; i < nelements; i++) {
  80. double diff = input[i] - output[i];
  81. stats.total_error += diff * diff;
  82. stats.max_error = fmax(fabs(diff), stats.max_error);
  83. stats.error_histogram[std::max(std::min((size_t) floor(fabs(diff) / HISTOGRAM_RANGE * HISTOGRAM_BUCKETS), HISTOGRAM_BUCKETS-1), (size_t) 0)]++;
  84. }
  85. stats.num_samples += nelements;
  86. }
  87. static void combine_error_stats(error_stats & into, const error_stats & from) {
  88. into.num_samples += from.num_samples;
  89. into.total_error += from.total_error;
  90. if (from.max_error > into.max_error) into.max_error = from.max_error;
  91. for (size_t i=0; i<HISTOGRAM_BUCKETS; ++i) into.error_histogram[i] += from.error_histogram[i];
  92. }
  93. static double find_quantile(const error_stats & stats, double quantile) {
  94. double sum = std::accumulate(std::begin(stats.error_histogram), std::end(stats.error_histogram), 0.0);
  95. double accum = 0;
  96. for (size_t i = 0; i < HISTOGRAM_BUCKETS; i++) {
  97. accum += stats.error_histogram[i];
  98. if (accum >= sum*quantile) {
  99. return (i+1) * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;
  100. }
  101. }
  102. return INFINITY;
  103. }
  104. static void print_error_stats(const std::string & name, const error_stats & stats, bool print_histogram) {
  105. double rmse = sqrt(stats.total_error / (double) stats.num_samples);
  106. double median = find_quantile(stats, .5);
  107. double pct95 = find_quantile(stats, .95);
  108. printf("%-50s: rmse %.8f, maxerr %.8f, 95pct<%.4f, median<%.4f\n", name.c_str(), rmse, stats.max_error, pct95, median);
  109. if (print_histogram) {
  110. printf("Error distribution:\n");
  111. for (size_t i = 0; i < HISTOGRAM_BUCKETS; i++) {
  112. double lower = i * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;
  113. double upper = (i+1) * HISTOGRAM_RANGE / HISTOGRAM_BUCKETS;
  114. if (i == HISTOGRAM_BUCKETS -1) upper = INFINITY;
  115. printf("[%3.4f, %3.4f): %11" PRIu64 "\n", lower, upper, stats.error_histogram[i]);
  116. }
  117. }
  118. }
  119. // copied from ggml.h - verify that we can access this as a flat array
  120. static bool tensor_is_contiguous(const struct ggml_tensor * tensor) {
  121. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  122. return
  123. tensor->nb[0] == ggml_type_size(tensor->type) &&
  124. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  125. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  126. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  127. }
  128. static void test_roundtrip_on_chunk(
  129. const ggml_tensor * layer, int64_t offset, int64_t chunk_size, const ggml_type_traits & qfns, const ggml_type_traits_cpu & qfns_cpu, bool use_reference,
  130. float * input_scratch, char * quantized_scratch, float * output_scratch, error_stats & stats
  131. ) {
  132. if (layer->type == GGML_TYPE_F16) {
  133. for (int i = 0; i < chunk_size; i++) {
  134. input_scratch[i] = ggml_get_f32_1d(layer, i + offset);
  135. }
  136. } else {
  137. input_scratch = ggml_get_data_f32(layer) + offset;
  138. }
  139. if (use_reference) {
  140. qfns.from_float_ref(input_scratch, quantized_scratch, chunk_size);
  141. } else {
  142. qfns_cpu.from_float(input_scratch, quantized_scratch, chunk_size);
  143. }
  144. qfns.to_float(quantized_scratch, output_scratch, chunk_size);
  145. update_error_stats(chunk_size, input_scratch, output_scratch, stats);
  146. }
  147. // Run quantization function for a single layer and update error stats
  148. static void test_roundtrip_on_layer(
  149. std::string & name, bool print_layer_stats, const ggml_type_traits & qfns, const ggml_type_traits_cpu & qfns_cpu, bool use_reference,
  150. const ggml_tensor * layer, std::vector<float> & input_scratch, std::vector<char> & quantized_scratch,
  151. std::vector<float> & output_scratch, error_stats & total_error, int max_thread = 0
  152. ) {
  153. assert(tensor_is_contiguous(layer));
  154. error_stats layer_error {};
  155. uint64_t nelements = ggml_nelements(layer);
  156. float* input_scratch_ptr = nullptr;
  157. if (layer->type == GGML_TYPE_F16) {
  158. if (input_scratch.size() < nelements) input_scratch.resize(nelements);
  159. input_scratch_ptr = input_scratch.data();
  160. }
  161. if (quantized_scratch.size() < 4*nelements) quantized_scratch.resize(4*nelements);
  162. if (output_scratch.size() < nelements) output_scratch.resize(nelements);
  163. if (max_thread < 1) max_thread = std::thread::hardware_concurrency();
  164. int chunk_size = 32*512;
  165. int num_chunks = (nelements + chunk_size - 1)/chunk_size;
  166. if (num_chunks < 2 || max_thread < 2) {
  167. test_roundtrip_on_chunk(layer, 0, nelements, qfns, qfns_cpu, use_reference, input_scratch_ptr, quantized_scratch.data(),
  168. output_scratch.data(), print_layer_stats ? layer_error : total_error);
  169. } else {
  170. auto & stats = print_layer_stats ? layer_error : total_error;
  171. std::mutex mutex;
  172. uint64_t counter = 0;
  173. auto compute = [&mutex, &counter, &stats, &qfns, &qfns_cpu, nelements, layer, use_reference, input_scratch_ptr,
  174. &quantized_scratch, &output_scratch, chunk_size] () {
  175. error_stats local_stats {};
  176. while (true) {
  177. std::unique_lock<std::mutex> lock(mutex);
  178. uint64_t offset = counter; counter += chunk_size;
  179. if (offset >= nelements) {
  180. combine_error_stats(stats, local_stats);
  181. break;
  182. }
  183. lock.unlock();
  184. uint64_t chunk = offset + chunk_size < nelements ? chunk_size : nelements - offset;
  185. test_roundtrip_on_chunk(layer, offset, chunk, qfns, qfns_cpu, use_reference, input_scratch_ptr + offset,
  186. quantized_scratch.data() + 4*offset, output_scratch.data() + offset, local_stats);
  187. }
  188. };
  189. int nthread = std::min(num_chunks, max_thread);
  190. std::vector<std::thread> workers(nthread-1);
  191. for (auto& w : workers) w = std::thread(compute);
  192. compute();
  193. for (auto& w : workers) w.join();
  194. }
  195. if (print_layer_stats) {
  196. print_error_stats(name, layer_error, false);
  197. combine_error_stats(total_error, layer_error);
  198. }
  199. }
  200. int main(int argc, char ** argv) {
  201. ggml_time_init();
  202. quantize_stats_params params;
  203. // read command line
  204. int max_thread = 0;
  205. bool invalid_param = false;
  206. std::string arg;
  207. for (int i = 1; i < argc; i++) {
  208. arg = argv[i];
  209. if (arg == "-h" || arg == "--help") {
  210. quantize_stats_print_usage(argc, argv);
  211. exit(0);
  212. } else if (arg == "-r" || arg == "--reference") {
  213. params.reference = true;
  214. } else if (arg == "-v") {
  215. params.verbose = true;
  216. } else if (arg == "-p" || arg == "--per-layer-stats") {
  217. params.per_layer_stats = true;
  218. } else if (arg == "--histogram") {
  219. params.print_histogram = true;
  220. } else if (arg == "-m" || arg == "--model") {
  221. if (++i >= argc) {
  222. invalid_param = true;
  223. break;
  224. }
  225. params.model = argv[i];
  226. } else if (arg == "-l" || arg == "--include-layer") {
  227. if (++i >= argc) {
  228. invalid_param = true;
  229. break;
  230. }
  231. params.include_layers.emplace_back(argv[i]);
  232. } else if (arg == "-L" || arg == "--exclude-layer") {
  233. if (++i >= argc) {
  234. invalid_param = true;
  235. break;
  236. }
  237. params.exclude_layers.emplace_back(argv[i]);
  238. } else if (arg == "-t" || arg == "--type") {
  239. if (++i >= argc) {
  240. invalid_param = true;
  241. break;
  242. }
  243. int j;
  244. for (j = 0; j < GGML_TYPE_COUNT; ++j) {
  245. const auto * name = ggml_type_name((ggml_type) j);
  246. if (name && strcmp(argv[i], name) == 0) break;
  247. }
  248. if (j < GGML_TYPE_COUNT) {
  249. params.include_types.push_back((ggml_type) j);
  250. } else {
  251. fprintf(stderr, "error: %s not in list of types\n", argv[i]);
  252. invalid_param = true;
  253. }
  254. } else if (arg == "-n" || arg == "--num-threads") {
  255. if (++i >= argc) {
  256. invalid_param = true;
  257. break;
  258. }
  259. max_thread = atoi(argv[i]);
  260. } else {
  261. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  262. quantize_stats_print_usage(argc, argv);
  263. return 1;
  264. }
  265. }
  266. if (invalid_param) {
  267. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  268. quantize_stats_print_usage(argc, argv);
  269. return 1;
  270. }
  271. print_build_info();
  272. // load the model
  273. fprintf(stderr, "Loading model\n");
  274. const int64_t t_main_start_us = ggml_time_us();
  275. llama_model * model;
  276. llama_context * ctx;
  277. {
  278. auto mparams = llama_model_default_params();
  279. mparams.use_mlock = false;
  280. model = llama_model_load_from_file(params.model.c_str(), mparams);
  281. if (model == NULL) {
  282. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  283. return 1;
  284. }
  285. auto cparams = llama_context_default_params();
  286. cparams.n_ctx = 256;
  287. ctx = llama_init_from_model(model, cparams);
  288. if (ctx == NULL) {
  289. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  290. llama_model_free(model);
  291. return 1;
  292. }
  293. }
  294. const auto & tensors = llama_internal_get_tensor_map(model);
  295. // check layer tensors
  296. int included_layers = 0;
  297. int64_t max_nelements = 0;
  298. bool is_f16 = false;
  299. for (const auto & kv_tensor : tensors) {
  300. if (!layer_included(params, kv_tensor.first)) {
  301. continue;
  302. }
  303. if (params.verbose) {
  304. printf("%s: type %s, size %" PRId64 "\n", kv_tensor.first.c_str(), ggml_type_name(kv_tensor.second->type), ggml_nelements(kv_tensor.second));
  305. }
  306. if (kv_tensor.second->type == GGML_TYPE_F16) {
  307. is_f16 = true;
  308. } else if (kv_tensor.second->type != GGML_TYPE_F32) {
  309. fprintf(stderr, "%s: error: Quantization should be tested with a float model, "
  310. "this model contains already quantized layers (%s is type %d)\n", __func__, kv_tensor.first.c_str(), kv_tensor.second->type);
  311. llama_free(ctx);
  312. llama_model_free(model);
  313. return 1;
  314. }
  315. included_layers++;
  316. max_nelements = std::max(max_nelements, ggml_nelements(kv_tensor.second));
  317. }
  318. if (is_f16) {
  319. printf("note: source model is f16\n");
  320. }
  321. printf("testing %d layers with max size %" PRId64 "\n", included_layers, max_nelements);
  322. // allocate scratch space
  323. std::vector<float> input_scratch;
  324. std::vector<char> quantized_scratch;
  325. std::vector<float> output_scratch;
  326. // loop throught quantization types
  327. for (int i = 0; i < GGML_TYPE_COUNT; i++) {
  328. const ggml_type type = (ggml_type) i;
  329. if (!params.include_types.empty() && std::find(params.include_types.begin(), params.include_types.end(), i) == params.include_types.end()) {
  330. continue;
  331. }
  332. const auto * qfns = ggml_get_type_traits(type);
  333. const auto * qfns_cpu = ggml_get_type_traits_cpu(type);
  334. if (qfns_cpu->from_float && qfns->to_float) {
  335. if (params.verbose) {
  336. printf("testing %s ...\n", ggml_type_name(type));
  337. }
  338. ggml_quantize_init(type);
  339. error_stats global_stats {};
  340. for (const auto & kv_tensor : tensors) {
  341. if (!layer_included(params, kv_tensor.first)) {
  342. continue;
  343. }
  344. if (params.verbose) {
  345. printf(" %s ...\n", kv_tensor.first.c_str());
  346. }
  347. std::string layer_name { ggml_type_name(type) };
  348. layer_name += "::" + kv_tensor.first;
  349. test_roundtrip_on_layer(
  350. layer_name,
  351. params.per_layer_stats,
  352. *qfns, *qfns_cpu,
  353. params.reference,
  354. kv_tensor.second,
  355. input_scratch,
  356. quantized_scratch,
  357. output_scratch,
  358. global_stats,
  359. max_thread
  360. );
  361. }
  362. print_error_stats(ggml_type_name(type), global_stats, params.print_histogram);
  363. }
  364. }
  365. llama_free(ctx);
  366. llama_model_free(model);
  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. }