run.cpp 42 KB

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