run.cpp 31 KB

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