simple-chat.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. #include "llama.h"
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. static void print_usage(int, char ** argv) {
  8. printf("\nexample usage:\n");
  9. printf("\n %s -m model.gguf [-c context_size] [-ngl n_gpu_layers]\n", argv[0]);
  10. printf("\n");
  11. }
  12. int main(int argc, char ** argv) {
  13. std::string model_path;
  14. int ngl = 99;
  15. int n_ctx = 2048;
  16. // parse command line arguments
  17. for (int i = 1; i < argc; i++) {
  18. try {
  19. if (strcmp(argv[i], "-m") == 0) {
  20. if (i + 1 < argc) {
  21. model_path = argv[++i];
  22. } else {
  23. print_usage(argc, argv);
  24. return 1;
  25. }
  26. } else if (strcmp(argv[i], "-c") == 0) {
  27. if (i + 1 < argc) {
  28. n_ctx = std::stoi(argv[++i]);
  29. } else {
  30. print_usage(argc, argv);
  31. return 1;
  32. }
  33. } else if (strcmp(argv[i], "-ngl") == 0) {
  34. if (i + 1 < argc) {
  35. ngl = std::stoi(argv[++i]);
  36. } else {
  37. print_usage(argc, argv);
  38. return 1;
  39. }
  40. } else {
  41. print_usage(argc, argv);
  42. return 1;
  43. }
  44. } catch (std::exception & e) {
  45. fprintf(stderr, "error: %s\n", e.what());
  46. print_usage(argc, argv);
  47. return 1;
  48. }
  49. }
  50. if (model_path.empty()) {
  51. print_usage(argc, argv);
  52. return 1;
  53. }
  54. // only print errors
  55. llama_log_set([](enum ggml_log_level level, const char * text, void * /* user_data */) {
  56. if (level >= GGML_LOG_LEVEL_ERROR) {
  57. fprintf(stderr, "%s", text);
  58. }
  59. }, nullptr);
  60. // load dynamic backends
  61. ggml_backend_load_all();
  62. // initialize the model
  63. llama_model_params model_params = llama_model_default_params();
  64. model_params.n_gpu_layers = ngl;
  65. llama_model * model = llama_model_load_from_file(model_path.c_str(), model_params);
  66. if (!model) {
  67. fprintf(stderr , "%s: error: unable to load model\n" , __func__);
  68. return 1;
  69. }
  70. // initialize the context
  71. llama_context_params ctx_params = llama_context_default_params();
  72. ctx_params.n_ctx = n_ctx;
  73. ctx_params.n_batch = n_ctx;
  74. llama_context * ctx = llama_new_context_with_model(model, ctx_params);
  75. if (!ctx) {
  76. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  77. return 1;
  78. }
  79. // initialize the sampler
  80. llama_sampler * smpl = llama_sampler_chain_init(llama_sampler_chain_default_params());
  81. llama_sampler_chain_add(smpl, llama_sampler_init_min_p(0.05f, 1));
  82. llama_sampler_chain_add(smpl, llama_sampler_init_temp(0.8f));
  83. llama_sampler_chain_add(smpl, llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
  84. // helper function to evaluate a prompt and generate a response
  85. auto generate = [&](const std::string & prompt) {
  86. std::string response;
  87. // tokenize the prompt
  88. const int n_prompt_tokens = -llama_tokenize(model, prompt.c_str(), prompt.size(), NULL, 0, true, true);
  89. std::vector<llama_token> prompt_tokens(n_prompt_tokens);
  90. if (llama_tokenize(model, prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), llama_get_kv_cache_used_cells(ctx) == 0, true) < 0) {
  91. GGML_ABORT("failed to tokenize the prompt\n");
  92. }
  93. // prepare a batch for the prompt
  94. llama_batch batch = llama_batch_get_one(prompt_tokens.data(), prompt_tokens.size());
  95. llama_token new_token_id;
  96. while (true) {
  97. // check if we have enough space in the context to evaluate this batch
  98. int n_ctx = llama_n_ctx(ctx);
  99. int n_ctx_used = llama_get_kv_cache_used_cells(ctx);
  100. if (n_ctx_used + batch.n_tokens > n_ctx) {
  101. printf("\033[0m\n");
  102. fprintf(stderr, "context size exceeded\n");
  103. exit(0);
  104. }
  105. if (llama_decode(ctx, batch)) {
  106. GGML_ABORT("failed to decode\n");
  107. }
  108. // sample the next token
  109. new_token_id = llama_sampler_sample(smpl, ctx, -1);
  110. // is it an end of generation?
  111. if (llama_token_is_eog(model, new_token_id)) {
  112. break;
  113. }
  114. // convert the token to a string, print it and add it to the response
  115. char buf[256];
  116. int n = llama_token_to_piece(model, new_token_id, buf, sizeof(buf), 0, true);
  117. if (n < 0) {
  118. GGML_ABORT("failed to convert token to piece\n");
  119. }
  120. std::string piece(buf, n);
  121. printf("%s", piece.c_str());
  122. fflush(stdout);
  123. response += piece;
  124. // prepare the next batch with the sampled token
  125. batch = llama_batch_get_one(&new_token_id, 1);
  126. }
  127. return response;
  128. };
  129. std::vector<llama_chat_message> messages;
  130. std::vector<char> formatted(llama_n_ctx(ctx));
  131. int prev_len = 0;
  132. while (true) {
  133. // get user input
  134. printf("\033[32m> \033[0m");
  135. std::string user;
  136. std::getline(std::cin, user);
  137. if (user.empty()) {
  138. break;
  139. }
  140. // add the user input to the message list and format it
  141. messages.push_back({"user", strdup(user.c_str())});
  142. int new_len = llama_chat_apply_template(model, nullptr, messages.data(), messages.size(), true, formatted.data(), formatted.size());
  143. if (new_len > (int)formatted.size()) {
  144. formatted.resize(new_len);
  145. new_len = llama_chat_apply_template(model, nullptr, messages.data(), messages.size(), true, formatted.data(), formatted.size());
  146. }
  147. if (new_len < 0) {
  148. fprintf(stderr, "failed to apply the chat template\n");
  149. return 1;
  150. }
  151. // remove previous messages to obtain the prompt to generate the response
  152. std::string prompt(formatted.begin() + prev_len, formatted.begin() + new_len);
  153. // generate a response
  154. printf("\033[33m");
  155. std::string response = generate(prompt);
  156. printf("\n\033[0m");
  157. // add the response to the messages
  158. messages.push_back({"assistant", strdup(response.c_str())});
  159. prev_len = llama_chat_apply_template(model, nullptr, messages.data(), messages.size(), false, nullptr, 0);
  160. if (prev_len < 0) {
  161. fprintf(stderr, "failed to apply the chat template\n");
  162. return 1;
  163. }
  164. }
  165. // free resources
  166. for (auto & msg : messages) {
  167. free(const_cast<char *>(msg.content));
  168. }
  169. llama_sampler_free(smpl);
  170. llama_free(ctx);
  171. llama_model_free(model);
  172. return 0;
  173. }