1
0

quantize.cpp 2.3 KB

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