simple-chat.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. const llama_vocab * vocab = llama_model_get_vocab(model);
  71. // initialize the context
  72. llama_context_params ctx_params = llama_context_default_params();
  73. ctx_params.n_ctx = n_ctx;
  74. ctx_params.n_batch = n_ctx;
  75. llama_context * ctx = llama_init_from_model(model, ctx_params);
  76. if (!ctx) {
  77. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  78. return 1;
  79. }
  80. // initialize the sampler
  81. llama_sampler * smpl = llama_sampler_chain_init(llama_sampler_chain_default_params());
  82. llama_sampler_chain_add(smpl, llama_sampler_init_min_p(0.05f, 1));
  83. llama_sampler_chain_add(smpl, llama_sampler_init_temp(0.8f));
  84. llama_sampler_chain_add(smpl, llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
  85. // helper function to evaluate a prompt and generate a response
  86. auto generate = [&](const std::string & prompt) {
  87. std::string response;
  88. const bool is_first = llama_kv_self_used_cells(ctx) == 0;
  89. // tokenize the prompt
  90. const int n_prompt_tokens = -llama_tokenize(vocab, prompt.c_str(), prompt.size(), NULL, 0, is_first, true);
  91. std::vector<llama_token> prompt_tokens(n_prompt_tokens);
  92. if (llama_tokenize(vocab, prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), is_first, true) < 0) {
  93. GGML_ABORT("failed to tokenize the prompt\n");
  94. }
  95. // prepare a batch for the prompt
  96. llama_batch batch = llama_batch_get_one(prompt_tokens.data(), prompt_tokens.size());
  97. llama_token new_token_id;
  98. while (true) {
  99. // check if we have enough space in the context to evaluate this batch
  100. int n_ctx = llama_n_ctx(ctx);
  101. int n_ctx_used = llama_kv_self_used_cells(ctx);
  102. if (n_ctx_used + batch.n_tokens > n_ctx) {
  103. printf("\033[0m\n");
  104. fprintf(stderr, "context size exceeded\n");
  105. exit(0);
  106. }
  107. if (llama_decode(ctx, batch)) {
  108. GGML_ABORT("failed to decode\n");
  109. }
  110. // sample the next token
  111. new_token_id = llama_sampler_sample(smpl, ctx, -1);
  112. // is it an end of generation?
  113. if (llama_vocab_is_eog(vocab, new_token_id)) {
  114. break;
  115. }
  116. // convert the token to a string, print it and add it to the response
  117. char buf[256];
  118. int n = llama_token_to_piece(vocab, new_token_id, buf, sizeof(buf), 0, true);
  119. if (n < 0) {
  120. GGML_ABORT("failed to convert token to piece\n");
  121. }
  122. std::string piece(buf, n);
  123. printf("%s", piece.c_str());
  124. fflush(stdout);
  125. response += piece;
  126. // prepare the next batch with the sampled token
  127. batch = llama_batch_get_one(&new_token_id, 1);
  128. }
  129. return response;
  130. };
  131. std::vector<llama_chat_message> messages;
  132. std::vector<char> formatted(llama_n_ctx(ctx));
  133. int prev_len = 0;
  134. while (true) {
  135. // get user input
  136. printf("\033[32m> \033[0m");
  137. std::string user;
  138. std::getline(std::cin, user);
  139. if (user.empty()) {
  140. break;
  141. }
  142. const char * tmpl = llama_model_chat_template(model, /* name */ nullptr);
  143. // add the user input to the message list and format it
  144. messages.push_back({"user", strdup(user.c_str())});
  145. int new_len = llama_chat_apply_template(tmpl, messages.data(), messages.size(), true, formatted.data(), formatted.size());
  146. if (new_len > (int)formatted.size()) {
  147. formatted.resize(new_len);
  148. new_len = llama_chat_apply_template(tmpl, messages.data(), messages.size(), true, formatted.data(), formatted.size());
  149. }
  150. if (new_len < 0) {
  151. fprintf(stderr, "failed to apply the chat template\n");
  152. return 1;
  153. }
  154. // remove previous messages to obtain the prompt to generate the response
  155. std::string prompt(formatted.begin() + prev_len, formatted.begin() + new_len);
  156. // generate a response
  157. printf("\033[33m");
  158. std::string response = generate(prompt);
  159. printf("\n\033[0m");
  160. // add the response to the messages
  161. messages.push_back({"assistant", strdup(response.c_str())});
  162. prev_len = llama_chat_apply_template(tmpl, messages.data(), messages.size(), false, nullptr, 0);
  163. if (prev_len < 0) {
  164. fprintf(stderr, "failed to apply the chat template\n");
  165. return 1;
  166. }
  167. }
  168. // free resources
  169. for (auto & msg : messages) {
  170. free(const_cast<char *>(msg.content));
  171. }
  172. llama_sampler_free(smpl);
  173. llama_free(ctx);
  174. llama_model_free(model);
  175. return 0;
  176. }