run.cpp 31 KB

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