1
0

simple-chat.cpp 6.8 KB

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