1
0

run.cpp 37 KB

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