run.cpp 33 KB

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