quantize.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. {"q4_3", LLAMA_FTYPE_MOSTLY_Q4_3},
  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. int nthread = argc > 4 ? atoi(argv[4]) : 0;
  47. const int64_t t_main_start_us = ggml_time_us();
  48. int64_t t_quantize_us = 0;
  49. // load the model
  50. {
  51. const int64_t t_start_us = ggml_time_us();
  52. if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ftype, nthread)) {
  53. fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
  54. return 1;
  55. }
  56. t_quantize_us = ggml_time_us() - t_start_us;
  57. }
  58. // report timing
  59. {
  60. const int64_t t_main_end_us = ggml_time_us();
  61. printf("\n");
  62. printf("%s: quantize time = %8.2f ms\n", __func__, t_quantize_us/1000.0);
  63. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0);
  64. }
  65. return 0;
  66. }