run.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #if defined(_WIN32)
  2. #include <windows.h>
  3. #else
  4. #include <unistd.h>
  5. #endif
  6. #include <climits>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <iostream>
  10. #include <sstream>
  11. #include <string>
  12. #include <unordered_map>
  13. #include <vector>
  14. #include "llama-cpp.h"
  15. typedef std::unique_ptr<char[]> char_array_ptr;
  16. struct Argument {
  17. std::string flag;
  18. std::string help_text;
  19. };
  20. struct Options {
  21. std::string model_path, prompt_non_interactive;
  22. int ngl = 99;
  23. int n_ctx = 2048;
  24. };
  25. class ArgumentParser {
  26. public:
  27. ArgumentParser(const char * program_name) : program_name(program_name) {}
  28. void add_argument(const std::string & flag, std::string & var, const std::string & help_text = "") {
  29. string_args[flag] = &var;
  30. arguments.push_back({flag, help_text});
  31. }
  32. void add_argument(const std::string & flag, int & var, const std::string & help_text = "") {
  33. int_args[flag] = &var;
  34. arguments.push_back({flag, help_text});
  35. }
  36. int parse(int argc, const char ** argv) {
  37. for (int i = 1; i < argc; ++i) {
  38. std::string arg = argv[i];
  39. if (string_args.count(arg)) {
  40. if (i + 1 < argc) {
  41. *string_args[arg] = argv[++i];
  42. } else {
  43. fprintf(stderr, "error: missing value for %s\n", arg.c_str());
  44. print_usage();
  45. return 1;
  46. }
  47. } else if (int_args.count(arg)) {
  48. if (i + 1 < argc) {
  49. if (parse_int_arg(argv[++i], *int_args[arg]) != 0) {
  50. fprintf(stderr, "error: invalid value for %s: %s\n", arg.c_str(), argv[i]);
  51. print_usage();
  52. return 1;
  53. }
  54. } else {
  55. fprintf(stderr, "error: missing value for %s\n", arg.c_str());
  56. print_usage();
  57. return 1;
  58. }
  59. } else {
  60. fprintf(stderr, "error: unrecognized argument %s\n", arg.c_str());
  61. print_usage();
  62. return 1;
  63. }
  64. }
  65. if (string_args["-m"]->empty()) {
  66. fprintf(stderr, "error: -m is required\n");
  67. print_usage();
  68. return 1;
  69. }
  70. return 0;
  71. }
  72. private:
  73. const char * program_name;
  74. std::unordered_map<std::string, std::string *> string_args;
  75. std::unordered_map<std::string, int *> int_args;
  76. std::vector<Argument> arguments;
  77. int parse_int_arg(const char * arg, int & value) {
  78. char * end;
  79. const long val = std::strtol(arg, &end, 10);
  80. if (*end == '\0' && val >= INT_MIN && val <= INT_MAX) {
  81. value = static_cast<int>(val);
  82. return 0;
  83. }
  84. return 1;
  85. }
  86. void print_usage() const {
  87. printf("\nUsage:\n");
  88. printf(" %s [OPTIONS]\n\n", program_name);
  89. printf("Options:\n");
  90. for (const auto & arg : arguments) {
  91. printf(" %-10s %s\n", arg.flag.c_str(), arg.help_text.c_str());
  92. }
  93. printf("\n");
  94. }
  95. };
  96. class LlamaData {
  97. public:
  98. llama_model_ptr model;
  99. llama_sampler_ptr sampler;
  100. llama_context_ptr context;
  101. std::vector<llama_chat_message> messages;
  102. int init(const Options & opt) {
  103. model = initialize_model(opt.model_path, opt.ngl);
  104. if (!model) {
  105. return 1;
  106. }
  107. context = initialize_context(model, opt.n_ctx);
  108. if (!context) {
  109. return 1;
  110. }
  111. sampler = initialize_sampler();
  112. return 0;
  113. }
  114. private:
  115. // Initializes the model and returns a unique pointer to it
  116. llama_model_ptr initialize_model(const std::string & model_path, const int ngl) {
  117. llama_model_params model_params = llama_model_default_params();
  118. model_params.n_gpu_layers = ngl;
  119. llama_model_ptr model(llama_load_model_from_file(model_path.c_str(), model_params));
  120. if (!model) {
  121. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  122. }
  123. return model;
  124. }
  125. // Initializes the context with the specified parameters
  126. llama_context_ptr initialize_context(const llama_model_ptr & model, const int n_ctx) {
  127. llama_context_params ctx_params = llama_context_default_params();
  128. ctx_params.n_ctx = n_ctx;
  129. ctx_params.n_batch = n_ctx;
  130. llama_context_ptr context(llama_new_context_with_model(model.get(), ctx_params));
  131. if (!context) {
  132. fprintf(stderr, "%s: error: failed to create the llama_context\n", __func__);
  133. }
  134. return context;
  135. }
  136. // Initializes and configures the sampler
  137. llama_sampler_ptr initialize_sampler() {
  138. llama_sampler_ptr sampler(llama_sampler_chain_init(llama_sampler_chain_default_params()));
  139. llama_sampler_chain_add(sampler.get(), llama_sampler_init_min_p(0.05f, 1));
  140. llama_sampler_chain_add(sampler.get(), llama_sampler_init_temp(0.8f));
  141. llama_sampler_chain_add(sampler.get(), llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
  142. return sampler;
  143. }
  144. };
  145. // Add a message to `messages` and store its content in `owned_content`
  146. static void add_message(const char * role, const std::string & text, LlamaData & llama_data,
  147. std::vector<char_array_ptr> & owned_content) {
  148. char_array_ptr content(new char[text.size() + 1]);
  149. std::strcpy(content.get(), text.c_str());
  150. llama_data.messages.push_back({role, content.get()});
  151. owned_content.push_back(std::move(content));
  152. }
  153. // Function to apply the chat template and resize `formatted` if needed
  154. static int apply_chat_template(const LlamaData & llama_data, std::vector<char> & formatted, const bool append) {
  155. int result = llama_chat_apply_template(llama_data.model.get(), nullptr, llama_data.messages.data(),
  156. llama_data.messages.size(), append, formatted.data(), formatted.size());
  157. if (result > static_cast<int>(formatted.size())) {
  158. formatted.resize(result);
  159. result = llama_chat_apply_template(llama_data.model.get(), nullptr, llama_data.messages.data(),
  160. llama_data.messages.size(), append, formatted.data(), formatted.size());
  161. }
  162. return result;
  163. }
  164. // Function to tokenize the prompt
  165. static int tokenize_prompt(const llama_model_ptr & model, const std::string & prompt,
  166. std::vector<llama_token> & prompt_tokens) {
  167. const int n_prompt_tokens = -llama_tokenize(model.get(), prompt.c_str(), prompt.size(), NULL, 0, true, true);
  168. prompt_tokens.resize(n_prompt_tokens);
  169. if (llama_tokenize(model.get(), prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), true,
  170. true) < 0) {
  171. GGML_ABORT("failed to tokenize the prompt\n");
  172. }
  173. return n_prompt_tokens;
  174. }
  175. // Check if we have enough space in the context to evaluate this batch
  176. static int check_context_size(const llama_context_ptr & ctx, const llama_batch & batch) {
  177. const int n_ctx = llama_n_ctx(ctx.get());
  178. const int n_ctx_used = llama_get_kv_cache_used_cells(ctx.get());
  179. if (n_ctx_used + batch.n_tokens > n_ctx) {
  180. printf("\033[0m\n");
  181. fprintf(stderr, "context size exceeded\n");
  182. return 1;
  183. }
  184. return 0;
  185. }
  186. // convert the token to a string
  187. static int convert_token_to_string(const llama_model_ptr & model, const llama_token token_id, std::string & piece) {
  188. char buf[256];
  189. int n = llama_token_to_piece(model.get(), token_id, buf, sizeof(buf), 0, true);
  190. if (n < 0) {
  191. GGML_ABORT("failed to convert token to piece\n");
  192. }
  193. piece = std::string(buf, n);
  194. return 0;
  195. }
  196. static void print_word_and_concatenate_to_response(const std::string & piece, std::string & response) {
  197. printf("%s", piece.c_str());
  198. fflush(stdout);
  199. response += piece;
  200. }
  201. // helper function to evaluate a prompt and generate a response
  202. static int generate(LlamaData & llama_data, const std::string & prompt, std::string & response) {
  203. std::vector<llama_token> prompt_tokens;
  204. const int n_prompt_tokens = tokenize_prompt(llama_data.model, prompt, prompt_tokens);
  205. if (n_prompt_tokens < 0) {
  206. return 1;
  207. }
  208. // prepare a batch for the prompt
  209. llama_batch batch = llama_batch_get_one(prompt_tokens.data(), prompt_tokens.size());
  210. llama_token new_token_id;
  211. while (true) {
  212. check_context_size(llama_data.context, batch);
  213. if (llama_decode(llama_data.context.get(), batch)) {
  214. GGML_ABORT("failed to decode\n");
  215. }
  216. // sample the next token, check is it an end of generation?
  217. new_token_id = llama_sampler_sample(llama_data.sampler.get(), llama_data.context.get(), -1);
  218. if (llama_token_is_eog(llama_data.model.get(), new_token_id)) {
  219. break;
  220. }
  221. std::string piece;
  222. if (convert_token_to_string(llama_data.model, new_token_id, piece)) {
  223. return 1;
  224. }
  225. print_word_and_concatenate_to_response(piece, response);
  226. // prepare the next batch with the sampled token
  227. batch = llama_batch_get_one(&new_token_id, 1);
  228. }
  229. return 0;
  230. }
  231. static int parse_arguments(const int argc, const char ** argv, Options & opt) {
  232. ArgumentParser parser(argv[0]);
  233. parser.add_argument("-m", opt.model_path, "model");
  234. parser.add_argument("-p", opt.prompt_non_interactive, "prompt");
  235. parser.add_argument("-c", opt.n_ctx, "context_size");
  236. parser.add_argument("-ngl", opt.ngl, "n_gpu_layers");
  237. if (parser.parse(argc, argv)) {
  238. return 1;
  239. }
  240. return 0;
  241. }
  242. static int read_user_input(std::string & user) {
  243. std::getline(std::cin, user);
  244. return user.empty(); // Indicate an error or empty input
  245. }
  246. // Function to generate a response based on the prompt
  247. static int generate_response(LlamaData & llama_data, const std::string & prompt, std::string & response) {
  248. // Set response color
  249. printf("\033[33m");
  250. if (generate(llama_data, prompt, response)) {
  251. fprintf(stderr, "failed to generate response\n");
  252. return 1;
  253. }
  254. // End response with color reset and newline
  255. printf("\n\033[0m");
  256. return 0;
  257. }
  258. // Helper function to apply the chat template and handle errors
  259. static int apply_chat_template_with_error_handling(const LlamaData & llama_data, std::vector<char> & formatted,
  260. const bool is_user_input, int & output_length) {
  261. const int new_len = apply_chat_template(llama_data, formatted, is_user_input);
  262. if (new_len < 0) {
  263. fprintf(stderr, "failed to apply the chat template\n");
  264. return -1;
  265. }
  266. output_length = new_len;
  267. return 0;
  268. }
  269. // Helper function to handle user input
  270. static bool handle_user_input(std::string & user_input, const std::string & prompt_non_interactive) {
  271. if (!prompt_non_interactive.empty()) {
  272. user_input = prompt_non_interactive;
  273. return true; // No need for interactive input
  274. }
  275. printf("\033[32m> \033[0m");
  276. return !read_user_input(user_input); // Returns false if input ends the loop
  277. }
  278. // Function to tokenize the prompt
  279. static int chat_loop(LlamaData & llama_data, std::string & prompt_non_interactive) {
  280. std::vector<char_array_ptr> owned_content;
  281. std::vector<char> fmtted(llama_n_ctx(llama_data.context.get()));
  282. int prev_len = 0;
  283. while (true) {
  284. // Get user input
  285. std::string user_input;
  286. if (!handle_user_input(user_input, prompt_non_interactive)) {
  287. break;
  288. }
  289. add_message("user", prompt_non_interactive.empty() ? user_input : prompt_non_interactive, llama_data,
  290. owned_content);
  291. int new_len;
  292. if (apply_chat_template_with_error_handling(llama_data, fmtted, true, new_len) < 0) {
  293. return 1;
  294. }
  295. std::string prompt(fmtted.begin() + prev_len, fmtted.begin() + new_len);
  296. std::string response;
  297. if (generate_response(llama_data, prompt, response)) {
  298. return 1;
  299. }
  300. }
  301. return 0;
  302. }
  303. static void log_callback(const enum ggml_log_level level, const char * text, void *) {
  304. if (level == GGML_LOG_LEVEL_ERROR) {
  305. fprintf(stderr, "%s", text);
  306. }
  307. }
  308. static bool is_stdin_a_terminal() {
  309. #if defined(_WIN32)
  310. HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
  311. DWORD mode;
  312. return GetConsoleMode(hStdin, &mode);
  313. #else
  314. return isatty(STDIN_FILENO);
  315. #endif
  316. }
  317. static std::string read_pipe_data() {
  318. std::ostringstream result;
  319. result << std::cin.rdbuf(); // Read all data from std::cin
  320. return result.str();
  321. }
  322. int main(int argc, const char ** argv) {
  323. Options opt;
  324. if (parse_arguments(argc, argv, opt)) {
  325. return 1;
  326. }
  327. if (!is_stdin_a_terminal()) {
  328. if (!opt.prompt_non_interactive.empty()) {
  329. opt.prompt_non_interactive += "\n\n";
  330. }
  331. opt.prompt_non_interactive += read_pipe_data();
  332. }
  333. llama_log_set(log_callback, nullptr);
  334. LlamaData llama_data;
  335. if (llama_data.init(opt)) {
  336. return 1;
  337. }
  338. if (chat_loop(llama_data, opt.prompt_non_interactive)) {
  339. return 1;
  340. }
  341. return 0;
  342. }