quantize.cpp 2.2 KB

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