simple-chat.cpp 6.6 KB

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