run.cpp 36 KB

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