quantize.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "ggml.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include <cstdio>
  5. #include <map>
  6. #include <string>
  7. static const std::map<std::string, enum llama_ftype> LLAMA_FTYPE_MAP = {
  8. {"q4_0", LLAMA_FTYPE_MOSTLY_Q4_0},
  9. {"q4_1", LLAMA_FTYPE_MOSTLY_Q4_1},
  10. {"q4_2", LLAMA_FTYPE_MOSTLY_Q4_2},
  11. {"q5_0", LLAMA_FTYPE_MOSTLY_Q5_0},
  12. {"q5_1", LLAMA_FTYPE_MOSTLY_Q5_1},
  13. {"q8_0", LLAMA_FTYPE_MOSTLY_Q8_0},
  14. };
  15. // usage:
  16. // ./quantize models/llama/ggml-model.bin models/llama/ggml-model-quant.bin type
  17. //
  18. int main(int argc, char ** argv) {
  19. ggml_time_init();
  20. if (argc < 4) {
  21. fprintf(stderr, "usage: %s model-f32.bin model-quant.bin type [nthread]\n", argv[0]);
  22. for (auto it = LLAMA_FTYPE_MAP.begin(); it != LLAMA_FTYPE_MAP.end(); it++) {
  23. fprintf(stderr, " type = \"%s\" or %d\n", it->first.c_str(), it->second);
  24. }
  25. return 1;
  26. }
  27. // needed to initialize f16 tables
  28. {
  29. struct ggml_init_params params = { 0, NULL, false };
  30. struct ggml_context * ctx = ggml_init(params);
  31. ggml_free(ctx);
  32. }
  33. const std::string fname_inp = argv[1];
  34. const std::string fname_out = argv[2];
  35. enum llama_ftype ftype;
  36. if (argv[3][0] == 'q') {
  37. auto it = LLAMA_FTYPE_MAP.find(argv[3]);
  38. if (it == LLAMA_FTYPE_MAP.end()) {
  39. fprintf(stderr, "%s: unknown ftype '%s'\n", __func__, argv[3]);
  40. return 1;
  41. }
  42. ftype = it->second;
  43. } else {
  44. ftype = (enum llama_ftype)atoi(argv[3]);
  45. }
  46. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  47. int nthread = argc > 4 ? atoi(argv[4]) : 0;
  48. const int64_t t_main_start_us = ggml_time_us();
  49. int64_t t_quantize_us = 0;
  50. // load the model
  51. {
  52. const int64_t t_start_us = ggml_time_us();
  53. if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ftype, nthread)) {
  54. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  55. return 1;
  56. }
  57. t_quantize_us = ggml_time_us() - t_start_us;
  58. }
  59. // report timing
  60. {
  61. const int64_t t_main_end_us = ggml_time_us();
  62. printf("\n");
  63. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0);
  64. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);
  65. }
  66. return 0;
  67. }