run.cpp 43 KB

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