run.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. #if defined(_WIN32)
  2. # include <windows.h>
  3. # include <io.h>
  4. #else
  5. # include <sys/file.h>
  6. # include <sys/ioctl.h>
  7. # include <unistd.h>
  8. #endif
  9. #if defined(LLAMA_USE_CURL)
  10. # include <curl/curl.h>
  11. #endif
  12. #include <signal.h>
  13. #include <climits>
  14. #include <cstdarg>
  15. #include <cstdio>
  16. #include <cstring>
  17. #include <filesystem>
  18. #include <iostream>
  19. #include <list>
  20. #include <sstream>
  21. #include <string>
  22. #include <vector>
  23. #include "chat.h"
  24. #include "common.h"
  25. #include "json.hpp"
  26. #include "linenoise.cpp/linenoise.h"
  27. #include "llama-cpp.h"
  28. #include "log.h"
  29. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(_WIN32)
  30. [[noreturn]] static void sigint_handler(int) {
  31. printf("\n" LOG_COL_DEFAULT);
  32. exit(0); // not ideal, but it's the only way to guarantee exit in all cases
  33. }
  34. #endif
  35. GGML_ATTRIBUTE_FORMAT(1, 2)
  36. static int printe(const char * fmt, ...) {
  37. va_list args;
  38. va_start(args, fmt);
  39. const int ret = vfprintf(stderr, fmt, args);
  40. va_end(args);
  41. return ret;
  42. }
  43. static std::string strftime_fmt(const char * fmt, const std::tm & tm) {
  44. std::ostringstream oss;
  45. oss << std::put_time(&tm, fmt);
  46. return oss.str();
  47. }
  48. class Opt {
  49. public:
  50. int init(int argc, const char ** argv) {
  51. ctx_params = llama_context_default_params();
  52. model_params = llama_model_default_params();
  53. context_size_default = ctx_params.n_batch;
  54. n_threads_default = ctx_params.n_threads;
  55. ngl_default = model_params.n_gpu_layers;
  56. common_params_sampling sampling;
  57. temperature_default = sampling.temp;
  58. if (argc < 2) {
  59. printe("Error: No arguments provided.\n");
  60. print_help();
  61. return 1;
  62. }
  63. // Parse arguments
  64. if (parse(argc, argv)) {
  65. printe("Error: Failed to parse arguments.\n");
  66. print_help();
  67. return 1;
  68. }
  69. // If help is requested, show help and exit
  70. if (help) {
  71. print_help();
  72. return 2;
  73. }
  74. ctx_params.n_batch = context_size >= 0 ? context_size : context_size_default;
  75. ctx_params.n_ctx = ctx_params.n_batch;
  76. ctx_params.n_threads = ctx_params.n_threads_batch = n_threads >= 0 ? n_threads : n_threads_default;
  77. model_params.n_gpu_layers = ngl >= 0 ? ngl : ngl_default;
  78. temperature = temperature >= 0 ? temperature : temperature_default;
  79. return 0; // Success
  80. }
  81. llama_context_params ctx_params;
  82. llama_model_params model_params;
  83. std::string model_;
  84. std::string chat_template_file;
  85. std::string user;
  86. bool use_jinja = false;
  87. int context_size = -1, ngl = -1, n_threads = -1;
  88. float temperature = -1;
  89. bool verbose = false;
  90. private:
  91. int context_size_default = -1, ngl_default = -1, n_threads_default = -1;
  92. float temperature_default = -1;
  93. bool help = false;
  94. bool parse_flag(const char ** argv, int i, const char * short_opt, const char * long_opt) {
  95. return strcmp(argv[i], short_opt) == 0 || strcmp(argv[i], long_opt) == 0;
  96. }
  97. int handle_option_with_value(int argc, const char ** argv, int & i, int & option_value) {
  98. if (i + 1 >= argc) {
  99. return 1;
  100. }
  101. option_value = std::atoi(argv[++i]);
  102. return 0;
  103. }
  104. int handle_option_with_value(int argc, const char ** argv, int & i, float & option_value) {
  105. if (i + 1 >= argc) {
  106. return 1;
  107. }
  108. option_value = std::atof(argv[++i]);
  109. return 0;
  110. }
  111. int handle_option_with_value(int argc, const char ** argv, int & i, std::string & option_value) {
  112. if (i + 1 >= argc) {
  113. return 1;
  114. }
  115. option_value = argv[++i];
  116. return 0;
  117. }
  118. int parse_options_with_value(int argc, const char ** argv, int & i, bool & options_parsing) {
  119. if (options_parsing && (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--context-size") == 0)) {
  120. if (handle_option_with_value(argc, argv, i, context_size) == 1) {
  121. return 1;
  122. }
  123. } else if (options_parsing &&
  124. (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "-ngl") == 0 || strcmp(argv[i], "--ngl") == 0)) {
  125. if (handle_option_with_value(argc, argv, i, ngl) == 1) {
  126. return 1;
  127. }
  128. } else if (options_parsing && (strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--threads") == 0)) {
  129. if (handle_option_with_value(argc, argv, i, n_threads) == 1) {
  130. return 1;
  131. }
  132. } else if (options_parsing && strcmp(argv[i], "--temp") == 0) {
  133. if (handle_option_with_value(argc, argv, i, temperature) == 1) {
  134. return 1;
  135. }
  136. } else if (options_parsing && strcmp(argv[i], "--chat-template-file") == 0) {
  137. if (handle_option_with_value(argc, argv, i, chat_template_file) == 1) {
  138. return 1;
  139. }
  140. use_jinja = true;
  141. } else {
  142. return 2;
  143. }
  144. return 0;
  145. }
  146. int parse_options(const char ** argv, int & i, bool & options_parsing) {
  147. if (options_parsing && (parse_flag(argv, i, "-v", "--verbose") || parse_flag(argv, i, "-v", "--log-verbose"))) {
  148. verbose = true;
  149. } else if (options_parsing && strcmp(argv[i], "--jinja") == 0) {
  150. use_jinja = true;
  151. } else if (options_parsing && parse_flag(argv, i, "-h", "--help")) {
  152. help = true;
  153. return 0;
  154. } else if (options_parsing && strcmp(argv[i], "--") == 0) {
  155. options_parsing = false;
  156. } else {
  157. return 2;
  158. }
  159. return 0;
  160. }
  161. int parse_positional_args(const char ** argv, int & i, int & positional_args_i) {
  162. if (positional_args_i == 0) {
  163. if (!argv[i][0] || argv[i][0] == '-') {
  164. return 1;
  165. }
  166. ++positional_args_i;
  167. model_ = argv[i];
  168. } else if (positional_args_i == 1) {
  169. ++positional_args_i;
  170. user = argv[i];
  171. } else {
  172. user += " " + std::string(argv[i]);
  173. }
  174. return 0;
  175. }
  176. int parse(int argc, const char ** argv) {
  177. bool options_parsing = true;
  178. for (int i = 1, positional_args_i = 0; i < argc; ++i) {
  179. int ret = parse_options_with_value(argc, argv, i, options_parsing);
  180. if (ret == 0) {
  181. continue;
  182. } else if (ret == 1) {
  183. return ret;
  184. }
  185. ret = parse_options(argv, i, options_parsing);
  186. if (ret == 0) {
  187. continue;
  188. } else if (ret == 1) {
  189. return ret;
  190. }
  191. if (parse_positional_args(argv, i, positional_args_i)) {
  192. return 1;
  193. }
  194. }
  195. if (model_.empty()) {
  196. return 1;
  197. }
  198. return 0;
  199. }
  200. void print_help() const {
  201. printf(
  202. "Description:\n"
  203. " Runs a llm\n"
  204. "\n"
  205. "Usage:\n"
  206. " llama-run [options] model [prompt]\n"
  207. "\n"
  208. "Options:\n"
  209. " -c, --context-size <value>\n"
  210. " Context size (default: %d)\n"
  211. " --chat-template-file <path>\n"
  212. " Path to the file containing the chat template to use with the model.\n"
  213. " Only supports jinja templates and implicitly sets the --jinja flag.\n"
  214. " --jinja\n"
  215. " Use jinja templating for the chat template of the model\n"
  216. " -n, -ngl, --ngl <value>\n"
  217. " Number of GPU layers (default: %d)\n"
  218. " --temp <value>\n"
  219. " Temperature (default: %.1f)\n"
  220. " -t, --threads <value>\n"
  221. " Number of threads to use during generation (default: %d)\n"
  222. " -v, --verbose, --log-verbose\n"
  223. " Set verbosity level to infinity (i.e. log all messages, useful for debugging)\n"
  224. " -h, --help\n"
  225. " Show help message\n"
  226. "\n"
  227. "Commands:\n"
  228. " model\n"
  229. " Model is a string with an optional prefix of \n"
  230. " huggingface:// (hf://), ollama://, https:// or file://.\n"
  231. " If no protocol is specified and a file exists in the specified\n"
  232. " path, file:// is assumed, otherwise if a file does not exist in\n"
  233. " the specified path, ollama:// is assumed. Models that are being\n"
  234. " pulled are downloaded with .partial extension while being\n"
  235. " downloaded and then renamed as the file without the .partial\n"
  236. " extension when complete.\n"
  237. "\n"
  238. "Examples:\n"
  239. " llama-run llama3\n"
  240. " llama-run ollama://granite-code\n"
  241. " llama-run ollama://smollm:135m\n"
  242. " llama-run hf://QuantFactory/SmolLM-135M-GGUF/SmolLM-135M.Q2_K.gguf\n"
  243. " llama-run "
  244. "huggingface://bartowski/SmolLM-1.7B-Instruct-v0.2-GGUF/SmolLM-1.7B-Instruct-v0.2-IQ3_M.gguf\n"
  245. " llama-run https://example.com/some-file1.gguf\n"
  246. " llama-run some-file2.gguf\n"
  247. " llama-run file://some-file3.gguf\n"
  248. " llama-run --ngl 999 some-file4.gguf\n"
  249. " llama-run --ngl 999 some-file5.gguf Hello World\n",
  250. context_size_default, ngl_default, temperature_default, n_threads_default);
  251. }
  252. };
  253. struct progress_data {
  254. size_t file_size = 0;
  255. std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
  256. bool printed = false;
  257. };
  258. static int get_terminal_width() {
  259. #if defined(_WIN32)
  260. CONSOLE_SCREEN_BUFFER_INFO csbi;
  261. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
  262. return csbi.srWindow.Right - csbi.srWindow.Left + 1;
  263. #else
  264. struct winsize w;
  265. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  266. return w.ws_col;
  267. #endif
  268. }
  269. class File {
  270. public:
  271. FILE * file = nullptr;
  272. FILE * open(const std::string & filename, const char * mode) {
  273. file = ggml_fopen(filename.c_str(), mode);
  274. return file;
  275. }
  276. int lock() {
  277. if (file) {
  278. # ifdef _WIN32
  279. fd = _fileno(file);
  280. hFile = (HANDLE) _get_osfhandle(fd);
  281. if (hFile == INVALID_HANDLE_VALUE) {
  282. fd = -1;
  283. return 1;
  284. }
  285. OVERLAPPED overlapped = {};
  286. if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD,
  287. &overlapped)) {
  288. fd = -1;
  289. return 1;
  290. }
  291. # else
  292. fd = fileno(file);
  293. if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
  294. fd = -1;
  295. return 1;
  296. }
  297. # endif
  298. }
  299. return 0;
  300. }
  301. std::string to_string() {
  302. fseek(file, 0, SEEK_END);
  303. const size_t size = ftell(file);
  304. fseek(file, 0, SEEK_SET);
  305. std::string out;
  306. out.resize(size);
  307. const size_t read_size = fread(&out[0], 1, size, file);
  308. if (read_size != size) {
  309. printe("Error reading file: %s", strerror(errno));
  310. }
  311. return out;
  312. }
  313. ~File() {
  314. if (fd >= 0) {
  315. # ifdef _WIN32
  316. if (hFile != INVALID_HANDLE_VALUE) {
  317. OVERLAPPED overlapped = {};
  318. UnlockFileEx(hFile, 0, MAXDWORD, MAXDWORD, &overlapped);
  319. }
  320. # else
  321. flock(fd, LOCK_UN);
  322. # endif
  323. }
  324. if (file) {
  325. fclose(file);
  326. }
  327. }
  328. private:
  329. int fd = -1;
  330. # ifdef _WIN32
  331. HANDLE hFile = nullptr;
  332. # endif
  333. };
  334. #ifdef LLAMA_USE_CURL
  335. class HttpClient {
  336. public:
  337. int init(const std::string & url, const std::vector<std::string> & headers, const std::string & output_file,
  338. const bool progress, std::string * response_str = nullptr) {
  339. if (std::filesystem::exists(output_file)) {
  340. return 0;
  341. }
  342. std::string output_file_partial;
  343. curl = curl_easy_init();
  344. if (!curl) {
  345. return 1;
  346. }
  347. progress_data data;
  348. File out;
  349. if (!output_file.empty()) {
  350. output_file_partial = output_file + ".partial";
  351. if (!out.open(output_file_partial, "ab")) {
  352. printe("Failed to open file for writing\n");
  353. return 1;
  354. }
  355. if (out.lock()) {
  356. printe("Failed to exclusively lock file\n");
  357. return 1;
  358. }
  359. }
  360. set_write_options(response_str, out);
  361. data.file_size = set_resume_point(output_file_partial);
  362. set_progress_options(progress, data);
  363. set_headers(headers);
  364. CURLcode res = perform(url);
  365. if (res != CURLE_OK){
  366. printe("Fetching resource '%s' failed: %s\n", url.c_str(), curl_easy_strerror(res));
  367. return 1;
  368. }
  369. if (!output_file.empty()) {
  370. std::filesystem::rename(output_file_partial, output_file);
  371. }
  372. return 0;
  373. }
  374. ~HttpClient() {
  375. if (chunk) {
  376. curl_slist_free_all(chunk);
  377. }
  378. if (curl) {
  379. curl_easy_cleanup(curl);
  380. }
  381. }
  382. private:
  383. CURL * curl = nullptr;
  384. struct curl_slist * chunk = nullptr;
  385. void set_write_options(std::string * response_str, const File & out) {
  386. if (response_str) {
  387. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, capture_data);
  388. curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_str);
  389. } else {
  390. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  391. curl_easy_setopt(curl, CURLOPT_WRITEDATA, out.file);
  392. }
  393. }
  394. size_t set_resume_point(const std::string & output_file) {
  395. size_t file_size = 0;
  396. if (std::filesystem::exists(output_file)) {
  397. file_size = std::filesystem::file_size(output_file);
  398. curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, static_cast<curl_off_t>(file_size));
  399. }
  400. return file_size;
  401. }
  402. void set_progress_options(bool progress, progress_data & data) {
  403. if (progress) {
  404. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  405. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &data);
  406. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, update_progress);
  407. }
  408. }
  409. void set_headers(const std::vector<std::string> & headers) {
  410. if (!headers.empty()) {
  411. if (chunk) {
  412. curl_slist_free_all(chunk);
  413. chunk = 0;
  414. }
  415. for (const auto & header : headers) {
  416. chunk = curl_slist_append(chunk, header.c_str());
  417. }
  418. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  419. }
  420. }
  421. CURLcode perform(const std::string & url) {
  422. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  423. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  424. curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  425. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
  426. return curl_easy_perform(curl);
  427. }
  428. static std::string human_readable_time(double seconds) {
  429. int hrs = static_cast<int>(seconds) / 3600;
  430. int mins = (static_cast<int>(seconds) % 3600) / 60;
  431. int secs = static_cast<int>(seconds) % 60;
  432. if (hrs > 0) {
  433. return string_format("%dh %02dm %02ds", hrs, mins, secs);
  434. } else if (mins > 0) {
  435. return string_format("%dm %02ds", mins, secs);
  436. } else {
  437. return string_format("%ds", secs);
  438. }
  439. }
  440. static std::string human_readable_size(curl_off_t size) {
  441. static const char * suffix[] = { "B", "KB", "MB", "GB", "TB" };
  442. char length = sizeof(suffix) / sizeof(suffix[0]);
  443. int i = 0;
  444. double dbl_size = size;
  445. if (size > 1024) {
  446. for (i = 0; (size / 1024) > 0 && i < length - 1; i++, size /= 1024) {
  447. dbl_size = size / 1024.0;
  448. }
  449. }
  450. return string_format("%.2f %s", dbl_size, suffix[i]);
  451. }
  452. static int update_progress(void * ptr, curl_off_t total_to_download, curl_off_t now_downloaded, curl_off_t,
  453. curl_off_t) {
  454. progress_data * data = static_cast<progress_data *>(ptr);
  455. if (total_to_download <= 0) {
  456. return 0;
  457. }
  458. total_to_download += data->file_size;
  459. const curl_off_t now_downloaded_plus_file_size = now_downloaded + data->file_size;
  460. const curl_off_t percentage = calculate_percentage(now_downloaded_plus_file_size, total_to_download);
  461. std::string progress_prefix = generate_progress_prefix(percentage);
  462. const double speed = calculate_speed(now_downloaded, data->start_time);
  463. const double tim = (total_to_download - now_downloaded) / speed;
  464. std::string progress_suffix =
  465. generate_progress_suffix(now_downloaded_plus_file_size, total_to_download, speed, tim);
  466. int progress_bar_width = calculate_progress_bar_width(progress_prefix, progress_suffix);
  467. std::string progress_bar;
  468. generate_progress_bar(progress_bar_width, percentage, progress_bar);
  469. print_progress(progress_prefix, progress_bar, progress_suffix);
  470. data->printed = true;
  471. return 0;
  472. }
  473. static curl_off_t calculate_percentage(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download) {
  474. return (now_downloaded_plus_file_size * 100) / total_to_download;
  475. }
  476. static std::string generate_progress_prefix(curl_off_t percentage) {
  477. return string_format("%3ld%% |", static_cast<long int>(percentage));
  478. }
  479. static double calculate_speed(curl_off_t now_downloaded, const std::chrono::steady_clock::time_point & start_time) {
  480. const auto now = std::chrono::steady_clock::now();
  481. const std::chrono::duration<double> elapsed_seconds = now - start_time;
  482. return now_downloaded / elapsed_seconds.count();
  483. }
  484. static std::string generate_progress_suffix(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download,
  485. double speed, double estimated_time) {
  486. const int width = 10;
  487. return string_format("%*s/%*s%*s/s%*s", width, human_readable_size(now_downloaded_plus_file_size).c_str(),
  488. width, human_readable_size(total_to_download).c_str(), width,
  489. human_readable_size(speed).c_str(), width, human_readable_time(estimated_time).c_str());
  490. }
  491. static int calculate_progress_bar_width(const std::string & progress_prefix, const std::string & progress_suffix) {
  492. int progress_bar_width = get_terminal_width() - progress_prefix.size() - progress_suffix.size() - 3;
  493. if (progress_bar_width < 1) {
  494. progress_bar_width = 1;
  495. }
  496. return progress_bar_width;
  497. }
  498. static std::string generate_progress_bar(int progress_bar_width, curl_off_t percentage,
  499. std::string & progress_bar) {
  500. const curl_off_t pos = (percentage * progress_bar_width) / 100;
  501. for (int i = 0; i < progress_bar_width; ++i) {
  502. progress_bar.append((i < pos) ? "█" : " ");
  503. }
  504. return progress_bar;
  505. }
  506. static void print_progress(const std::string & progress_prefix, const std::string & progress_bar,
  507. const std::string & progress_suffix) {
  508. printe("\r" LOG_CLR_TO_EOL "%s%s| %s", progress_prefix.c_str(), progress_bar.c_str(), progress_suffix.c_str());
  509. }
  510. // Function to write data to a file
  511. static size_t write_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  512. FILE * out = static_cast<FILE *>(stream);
  513. return fwrite(ptr, size, nmemb, out);
  514. }
  515. // Function to capture data into a string
  516. static size_t capture_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  517. std::string * str = static_cast<std::string *>(stream);
  518. str->append(static_cast<char *>(ptr), size * nmemb);
  519. return size * nmemb;
  520. }
  521. };
  522. #endif
  523. class LlamaData {
  524. public:
  525. llama_model_ptr model;
  526. llama_sampler_ptr sampler;
  527. llama_context_ptr context;
  528. std::vector<llama_chat_message> messages; // TODO: switch to common_chat_msg
  529. std::list<std::string> msg_strs;
  530. std::vector<char> fmtted;
  531. int init(Opt & opt) {
  532. model = initialize_model(opt);
  533. if (!model) {
  534. return 1;
  535. }
  536. context = initialize_context(model, opt);
  537. if (!context) {
  538. return 1;
  539. }
  540. sampler = initialize_sampler(opt);
  541. return 0;
  542. }
  543. private:
  544. #ifdef LLAMA_USE_CURL
  545. int download(const std::string & url, const std::string & output_file, const bool progress,
  546. const std::vector<std::string> & headers = {}, std::string * response_str = nullptr) {
  547. HttpClient http;
  548. if (http.init(url, headers, output_file, progress, response_str)) {
  549. return 1;
  550. }
  551. return 0;
  552. }
  553. #else
  554. int download(const std::string &, const std::string &, const bool, const std::vector<std::string> & = {},
  555. std::string * = nullptr) {
  556. printe("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  557. return 1;
  558. }
  559. #endif
  560. // Helper function to handle model tag extraction and URL construction
  561. std::pair<std::string, std::string> extract_model_and_tag(std::string & model, const std::string & base_url) {
  562. std::string model_tag = "latest";
  563. const size_t colon_pos = model.find(':');
  564. if (colon_pos != std::string::npos) {
  565. model_tag = model.substr(colon_pos + 1);
  566. model = model.substr(0, colon_pos);
  567. }
  568. std::string url = base_url + model + "/manifests/" + model_tag;
  569. return { model, url };
  570. }
  571. // Helper function to download and parse the manifest
  572. int download_and_parse_manifest(const std::string & url, const std::vector<std::string> & headers,
  573. nlohmann::json & manifest) {
  574. std::string manifest_str;
  575. int ret = download(url, "", false, headers, &manifest_str);
  576. if (ret) {
  577. return ret;
  578. }
  579. manifest = nlohmann::json::parse(manifest_str);
  580. return 0;
  581. }
  582. int huggingface_dl(std::string & model, const std::string & bn) {
  583. // Find the second occurrence of '/' after protocol string
  584. size_t pos = model.find('/');
  585. pos = model.find('/', pos + 1);
  586. std::string hfr, hff;
  587. std::vector<std::string> headers = { "User-Agent: llama-cpp", "Accept: application/json" };
  588. std::string url;
  589. if (pos == std::string::npos) {
  590. auto [model_name, manifest_url] = extract_model_and_tag(model, "https://huggingface.co/v2/");
  591. hfr = model_name;
  592. nlohmann::json manifest;
  593. int ret = download_and_parse_manifest(manifest_url, headers, manifest);
  594. if (ret) {
  595. return ret;
  596. }
  597. hff = manifest["ggufFile"]["rfilename"];
  598. } else {
  599. hfr = model.substr(0, pos);
  600. hff = model.substr(pos + 1);
  601. }
  602. url = "https://huggingface.co/" + hfr + "/resolve/main/" + hff;
  603. return download(url, bn, true, headers);
  604. }
  605. int ollama_dl(std::string & model, const std::string & bn) {
  606. const std::vector<std::string> headers = { "Accept: application/vnd.docker.distribution.manifest.v2+json" };
  607. if (model.find('/') == std::string::npos) {
  608. model = "library/" + model;
  609. }
  610. auto [model_name, manifest_url] = extract_model_and_tag(model, "https://registry.ollama.ai/v2/");
  611. nlohmann::json manifest;
  612. int ret = download_and_parse_manifest(manifest_url, {}, manifest);
  613. if (ret) {
  614. return ret;
  615. }
  616. std::string layer;
  617. for (const auto & l : manifest["layers"]) {
  618. if (l["mediaType"] == "application/vnd.ollama.image.model") {
  619. layer = l["digest"];
  620. break;
  621. }
  622. }
  623. std::string blob_url = "https://registry.ollama.ai/v2/" + model_name + "/blobs/" + layer;
  624. return download(blob_url, bn, true, headers);
  625. }
  626. int github_dl(const std::string & model, const std::string & bn) {
  627. std::string repository = model;
  628. std::string branch = "main";
  629. const size_t at_pos = model.find('@');
  630. if (at_pos != std::string::npos) {
  631. repository = model.substr(0, at_pos);
  632. branch = model.substr(at_pos + 1);
  633. }
  634. const std::vector<std::string> repo_parts = string_split(repository, "/");
  635. if (repo_parts.size() < 3) {
  636. printe("Invalid GitHub repository format\n");
  637. return 1;
  638. }
  639. const std::string & org = repo_parts[0];
  640. const std::string & project = repo_parts[1];
  641. std::string url = "https://raw.githubusercontent.com/" + org + "/" + project + "/" + branch;
  642. for (size_t i = 2; i < repo_parts.size(); ++i) {
  643. url += "/" + repo_parts[i];
  644. }
  645. return download(url, bn, true);
  646. }
  647. int s3_dl(const std::string & model, const std::string & bn) {
  648. const size_t slash_pos = model.find('/');
  649. if (slash_pos == std::string::npos) {
  650. return 1;
  651. }
  652. const std::string bucket = model.substr(0, slash_pos);
  653. const std::string key = model.substr(slash_pos + 1);
  654. const char * access_key = std::getenv("AWS_ACCESS_KEY_ID");
  655. const char * secret_key = std::getenv("AWS_SECRET_ACCESS_KEY");
  656. if (!access_key || !secret_key) {
  657. printe("AWS credentials not found in environment\n");
  658. return 1;
  659. }
  660. // Generate AWS Signature Version 4 headers
  661. // (Implementation requires HMAC-SHA256 and date handling)
  662. // Get current timestamp
  663. const time_t now = time(nullptr);
  664. const tm tm = *gmtime(&now);
  665. const std::string date = strftime_fmt("%Y%m%d", tm);
  666. const std::string datetime = strftime_fmt("%Y%m%dT%H%M%SZ", tm);
  667. const std::vector<std::string> headers = {
  668. "Authorization: AWS4-HMAC-SHA256 Credential=" + std::string(access_key) + "/" + date +
  669. "/us-east-1/s3/aws4_request",
  670. "x-amz-content-sha256: UNSIGNED-PAYLOAD", "x-amz-date: " + datetime
  671. };
  672. const std::string url = "https://" + bucket + ".s3.amazonaws.com/" + key;
  673. return download(url, bn, true, headers);
  674. }
  675. std::string basename(const std::string & path) {
  676. const size_t pos = path.find_last_of("/\\");
  677. if (pos == std::string::npos) {
  678. return path;
  679. }
  680. return path.substr(pos + 1);
  681. }
  682. int rm_until_substring(std::string & model_, const std::string & substring) {
  683. const std::string::size_type pos = model_.find(substring);
  684. if (pos == std::string::npos) {
  685. return 1;
  686. }
  687. model_ = model_.substr(pos + substring.size()); // Skip past the substring
  688. return 0;
  689. }
  690. int resolve_model(std::string & model_) {
  691. int ret = 0;
  692. if (string_starts_with(model_, "file://") || std::filesystem::exists(model_)) {
  693. rm_until_substring(model_, "://");
  694. return ret;
  695. }
  696. const std::string bn = basename(model_);
  697. if (string_starts_with(model_, "hf://") || string_starts_with(model_, "huggingface://") ||
  698. string_starts_with(model_, "hf.co/")) {
  699. rm_until_substring(model_, "hf.co/");
  700. rm_until_substring(model_, "://");
  701. ret = huggingface_dl(model_, bn);
  702. } else if ((string_starts_with(model_, "https://") || string_starts_with(model_, "http://")) &&
  703. !string_starts_with(model_, "https://ollama.com/library/")) {
  704. ret = download(model_, bn, true);
  705. } else if (string_starts_with(model_, "github:") || string_starts_with(model_, "github://")) {
  706. rm_until_substring(model_, "github:");
  707. rm_until_substring(model_, "://");
  708. ret = github_dl(model_, bn);
  709. } else if (string_starts_with(model_, "s3://")) {
  710. rm_until_substring(model_, "://");
  711. ret = s3_dl(model_, bn);
  712. } else { // ollama:// or nothing
  713. rm_until_substring(model_, "ollama.com/library/");
  714. rm_until_substring(model_, "://");
  715. ret = ollama_dl(model_, bn);
  716. }
  717. model_ = bn;
  718. return ret;
  719. }
  720. // Initializes the model and returns a unique pointer to it
  721. llama_model_ptr initialize_model(Opt & opt) {
  722. ggml_backend_load_all();
  723. resolve_model(opt.model_);
  724. printe("\r" LOG_CLR_TO_EOL "Loading model");
  725. llama_model_ptr model(llama_model_load_from_file(opt.model_.c_str(), opt.model_params));
  726. if (!model) {
  727. printe("%s: error: unable to load model from file: %s\n", __func__, opt.model_.c_str());
  728. }
  729. printe("\r" LOG_CLR_TO_EOL);
  730. return model;
  731. }
  732. // Initializes the context with the specified parameters
  733. llama_context_ptr initialize_context(const llama_model_ptr & model, const Opt & opt) {
  734. llama_context_ptr context(llama_init_from_model(model.get(), opt.ctx_params));
  735. if (!context) {
  736. printe("%s: error: failed to create the llama_context\n", __func__);
  737. }
  738. return context;
  739. }
  740. // Initializes and configures the sampler
  741. llama_sampler_ptr initialize_sampler(const Opt & opt) {
  742. llama_sampler_ptr sampler(llama_sampler_chain_init(llama_sampler_chain_default_params()));
  743. llama_sampler_chain_add(sampler.get(), llama_sampler_init_min_p(0.05f, 1));
  744. llama_sampler_chain_add(sampler.get(), llama_sampler_init_temp(opt.temperature));
  745. llama_sampler_chain_add(sampler.get(), llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
  746. return sampler;
  747. }
  748. };
  749. // Add a message to `messages` and store its content in `msg_strs`
  750. static void add_message(const char * role, const std::string & text, LlamaData & llama_data) {
  751. llama_data.msg_strs.push_back(std::move(text));
  752. llama_data.messages.push_back({ role, llama_data.msg_strs.back().c_str() });
  753. }
  754. // Function to apply the chat template and resize `formatted` if needed
  755. static int apply_chat_template(const struct common_chat_templates * tmpls, LlamaData & llama_data, const bool append, bool use_jinja) {
  756. common_chat_templates_inputs inputs;
  757. for (const auto & msg : llama_data.messages) {
  758. common_chat_msg cmsg;
  759. cmsg.role = msg.role;
  760. cmsg.content = msg.content;
  761. inputs.messages.push_back(cmsg);
  762. }
  763. inputs.add_generation_prompt = append;
  764. inputs.use_jinja = use_jinja;
  765. auto chat_params = common_chat_templates_apply(tmpls, inputs);
  766. // TODO: use other params for tool calls.
  767. auto result = chat_params.prompt;
  768. llama_data.fmtted.resize(result.size() + 1);
  769. memcpy(llama_data.fmtted.data(), result.c_str(), result.size() + 1);
  770. return result.size();
  771. }
  772. // Function to tokenize the prompt
  773. static int tokenize_prompt(const llama_vocab * vocab, const std::string & prompt,
  774. std::vector<llama_token> & prompt_tokens, const LlamaData & llama_data) {
  775. const bool is_first = llama_kv_self_used_cells(llama_data.context.get()) == 0;
  776. const int n_prompt_tokens = -llama_tokenize(vocab, prompt.c_str(), prompt.size(), NULL, 0, is_first, true);
  777. prompt_tokens.resize(n_prompt_tokens);
  778. if (llama_tokenize(vocab, prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), is_first,
  779. true) < 0) {
  780. printe("failed to tokenize the prompt\n");
  781. return -1;
  782. }
  783. return n_prompt_tokens;
  784. }
  785. // Check if we have enough space in the context to evaluate this batch
  786. static int check_context_size(const llama_context_ptr & ctx, const llama_batch & batch) {
  787. const int n_ctx = llama_n_ctx(ctx.get());
  788. const int n_ctx_used = llama_kv_self_used_cells(ctx.get());
  789. if (n_ctx_used + batch.n_tokens > n_ctx) {
  790. printf(LOG_COL_DEFAULT "\n");
  791. printe("context size exceeded\n");
  792. return 1;
  793. }
  794. return 0;
  795. }
  796. // convert the token to a string
  797. static int convert_token_to_string(const llama_vocab * vocab, const llama_token token_id, std::string & piece) {
  798. char buf[256];
  799. int n = llama_token_to_piece(vocab, token_id, buf, sizeof(buf), 0, true);
  800. if (n < 0) {
  801. printe("failed to convert token to piece\n");
  802. return 1;
  803. }
  804. piece = std::string(buf, n);
  805. return 0;
  806. }
  807. static void print_word_and_concatenate_to_response(const std::string & piece, std::string & response) {
  808. printf("%s", piece.c_str());
  809. fflush(stdout);
  810. response += piece;
  811. }
  812. // helper function to evaluate a prompt and generate a response
  813. static int generate(LlamaData & llama_data, const std::string & prompt, std::string & response) {
  814. const llama_vocab * vocab = llama_model_get_vocab(llama_data.model.get());
  815. std::vector<llama_token> tokens;
  816. if (tokenize_prompt(vocab, prompt, tokens, llama_data) < 0) {
  817. return 1;
  818. }
  819. // prepare a batch for the prompt
  820. llama_batch batch = llama_batch_get_one(tokens.data(), tokens.size());
  821. llama_token new_token_id;
  822. while (true) {
  823. check_context_size(llama_data.context, batch);
  824. if (llama_decode(llama_data.context.get(), batch)) {
  825. printe("failed to decode\n");
  826. return 1;
  827. }
  828. // sample the next token, check is it an end of generation?
  829. new_token_id = llama_sampler_sample(llama_data.sampler.get(), llama_data.context.get(), -1);
  830. if (llama_vocab_is_eog(vocab, new_token_id)) {
  831. break;
  832. }
  833. std::string piece;
  834. if (convert_token_to_string(vocab, new_token_id, piece)) {
  835. return 1;
  836. }
  837. print_word_and_concatenate_to_response(piece, response);
  838. // prepare the next batch with the sampled token
  839. batch = llama_batch_get_one(&new_token_id, 1);
  840. }
  841. printf(LOG_COL_DEFAULT);
  842. return 0;
  843. }
  844. static int read_user_input(std::string & user_input) {
  845. static const char * prompt_prefix_env = std::getenv("LLAMA_PROMPT_PREFIX");
  846. static const char * prompt_prefix = prompt_prefix_env ? prompt_prefix_env : "> ";
  847. #ifdef WIN32
  848. printf("\r" LOG_CLR_TO_EOL LOG_COL_DEFAULT "%s", prompt_prefix);
  849. std::getline(std::cin, user_input);
  850. if (std::cin.eof()) {
  851. printf("\n");
  852. return 1;
  853. }
  854. #else
  855. std::unique_ptr<char, decltype(&std::free)> line(const_cast<char *>(linenoise(prompt_prefix)), free);
  856. if (!line) {
  857. return 1;
  858. }
  859. user_input = line.get();
  860. #endif
  861. if (user_input == "/bye") {
  862. return 1;
  863. }
  864. if (user_input.empty()) {
  865. return 2;
  866. }
  867. #ifndef WIN32
  868. linenoiseHistoryAdd(line.get());
  869. #endif
  870. return 0; // Should have data in happy path
  871. }
  872. // Function to generate a response based on the prompt
  873. static int generate_response(LlamaData & llama_data, const std::string & prompt, std::string & response,
  874. const bool stdout_a_terminal) {
  875. // Set response color
  876. if (stdout_a_terminal) {
  877. printf(LOG_COL_YELLOW);
  878. }
  879. if (generate(llama_data, prompt, response)) {
  880. printe("failed to generate response\n");
  881. return 1;
  882. }
  883. // End response with color reset and newline
  884. printf("\n%s", stdout_a_terminal ? LOG_COL_DEFAULT : "");
  885. return 0;
  886. }
  887. // Helper function to apply the chat template and handle errors
  888. static int apply_chat_template_with_error_handling(const common_chat_templates * tmpls, LlamaData & llama_data, const bool append, int & output_length, bool use_jinja) {
  889. const int new_len = apply_chat_template(tmpls, llama_data, append, use_jinja);
  890. if (new_len < 0) {
  891. printe("failed to apply the chat template\n");
  892. return -1;
  893. }
  894. output_length = new_len;
  895. return 0;
  896. }
  897. // Helper function to handle user input
  898. static int handle_user_input(std::string & user_input, const std::string & user) {
  899. if (!user.empty()) {
  900. user_input = user;
  901. return 0; // No need for interactive input
  902. }
  903. return read_user_input(user_input); // Returns true if input ends the loop
  904. }
  905. static bool is_stdin_a_terminal() {
  906. #if defined(_WIN32)
  907. HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
  908. DWORD mode;
  909. return GetConsoleMode(hStdin, &mode);
  910. #else
  911. return isatty(STDIN_FILENO);
  912. #endif
  913. }
  914. static bool is_stdout_a_terminal() {
  915. #if defined(_WIN32)
  916. HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  917. DWORD mode;
  918. return GetConsoleMode(hStdout, &mode);
  919. #else
  920. return isatty(STDOUT_FILENO);
  921. #endif
  922. }
  923. // Function to handle user input
  924. static int get_user_input(std::string & user_input, const std::string & user) {
  925. while (true) {
  926. const int ret = handle_user_input(user_input, user);
  927. if (ret == 1) {
  928. return 1;
  929. }
  930. if (ret == 2) {
  931. continue;
  932. }
  933. break;
  934. }
  935. return 0;
  936. }
  937. // Reads a chat template file to be used
  938. static std::string read_chat_template_file(const std::string & chat_template_file) {
  939. File file;
  940. if (!file.open(chat_template_file, "r")) {
  941. printe("Error opening chat template file '%s': %s", chat_template_file.c_str(), strerror(errno));
  942. return "";
  943. }
  944. return file.to_string();
  945. }
  946. static int process_user_message(const Opt & opt, const std::string & user_input, LlamaData & llama_data,
  947. const common_chat_templates_ptr & chat_templates, int & prev_len,
  948. const bool stdout_a_terminal) {
  949. add_message("user", opt.user.empty() ? user_input : opt.user, llama_data);
  950. int new_len;
  951. if (apply_chat_template_with_error_handling(chat_templates.get(), llama_data, true, new_len, opt.use_jinja) < 0) {
  952. return 1;
  953. }
  954. std::string prompt(llama_data.fmtted.begin() + prev_len, llama_data.fmtted.begin() + new_len);
  955. std::string response;
  956. if (generate_response(llama_data, prompt, response, stdout_a_terminal)) {
  957. return 1;
  958. }
  959. if (!opt.user.empty()) {
  960. return 2;
  961. }
  962. add_message("assistant", response, llama_data);
  963. if (apply_chat_template_with_error_handling(chat_templates.get(), llama_data, false, prev_len, opt.use_jinja) < 0) {
  964. return 1;
  965. }
  966. return 0;
  967. }
  968. // Main chat loop function
  969. static int chat_loop(LlamaData & llama_data, const Opt & opt) {
  970. int prev_len = 0;
  971. llama_data.fmtted.resize(llama_n_ctx(llama_data.context.get()));
  972. std::string chat_template;
  973. if (!opt.chat_template_file.empty()) {
  974. chat_template = read_chat_template_file(opt.chat_template_file);
  975. }
  976. common_chat_templates_ptr chat_templates = common_chat_templates_init(llama_data.model.get(), chat_template);
  977. static const bool stdout_a_terminal = is_stdout_a_terminal();
  978. while (true) {
  979. // Get user input
  980. std::string user_input;
  981. if (get_user_input(user_input, opt.user) == 1) {
  982. return 0;
  983. }
  984. const int ret = process_user_message(opt, user_input, llama_data, chat_templates, prev_len, stdout_a_terminal);
  985. if (ret == 1) {
  986. return 1;
  987. } else if (ret == 2) {
  988. break;
  989. }
  990. }
  991. return 0;
  992. }
  993. static void log_callback(const enum ggml_log_level level, const char * text, void * p) {
  994. const Opt * opt = static_cast<Opt *>(p);
  995. if (opt->verbose || level == GGML_LOG_LEVEL_ERROR) {
  996. printe("%s", text);
  997. }
  998. }
  999. static std::string read_pipe_data() {
  1000. std::ostringstream result;
  1001. result << std::cin.rdbuf(); // Read all data from std::cin
  1002. return result.str();
  1003. }
  1004. static void ctrl_c_handling() {
  1005. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  1006. struct sigaction sigint_action;
  1007. sigint_action.sa_handler = sigint_handler;
  1008. sigemptyset(&sigint_action.sa_mask);
  1009. sigint_action.sa_flags = 0;
  1010. sigaction(SIGINT, &sigint_action, NULL);
  1011. #elif defined(_WIN32)
  1012. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  1013. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  1014. };
  1015. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  1016. #endif
  1017. }
  1018. int main(int argc, const char ** argv) {
  1019. ctrl_c_handling();
  1020. Opt opt;
  1021. const int ret = opt.init(argc, argv);
  1022. if (ret == 2) {
  1023. return 0;
  1024. } else if (ret) {
  1025. return 1;
  1026. }
  1027. if (!is_stdin_a_terminal()) {
  1028. if (!opt.user.empty()) {
  1029. opt.user += "\n\n";
  1030. }
  1031. opt.user += read_pipe_data();
  1032. }
  1033. llama_log_set(log_callback, &opt);
  1034. LlamaData llama_data;
  1035. if (llama_data.init(opt)) {
  1036. return 1;
  1037. }
  1038. if (chat_loop(llama_data, opt)) {
  1039. return 1;
  1040. }
  1041. return 0;
  1042. }