run.cpp 39 KB

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