run.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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 <sstream>
  20. #include <string>
  21. #include <vector>
  22. #include "common.h"
  23. #include "json.hpp"
  24. #include "llama-cpp.h"
  25. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(_WIN32)
  26. [[noreturn]] static void sigint_handler(int) {
  27. printf("\n");
  28. exit(0); // not ideal, but it's the only way to guarantee exit in all cases
  29. }
  30. #endif
  31. GGML_ATTRIBUTE_FORMAT(1, 2)
  32. static std::string fmt(const char * fmt, ...) {
  33. va_list ap;
  34. va_list ap2;
  35. va_start(ap, fmt);
  36. va_copy(ap2, ap);
  37. const int size = vsnprintf(NULL, 0, fmt, ap);
  38. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  39. std::string buf;
  40. buf.resize(size);
  41. const int size2 = vsnprintf(const_cast<char *>(buf.data()), buf.size() + 1, fmt, ap2);
  42. GGML_ASSERT(size2 == size);
  43. va_end(ap2);
  44. va_end(ap);
  45. return buf;
  46. }
  47. GGML_ATTRIBUTE_FORMAT(1, 2)
  48. static int printe(const char * fmt, ...) {
  49. va_list args;
  50. va_start(args, fmt);
  51. const int ret = vfprintf(stderr, fmt, args);
  52. va_end(args);
  53. return ret;
  54. }
  55. class Opt {
  56. public:
  57. int init(int argc, const char ** argv) {
  58. ctx_params = llama_context_default_params();
  59. model_params = llama_model_default_params();
  60. context_size_default = ctx_params.n_batch;
  61. ngl_default = model_params.n_gpu_layers;
  62. common_params_sampling sampling;
  63. temperature_default = sampling.temp;
  64. if (argc < 2) {
  65. printe("Error: No arguments provided.\n");
  66. print_help();
  67. return 1;
  68. }
  69. // Parse arguments
  70. if (parse(argc, argv)) {
  71. printe("Error: Failed to parse arguments.\n");
  72. print_help();
  73. return 1;
  74. }
  75. // If help is requested, show help and exit
  76. if (help) {
  77. print_help();
  78. return 2;
  79. }
  80. ctx_params.n_batch = context_size >= 0 ? context_size : context_size_default;
  81. ctx_params.n_ctx = ctx_params.n_batch;
  82. model_params.n_gpu_layers = ngl >= 0 ? ngl : ngl_default;
  83. temperature = temperature >= 0 ? temperature : temperature_default;
  84. return 0; // Success
  85. }
  86. llama_context_params ctx_params;
  87. llama_model_params model_params;
  88. std::string model_;
  89. std::string user;
  90. int context_size = -1, ngl = -1;
  91. float temperature = -1;
  92. bool verbose = false;
  93. private:
  94. int context_size_default = -1, ngl_default = -1;
  95. float temperature_default = -1;
  96. bool help = false;
  97. bool parse_flag(const char ** argv, int i, const char * short_opt, const char * long_opt) {
  98. return strcmp(argv[i], short_opt) == 0 || strcmp(argv[i], long_opt) == 0;
  99. }
  100. int handle_option_with_value(int argc, const char ** argv, int & i, int & option_value) {
  101. if (i + 1 >= argc) {
  102. return 1;
  103. }
  104. option_value = std::atoi(argv[++i]);
  105. return 0;
  106. }
  107. int handle_option_with_value(int argc, const char ** argv, int & i, float & option_value) {
  108. if (i + 1 >= argc) {
  109. return 1;
  110. }
  111. option_value = std::atof(argv[++i]);
  112. return 0;
  113. }
  114. int parse(int argc, const char ** argv) {
  115. bool options_parsing = true;
  116. for (int i = 1, positional_args_i = 0; i < argc; ++i) {
  117. if (options_parsing && (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--context-size") == 0)) {
  118. if (handle_option_with_value(argc, argv, i, context_size) == 1) {
  119. return 1;
  120. }
  121. } else if (options_parsing && (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--ngl") == 0)) {
  122. if (handle_option_with_value(argc, argv, i, ngl) == 1) {
  123. return 1;
  124. }
  125. } else if (options_parsing && strcmp(argv[i], "--temp") == 0) {
  126. if (handle_option_with_value(argc, argv, i, temperature) == 1) {
  127. return 1;
  128. }
  129. } else if (options_parsing &&
  130. (parse_flag(argv, i, "-v", "--verbose") || parse_flag(argv, i, "-v", "--log-verbose"))) {
  131. verbose = true;
  132. } else if (options_parsing && parse_flag(argv, i, "-h", "--help")) {
  133. help = true;
  134. return 0;
  135. } else if (options_parsing && strcmp(argv[i], "--") == 0) {
  136. options_parsing = false;
  137. } else if (positional_args_i == 0) {
  138. if (!argv[i][0] || argv[i][0] == '-') {
  139. return 1;
  140. }
  141. ++positional_args_i;
  142. model_ = argv[i];
  143. } else if (positional_args_i == 1) {
  144. ++positional_args_i;
  145. user = argv[i];
  146. } else {
  147. user += " " + std::string(argv[i]);
  148. }
  149. }
  150. return 0;
  151. }
  152. void print_help() const {
  153. printf(
  154. "Description:\n"
  155. " Runs a llm\n"
  156. "\n"
  157. "Usage:\n"
  158. " llama-run [options] model [prompt]\n"
  159. "\n"
  160. "Options:\n"
  161. " -c, --context-size <value>\n"
  162. " Context size (default: %d)\n"
  163. " -n, --ngl <value>\n"
  164. " Number of GPU layers (default: %d)\n"
  165. " --temp <value>\n"
  166. " Temperature (default: %.1f)\n"
  167. " -v, --verbose, --log-verbose\n"
  168. " Set verbosity level to infinity (i.e. log all messages, useful for debugging)\n"
  169. " -h, --help\n"
  170. " Show help message\n"
  171. "\n"
  172. "Commands:\n"
  173. " model\n"
  174. " Model is a string with an optional prefix of \n"
  175. " huggingface:// (hf://), ollama://, https:// or file://.\n"
  176. " If no protocol is specified and a file exists in the specified\n"
  177. " path, file:// is assumed, otherwise if a file does not exist in\n"
  178. " the specified path, ollama:// is assumed. Models that are being\n"
  179. " pulled are downloaded with .partial extension while being\n"
  180. " downloaded and then renamed as the file without the .partial\n"
  181. " extension when complete.\n"
  182. "\n"
  183. "Examples:\n"
  184. " llama-run llama3\n"
  185. " llama-run ollama://granite-code\n"
  186. " llama-run ollama://smollm:135m\n"
  187. " llama-run hf://QuantFactory/SmolLM-135M-GGUF/SmolLM-135M.Q2_K.gguf\n"
  188. " llama-run "
  189. "huggingface://bartowski/SmolLM-1.7B-Instruct-v0.2-GGUF/SmolLM-1.7B-Instruct-v0.2-IQ3_M.gguf\n"
  190. " llama-run https://example.com/some-file1.gguf\n"
  191. " llama-run some-file2.gguf\n"
  192. " llama-run file://some-file3.gguf\n"
  193. " llama-run --ngl 999 some-file4.gguf\n"
  194. " llama-run --ngl 999 some-file5.gguf Hello World\n",
  195. context_size_default, ngl_default, temperature_default);
  196. }
  197. };
  198. struct progress_data {
  199. size_t file_size = 0;
  200. std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
  201. bool printed = false;
  202. };
  203. static int get_terminal_width() {
  204. #if defined(_WIN32)
  205. CONSOLE_SCREEN_BUFFER_INFO csbi;
  206. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
  207. return csbi.srWindow.Right - csbi.srWindow.Left + 1;
  208. #else
  209. struct winsize w;
  210. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  211. return w.ws_col;
  212. #endif
  213. }
  214. #ifdef LLAMA_USE_CURL
  215. class File {
  216. public:
  217. FILE * file = nullptr;
  218. FILE * open(const std::string & filename, const char * mode) {
  219. file = fopen(filename.c_str(), mode);
  220. return file;
  221. }
  222. int lock() {
  223. if (file) {
  224. # ifdef _WIN32
  225. fd = _fileno(file);
  226. hFile = (HANDLE) _get_osfhandle(fd);
  227. if (hFile == INVALID_HANDLE_VALUE) {
  228. fd = -1;
  229. return 1;
  230. }
  231. OVERLAPPED overlapped = {};
  232. if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD,
  233. &overlapped)) {
  234. fd = -1;
  235. return 1;
  236. }
  237. # else
  238. fd = fileno(file);
  239. if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
  240. fd = -1;
  241. return 1;
  242. }
  243. # endif
  244. }
  245. return 0;
  246. }
  247. ~File() {
  248. if (fd >= 0) {
  249. # ifdef _WIN32
  250. if (hFile != INVALID_HANDLE_VALUE) {
  251. OVERLAPPED overlapped = {};
  252. UnlockFileEx(hFile, 0, MAXDWORD, MAXDWORD, &overlapped);
  253. }
  254. # else
  255. flock(fd, LOCK_UN);
  256. # endif
  257. }
  258. if (file) {
  259. fclose(file);
  260. }
  261. }
  262. private:
  263. int fd = -1;
  264. # ifdef _WIN32
  265. HANDLE hFile = nullptr;
  266. # endif
  267. };
  268. class HttpClient {
  269. public:
  270. int init(const std::string & url, const std::vector<std::string> & headers, const std::string & output_file,
  271. const bool progress, std::string * response_str = nullptr) {
  272. std::string output_file_partial;
  273. curl = curl_easy_init();
  274. if (!curl) {
  275. return 1;
  276. }
  277. progress_data data;
  278. File out;
  279. if (!output_file.empty()) {
  280. output_file_partial = output_file + ".partial";
  281. if (!out.open(output_file_partial, "ab")) {
  282. printe("Failed to open file\n");
  283. return 1;
  284. }
  285. if (out.lock()) {
  286. printe("Failed to exclusively lock file\n");
  287. return 1;
  288. }
  289. }
  290. set_write_options(response_str, out);
  291. data.file_size = set_resume_point(output_file_partial);
  292. set_progress_options(progress, data);
  293. set_headers(headers);
  294. perform(url);
  295. if (!output_file.empty()) {
  296. std::filesystem::rename(output_file_partial, output_file);
  297. }
  298. return 0;
  299. }
  300. ~HttpClient() {
  301. if (chunk) {
  302. curl_slist_free_all(chunk);
  303. }
  304. if (curl) {
  305. curl_easy_cleanup(curl);
  306. }
  307. }
  308. private:
  309. CURL * curl = nullptr;
  310. struct curl_slist * chunk = nullptr;
  311. void set_write_options(std::string * response_str, const File & out) {
  312. if (response_str) {
  313. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, capture_data);
  314. curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_str);
  315. } else {
  316. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  317. curl_easy_setopt(curl, CURLOPT_WRITEDATA, out.file);
  318. }
  319. }
  320. size_t set_resume_point(const std::string & output_file) {
  321. size_t file_size = 0;
  322. if (std::filesystem::exists(output_file)) {
  323. file_size = std::filesystem::file_size(output_file);
  324. curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, static_cast<curl_off_t>(file_size));
  325. }
  326. return file_size;
  327. }
  328. void set_progress_options(bool progress, progress_data & data) {
  329. if (progress) {
  330. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  331. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &data);
  332. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, update_progress);
  333. }
  334. }
  335. void set_headers(const std::vector<std::string> & headers) {
  336. if (!headers.empty()) {
  337. if (chunk) {
  338. curl_slist_free_all(chunk);
  339. chunk = 0;
  340. }
  341. for (const auto & header : headers) {
  342. chunk = curl_slist_append(chunk, header.c_str());
  343. }
  344. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  345. }
  346. }
  347. void perform(const std::string & url) {
  348. CURLcode res;
  349. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  350. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  351. curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  352. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
  353. res = curl_easy_perform(curl);
  354. if (res != CURLE_OK) {
  355. printe("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
  356. }
  357. }
  358. static std::string human_readable_time(double seconds) {
  359. int hrs = static_cast<int>(seconds) / 3600;
  360. int mins = (static_cast<int>(seconds) % 3600) / 60;
  361. int secs = static_cast<int>(seconds) % 60;
  362. if (hrs > 0) {
  363. return fmt("%dh %02dm %02ds", hrs, mins, secs);
  364. } else if (mins > 0) {
  365. return fmt("%dm %02ds", mins, secs);
  366. } else {
  367. return fmt("%ds", secs);
  368. }
  369. }
  370. static std::string human_readable_size(curl_off_t size) {
  371. static const char * suffix[] = { "B", "KB", "MB", "GB", "TB" };
  372. char length = sizeof(suffix) / sizeof(suffix[0]);
  373. int i = 0;
  374. double dbl_size = size;
  375. if (size > 1024) {
  376. for (i = 0; (size / 1024) > 0 && i < length - 1; i++, size /= 1024) {
  377. dbl_size = size / 1024.0;
  378. }
  379. }
  380. return fmt("%.2f %s", dbl_size, suffix[i]);
  381. }
  382. static int update_progress(void * ptr, curl_off_t total_to_download, curl_off_t now_downloaded, curl_off_t,
  383. curl_off_t) {
  384. progress_data * data = static_cast<progress_data *>(ptr);
  385. if (total_to_download <= 0) {
  386. return 0;
  387. }
  388. total_to_download += data->file_size;
  389. const curl_off_t now_downloaded_plus_file_size = now_downloaded + data->file_size;
  390. const curl_off_t percentage = calculate_percentage(now_downloaded_plus_file_size, total_to_download);
  391. std::string progress_prefix = generate_progress_prefix(percentage);
  392. const double speed = calculate_speed(now_downloaded, data->start_time);
  393. const double tim = (total_to_download - now_downloaded) / speed;
  394. std::string progress_suffix =
  395. generate_progress_suffix(now_downloaded_plus_file_size, total_to_download, speed, tim);
  396. int progress_bar_width = calculate_progress_bar_width(progress_prefix, progress_suffix);
  397. std::string progress_bar;
  398. generate_progress_bar(progress_bar_width, percentage, progress_bar);
  399. print_progress(progress_prefix, progress_bar, progress_suffix);
  400. data->printed = true;
  401. return 0;
  402. }
  403. static curl_off_t calculate_percentage(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download) {
  404. return (now_downloaded_plus_file_size * 100) / total_to_download;
  405. }
  406. static std::string generate_progress_prefix(curl_off_t percentage) { return fmt("%3ld%% |", static_cast<long int>(percentage)); }
  407. static double calculate_speed(curl_off_t now_downloaded, const std::chrono::steady_clock::time_point & start_time) {
  408. const auto now = std::chrono::steady_clock::now();
  409. const std::chrono::duration<double> elapsed_seconds = now - start_time;
  410. return now_downloaded / elapsed_seconds.count();
  411. }
  412. static std::string generate_progress_suffix(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download,
  413. double speed, double estimated_time) {
  414. const int width = 10;
  415. return fmt("%*s/%*s%*s/s%*s", width, human_readable_size(now_downloaded_plus_file_size).c_str(), width,
  416. human_readable_size(total_to_download).c_str(), width, human_readable_size(speed).c_str(), width,
  417. human_readable_time(estimated_time).c_str());
  418. }
  419. static int calculate_progress_bar_width(const std::string & progress_prefix, const std::string & progress_suffix) {
  420. int progress_bar_width = get_terminal_width() - progress_prefix.size() - progress_suffix.size() - 3;
  421. if (progress_bar_width < 1) {
  422. progress_bar_width = 1;
  423. }
  424. return progress_bar_width;
  425. }
  426. static std::string generate_progress_bar(int progress_bar_width, curl_off_t percentage,
  427. std::string & progress_bar) {
  428. const curl_off_t pos = (percentage * progress_bar_width) / 100;
  429. for (int i = 0; i < progress_bar_width; ++i) {
  430. progress_bar.append((i < pos) ? "█" : " ");
  431. }
  432. return progress_bar;
  433. }
  434. static void print_progress(const std::string & progress_prefix, const std::string & progress_bar,
  435. const std::string & progress_suffix) {
  436. printe("\r%*s\r%s%s| %s", get_terminal_width(), " ", progress_prefix.c_str(), progress_bar.c_str(),
  437. progress_suffix.c_str());
  438. }
  439. // Function to write data to a file
  440. static size_t write_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  441. FILE * out = static_cast<FILE *>(stream);
  442. return fwrite(ptr, size, nmemb, out);
  443. }
  444. // Function to capture data into a string
  445. static size_t capture_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  446. std::string * str = static_cast<std::string *>(stream);
  447. str->append(static_cast<char *>(ptr), size * nmemb);
  448. return size * nmemb;
  449. }
  450. };
  451. #endif
  452. class LlamaData {
  453. public:
  454. llama_model_ptr model;
  455. llama_sampler_ptr sampler;
  456. llama_context_ptr context;
  457. std::vector<llama_chat_message> messages;
  458. std::vector<std::string> msg_strs;
  459. std::vector<char> fmtted;
  460. int init(Opt & opt) {
  461. model = initialize_model(opt);
  462. if (!model) {
  463. return 1;
  464. }
  465. context = initialize_context(model, opt);
  466. if (!context) {
  467. return 1;
  468. }
  469. sampler = initialize_sampler(opt);
  470. return 0;
  471. }
  472. private:
  473. #ifdef LLAMA_USE_CURL
  474. int download(const std::string & url, const std::vector<std::string> & headers, const std::string & output_file,
  475. const bool progress, std::string * response_str = nullptr) {
  476. HttpClient http;
  477. if (http.init(url, headers, output_file, progress, response_str)) {
  478. return 1;
  479. }
  480. return 0;
  481. }
  482. #else
  483. int download(const std::string &, const std::vector<std::string> &, const std::string &, const bool,
  484. std::string * = nullptr) {
  485. printe("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  486. return 1;
  487. }
  488. #endif
  489. int huggingface_dl(const std::string & model, const std::vector<std::string> headers, const std::string & bn) {
  490. // Find the second occurrence of '/' after protocol string
  491. size_t pos = model.find('/');
  492. pos = model.find('/', pos + 1);
  493. if (pos == std::string::npos) {
  494. return 1;
  495. }
  496. const std::string hfr = model.substr(0, pos);
  497. const std::string hff = model.substr(pos + 1);
  498. const std::string url = "https://huggingface.co/" + hfr + "/resolve/main/" + hff;
  499. return download(url, headers, bn, true);
  500. }
  501. int ollama_dl(std::string & model, const std::vector<std::string> headers, const std::string & bn) {
  502. if (model.find('/') == std::string::npos) {
  503. model = "library/" + model;
  504. }
  505. std::string model_tag = "latest";
  506. size_t colon_pos = model.find(':');
  507. if (colon_pos != std::string::npos) {
  508. model_tag = model.substr(colon_pos + 1);
  509. model = model.substr(0, colon_pos);
  510. }
  511. std::string manifest_url = "https://registry.ollama.ai/v2/" + model + "/manifests/" + model_tag;
  512. std::string manifest_str;
  513. const int ret = download(manifest_url, headers, "", false, &manifest_str);
  514. if (ret) {
  515. return ret;
  516. }
  517. nlohmann::json manifest = nlohmann::json::parse(manifest_str);
  518. std::string layer;
  519. for (const auto & l : manifest["layers"]) {
  520. if (l["mediaType"] == "application/vnd.ollama.image.model") {
  521. layer = l["digest"];
  522. break;
  523. }
  524. }
  525. std::string blob_url = "https://registry.ollama.ai/v2/" + model + "/blobs/" + layer;
  526. return download(blob_url, headers, bn, true);
  527. }
  528. std::string basename(const std::string & path) {
  529. const size_t pos = path.find_last_of("/\\");
  530. if (pos == std::string::npos) {
  531. return path;
  532. }
  533. return path.substr(pos + 1);
  534. }
  535. int remove_proto(std::string & model_) {
  536. const std::string::size_type pos = model_.find("://");
  537. if (pos == std::string::npos) {
  538. return 1;
  539. }
  540. model_ = model_.substr(pos + 3); // Skip past "://"
  541. return 0;
  542. }
  543. int resolve_model(std::string & model_) {
  544. int ret = 0;
  545. if (string_starts_with(model_, "file://") || std::filesystem::exists(model_)) {
  546. remove_proto(model_);
  547. return ret;
  548. }
  549. const std::string bn = basename(model_);
  550. const std::vector<std::string> headers = { "--header",
  551. "Accept: application/vnd.docker.distribution.manifest.v2+json" };
  552. if (string_starts_with(model_, "hf://") || string_starts_with(model_, "huggingface://")) {
  553. remove_proto(model_);
  554. ret = huggingface_dl(model_, headers, bn);
  555. } else if (string_starts_with(model_, "ollama://")) {
  556. remove_proto(model_);
  557. ret = ollama_dl(model_, headers, bn);
  558. } else if (string_starts_with(model_, "https://")) {
  559. download(model_, headers, bn, true);
  560. } else {
  561. ret = ollama_dl(model_, headers, bn);
  562. }
  563. model_ = bn;
  564. return ret;
  565. }
  566. // Initializes the model and returns a unique pointer to it
  567. llama_model_ptr initialize_model(Opt & opt) {
  568. ggml_backend_load_all();
  569. resolve_model(opt.model_);
  570. printe(
  571. "\r%*s"
  572. "\rLoading model",
  573. get_terminal_width(), " ");
  574. llama_model_ptr model(llama_model_load_from_file(opt.model_.c_str(), opt.model_params));
  575. if (!model) {
  576. printe("%s: error: unable to load model from file: %s\n", __func__, opt.model_.c_str());
  577. }
  578. printe("\r%*s\r", static_cast<int>(sizeof("Loading model")), " ");
  579. return model;
  580. }
  581. // Initializes the context with the specified parameters
  582. llama_context_ptr initialize_context(const llama_model_ptr & model, const Opt & opt) {
  583. llama_context_ptr context(llama_new_context_with_model(model.get(), opt.ctx_params));
  584. if (!context) {
  585. printe("%s: error: failed to create the llama_context\n", __func__);
  586. }
  587. return context;
  588. }
  589. // Initializes and configures the sampler
  590. llama_sampler_ptr initialize_sampler(const Opt & opt) {
  591. llama_sampler_ptr sampler(llama_sampler_chain_init(llama_sampler_chain_default_params()));
  592. llama_sampler_chain_add(sampler.get(), llama_sampler_init_min_p(0.05f, 1));
  593. llama_sampler_chain_add(sampler.get(), llama_sampler_init_temp(opt.temperature));
  594. llama_sampler_chain_add(sampler.get(), llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
  595. return sampler;
  596. }
  597. };
  598. // Add a message to `messages` and store its content in `msg_strs`
  599. static void add_message(const char * role, const std::string & text, LlamaData & llama_data) {
  600. llama_data.msg_strs.push_back(std::move(text));
  601. llama_data.messages.push_back({ role, llama_data.msg_strs.back().c_str() });
  602. }
  603. // Function to apply the chat template and resize `formatted` if needed
  604. static int apply_chat_template(LlamaData & llama_data, const bool append) {
  605. int result = llama_chat_apply_template(
  606. llama_data.model.get(), nullptr, llama_data.messages.data(), llama_data.messages.size(), append,
  607. append ? llama_data.fmtted.data() : nullptr, append ? llama_data.fmtted.size() : 0);
  608. if (append && result > static_cast<int>(llama_data.fmtted.size())) {
  609. llama_data.fmtted.resize(result);
  610. result = llama_chat_apply_template(llama_data.model.get(), nullptr, llama_data.messages.data(),
  611. llama_data.messages.size(), append, llama_data.fmtted.data(),
  612. llama_data.fmtted.size());
  613. }
  614. return result;
  615. }
  616. // Function to tokenize the prompt
  617. static int tokenize_prompt(const llama_model_ptr & model, const std::string & prompt,
  618. std::vector<llama_token> & prompt_tokens) {
  619. const int n_prompt_tokens = -llama_tokenize(model.get(), prompt.c_str(), prompt.size(), NULL, 0, true, true);
  620. prompt_tokens.resize(n_prompt_tokens);
  621. if (llama_tokenize(model.get(), prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), true,
  622. true) < 0) {
  623. printe("failed to tokenize the prompt\n");
  624. return -1;
  625. }
  626. return n_prompt_tokens;
  627. }
  628. // Check if we have enough space in the context to evaluate this batch
  629. static int check_context_size(const llama_context_ptr & ctx, const llama_batch & batch) {
  630. const int n_ctx = llama_n_ctx(ctx.get());
  631. const int n_ctx_used = llama_get_kv_cache_used_cells(ctx.get());
  632. if (n_ctx_used + batch.n_tokens > n_ctx) {
  633. printf("\033[0m\n");
  634. printe("context size exceeded\n");
  635. return 1;
  636. }
  637. return 0;
  638. }
  639. // convert the token to a string
  640. static int convert_token_to_string(const llama_model_ptr & model, const llama_token token_id, std::string & piece) {
  641. char buf[256];
  642. int n = llama_token_to_piece(model.get(), token_id, buf, sizeof(buf), 0, true);
  643. if (n < 0) {
  644. printe("failed to convert token to piece\n");
  645. return 1;
  646. }
  647. piece = std::string(buf, n);
  648. return 0;
  649. }
  650. static void print_word_and_concatenate_to_response(const std::string & piece, std::string & response) {
  651. printf("%s", piece.c_str());
  652. fflush(stdout);
  653. response += piece;
  654. }
  655. // helper function to evaluate a prompt and generate a response
  656. static int generate(LlamaData & llama_data, const std::string & prompt, std::string & response) {
  657. std::vector<llama_token> tokens;
  658. if (tokenize_prompt(llama_data.model, prompt, tokens) < 0) {
  659. return 1;
  660. }
  661. // prepare a batch for the prompt
  662. llama_batch batch = llama_batch_get_one(tokens.data(), tokens.size());
  663. llama_token new_token_id;
  664. while (true) {
  665. check_context_size(llama_data.context, batch);
  666. if (llama_decode(llama_data.context.get(), batch)) {
  667. printe("failed to decode\n");
  668. return 1;
  669. }
  670. // sample the next token, check is it an end of generation?
  671. new_token_id = llama_sampler_sample(llama_data.sampler.get(), llama_data.context.get(), -1);
  672. if (llama_token_is_eog(llama_data.model.get(), new_token_id)) {
  673. break;
  674. }
  675. std::string piece;
  676. if (convert_token_to_string(llama_data.model, new_token_id, piece)) {
  677. return 1;
  678. }
  679. print_word_and_concatenate_to_response(piece, response);
  680. // prepare the next batch with the sampled token
  681. batch = llama_batch_get_one(&new_token_id, 1);
  682. }
  683. return 0;
  684. }
  685. static int read_user_input(std::string & user) {
  686. std::getline(std::cin, user);
  687. if (std::cin.eof()) {
  688. printf("\n");
  689. return 1;
  690. }
  691. if (user == "/bye") {
  692. return 1;
  693. }
  694. if (user.empty()) {
  695. return 2;
  696. }
  697. return 0; // Should have data in happy path
  698. }
  699. // Function to generate a response based on the prompt
  700. static int generate_response(LlamaData & llama_data, const std::string & prompt, std::string & response,
  701. const bool stdout_a_terminal) {
  702. // Set response color
  703. if (stdout_a_terminal) {
  704. printf("\033[33m");
  705. }
  706. if (generate(llama_data, prompt, response)) {
  707. printe("failed to generate response\n");
  708. return 1;
  709. }
  710. // End response with color reset and newline
  711. printf("\n%s", stdout_a_terminal ? "\033[0m" : "");
  712. return 0;
  713. }
  714. // Helper function to apply the chat template and handle errors
  715. static int apply_chat_template_with_error_handling(LlamaData & llama_data, const bool append, int & output_length) {
  716. const int new_len = apply_chat_template(llama_data, append);
  717. if (new_len < 0) {
  718. printe("failed to apply the chat template\n");
  719. return -1;
  720. }
  721. output_length = new_len;
  722. return 0;
  723. }
  724. // Helper function to handle user input
  725. static int handle_user_input(std::string & user_input, const std::string & user) {
  726. if (!user.empty()) {
  727. user_input = user;
  728. return 0; // No need for interactive input
  729. }
  730. printf(
  731. "\r%*s"
  732. "\r\033[32m> \033[0m",
  733. get_terminal_width(), " ");
  734. return read_user_input(user_input); // Returns true if input ends the loop
  735. }
  736. static bool is_stdin_a_terminal() {
  737. #if defined(_WIN32)
  738. HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
  739. DWORD mode;
  740. return GetConsoleMode(hStdin, &mode);
  741. #else
  742. return isatty(STDIN_FILENO);
  743. #endif
  744. }
  745. static bool is_stdout_a_terminal() {
  746. #if defined(_WIN32)
  747. HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  748. DWORD mode;
  749. return GetConsoleMode(hStdout, &mode);
  750. #else
  751. return isatty(STDOUT_FILENO);
  752. #endif
  753. }
  754. // Function to handle user input
  755. static int get_user_input(std::string & user_input, const std::string & user) {
  756. while (true) {
  757. const int ret = handle_user_input(user_input, user);
  758. if (ret == 1) {
  759. return 1;
  760. }
  761. if (ret == 2) {
  762. continue;
  763. }
  764. break;
  765. }
  766. return 0;
  767. }
  768. // Main chat loop function
  769. static int chat_loop(LlamaData & llama_data, const std::string & user) {
  770. int prev_len = 0;
  771. llama_data.fmtted.resize(llama_n_ctx(llama_data.context.get()));
  772. static const bool stdout_a_terminal = is_stdout_a_terminal();
  773. while (true) {
  774. // Get user input
  775. std::string user_input;
  776. if (get_user_input(user_input, user) == 1) {
  777. return 0;
  778. }
  779. add_message("user", user.empty() ? user_input : user, llama_data);
  780. int new_len;
  781. if (apply_chat_template_with_error_handling(llama_data, true, new_len) < 0) {
  782. return 1;
  783. }
  784. std::string prompt(llama_data.fmtted.begin() + prev_len, llama_data.fmtted.begin() + new_len);
  785. std::string response;
  786. if (generate_response(llama_data, prompt, response, stdout_a_terminal)) {
  787. return 1;
  788. }
  789. if (!user.empty()) {
  790. break;
  791. }
  792. add_message("assistant", response, llama_data);
  793. if (apply_chat_template_with_error_handling(llama_data, false, prev_len) < 0) {
  794. return 1;
  795. }
  796. }
  797. return 0;
  798. }
  799. static void log_callback(const enum ggml_log_level level, const char * text, void * p) {
  800. const Opt * opt = static_cast<Opt *>(p);
  801. if (opt->verbose || level == GGML_LOG_LEVEL_ERROR) {
  802. printe("%s", text);
  803. }
  804. }
  805. static std::string read_pipe_data() {
  806. std::ostringstream result;
  807. result << std::cin.rdbuf(); // Read all data from std::cin
  808. return result.str();
  809. }
  810. static void ctrl_c_handling() {
  811. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  812. struct sigaction sigint_action;
  813. sigint_action.sa_handler = sigint_handler;
  814. sigemptyset(&sigint_action.sa_mask);
  815. sigint_action.sa_flags = 0;
  816. sigaction(SIGINT, &sigint_action, NULL);
  817. #elif defined(_WIN32)
  818. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  819. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  820. };
  821. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  822. #endif
  823. }
  824. int main(int argc, const char ** argv) {
  825. ctrl_c_handling();
  826. Opt opt;
  827. const int ret = opt.init(argc, argv);
  828. if (ret == 2) {
  829. return 0;
  830. } else if (ret) {
  831. return 1;
  832. }
  833. if (!is_stdin_a_terminal()) {
  834. if (!opt.user.empty()) {
  835. opt.user += "\n\n";
  836. }
  837. opt.user += read_pipe_data();
  838. }
  839. llama_log_set(log_callback, &opt);
  840. LlamaData llama_data;
  841. if (llama_data.init(opt)) {
  842. return 1;
  843. }
  844. if (chat_loop(llama_data, opt.user)) {
  845. return 1;
  846. }
  847. return 0;
  848. }