run.cpp 41 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 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. n_threads_default = ctx_params.n_threads;
  71. ngl_default = model_params.n_gpu_layers;
  72. common_params_sampling sampling;
  73. temperature_default = sampling.temp;
  74. if (argc < 2) {
  75. printe("Error: No arguments provided.\n");
  76. print_help();
  77. return 1;
  78. }
  79. // Parse arguments
  80. if (parse(argc, argv)) {
  81. printe("Error: Failed to parse arguments.\n");
  82. print_help();
  83. return 1;
  84. }
  85. // If help is requested, show help and exit
  86. if (help) {
  87. print_help();
  88. return 2;
  89. }
  90. ctx_params.n_batch = context_size >= 0 ? context_size : context_size_default;
  91. ctx_params.n_ctx = ctx_params.n_batch;
  92. ctx_params.n_threads = ctx_params.n_threads_batch = n_threads >= 0 ? n_threads : n_threads_default;
  93. model_params.n_gpu_layers = ngl >= 0 ? ngl : ngl_default;
  94. temperature = temperature >= 0 ? temperature : temperature_default;
  95. return 0; // Success
  96. }
  97. llama_context_params ctx_params;
  98. llama_model_params model_params;
  99. std::string model_;
  100. std::string chat_template_file;
  101. std::string user;
  102. bool use_jinja = false;
  103. int context_size = -1, ngl = -1, n_threads = -1;
  104. float temperature = -1;
  105. bool verbose = false;
  106. private:
  107. int context_size_default = -1, ngl_default = -1, n_threads_default = -1;
  108. float temperature_default = -1;
  109. bool help = false;
  110. bool parse_flag(const char ** argv, int i, const char * short_opt, const char * long_opt) {
  111. return strcmp(argv[i], short_opt) == 0 || strcmp(argv[i], long_opt) == 0;
  112. }
  113. int handle_option_with_value(int argc, const char ** argv, int & i, int & option_value) {
  114. if (i + 1 >= argc) {
  115. return 1;
  116. }
  117. option_value = std::atoi(argv[++i]);
  118. return 0;
  119. }
  120. int handle_option_with_value(int argc, const char ** argv, int & i, float & option_value) {
  121. if (i + 1 >= argc) {
  122. return 1;
  123. }
  124. option_value = std::atof(argv[++i]);
  125. return 0;
  126. }
  127. int handle_option_with_value(int argc, const char ** argv, int & i, std::string & option_value) {
  128. if (i + 1 >= argc) {
  129. return 1;
  130. }
  131. option_value = argv[++i];
  132. return 0;
  133. }
  134. int parse_options_with_value(int argc, const char ** argv, int & i, bool & options_parsing) {
  135. if (options_parsing && (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--context-size") == 0)) {
  136. if (handle_option_with_value(argc, argv, i, context_size) == 1) {
  137. return 1;
  138. }
  139. } else if (options_parsing &&
  140. (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "-ngl") == 0 || strcmp(argv[i], "--ngl") == 0)) {
  141. if (handle_option_with_value(argc, argv, i, ngl) == 1) {
  142. return 1;
  143. }
  144. } else if (options_parsing && (strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--threads") == 0)) {
  145. if (handle_option_with_value(argc, argv, i, n_threads) == 1) {
  146. return 1;
  147. }
  148. } else if (options_parsing && strcmp(argv[i], "--temp") == 0) {
  149. if (handle_option_with_value(argc, argv, i, temperature) == 1) {
  150. return 1;
  151. }
  152. } else if (options_parsing && strcmp(argv[i], "--chat-template-file") == 0) {
  153. if (handle_option_with_value(argc, argv, i, chat_template_file) == 1) {
  154. return 1;
  155. }
  156. use_jinja = true;
  157. } else {
  158. return 2;
  159. }
  160. return 0;
  161. }
  162. int parse_options(const char ** argv, int & i, bool & options_parsing) {
  163. if (options_parsing && (parse_flag(argv, i, "-v", "--verbose") || parse_flag(argv, i, "-v", "--log-verbose"))) {
  164. verbose = true;
  165. } else if (options_parsing && strcmp(argv[i], "--jinja") == 0) {
  166. use_jinja = true;
  167. } else if (options_parsing && parse_flag(argv, i, "-h", "--help")) {
  168. help = true;
  169. return 0;
  170. } else if (options_parsing && strcmp(argv[i], "--") == 0) {
  171. options_parsing = false;
  172. } else {
  173. return 2;
  174. }
  175. return 0;
  176. }
  177. int parse_positional_args(const char ** argv, int & i, int & positional_args_i) {
  178. if (positional_args_i == 0) {
  179. if (!argv[i][0] || argv[i][0] == '-') {
  180. return 1;
  181. }
  182. ++positional_args_i;
  183. model_ = argv[i];
  184. } else if (positional_args_i == 1) {
  185. ++positional_args_i;
  186. user = argv[i];
  187. } else {
  188. user += " " + std::string(argv[i]);
  189. }
  190. return 0;
  191. }
  192. int parse(int argc, const char ** argv) {
  193. bool options_parsing = true;
  194. for (int i = 1, positional_args_i = 0; i < argc; ++i) {
  195. int ret = parse_options_with_value(argc, argv, i, options_parsing);
  196. if (ret == 0) {
  197. continue;
  198. } else if (ret == 1) {
  199. return ret;
  200. }
  201. ret = parse_options(argv, i, options_parsing);
  202. if (ret == 0) {
  203. continue;
  204. } else if (ret == 1) {
  205. return ret;
  206. }
  207. if (parse_positional_args(argv, i, positional_args_i)) {
  208. return 1;
  209. }
  210. }
  211. if (model_.empty()) {
  212. return 1;
  213. }
  214. return 0;
  215. }
  216. void print_help() const {
  217. printf(
  218. "Description:\n"
  219. " Runs a llm\n"
  220. "\n"
  221. "Usage:\n"
  222. " llama-run [options] model [prompt]\n"
  223. "\n"
  224. "Options:\n"
  225. " -c, --context-size <value>\n"
  226. " Context size (default: %d)\n"
  227. " --chat-template-file <path>\n"
  228. " Path to the file containing the chat template to use with the model.\n"
  229. " Only supports jinja templates and implicitly sets the --jinja flag.\n"
  230. " --jinja\n"
  231. " Use jinja templating for the chat template of the model\n"
  232. " -n, -ngl, --ngl <value>\n"
  233. " Number of GPU layers (default: %d)\n"
  234. " --temp <value>\n"
  235. " Temperature (default: %.1f)\n"
  236. " -t, --threads <value>\n"
  237. " Number of threads to use during generation (default: %d)\n"
  238. " -v, --verbose, --log-verbose\n"
  239. " Set verbosity level to infinity (i.e. log all messages, useful for debugging)\n"
  240. " -h, --help\n"
  241. " Show help message\n"
  242. "\n"
  243. "Commands:\n"
  244. " model\n"
  245. " Model is a string with an optional prefix of \n"
  246. " huggingface:// (hf://), ollama://, https:// or file://.\n"
  247. " If no protocol is specified and a file exists in the specified\n"
  248. " path, file:// is assumed, otherwise if a file does not exist in\n"
  249. " the specified path, ollama:// is assumed. Models that are being\n"
  250. " pulled are downloaded with .partial extension while being\n"
  251. " downloaded and then renamed as the file without the .partial\n"
  252. " extension when complete.\n"
  253. "\n"
  254. "Examples:\n"
  255. " llama-run llama3\n"
  256. " llama-run ollama://granite-code\n"
  257. " llama-run ollama://smollm:135m\n"
  258. " llama-run hf://QuantFactory/SmolLM-135M-GGUF/SmolLM-135M.Q2_K.gguf\n"
  259. " llama-run "
  260. "huggingface://bartowski/SmolLM-1.7B-Instruct-v0.2-GGUF/SmolLM-1.7B-Instruct-v0.2-IQ3_M.gguf\n"
  261. " llama-run https://example.com/some-file1.gguf\n"
  262. " llama-run some-file2.gguf\n"
  263. " llama-run file://some-file3.gguf\n"
  264. " llama-run --ngl 999 some-file4.gguf\n"
  265. " llama-run --ngl 999 some-file5.gguf Hello World\n",
  266. context_size_default, ngl_default, temperature_default, n_threads_default);
  267. }
  268. };
  269. struct progress_data {
  270. size_t file_size = 0;
  271. std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
  272. bool printed = false;
  273. };
  274. static int get_terminal_width() {
  275. #if defined(_WIN32)
  276. CONSOLE_SCREEN_BUFFER_INFO csbi;
  277. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
  278. return csbi.srWindow.Right - csbi.srWindow.Left + 1;
  279. #else
  280. struct winsize w;
  281. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  282. return w.ws_col;
  283. #endif
  284. }
  285. class File {
  286. public:
  287. FILE * file = nullptr;
  288. FILE * open(const std::string & filename, const char * mode) {
  289. file = ggml_fopen(filename.c_str(), mode);
  290. return file;
  291. }
  292. int lock() {
  293. if (file) {
  294. # ifdef _WIN32
  295. fd = _fileno(file);
  296. hFile = (HANDLE) _get_osfhandle(fd);
  297. if (hFile == INVALID_HANDLE_VALUE) {
  298. fd = -1;
  299. return 1;
  300. }
  301. OVERLAPPED overlapped = {};
  302. if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD,
  303. &overlapped)) {
  304. fd = -1;
  305. return 1;
  306. }
  307. # else
  308. fd = fileno(file);
  309. if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
  310. fd = -1;
  311. return 1;
  312. }
  313. # endif
  314. }
  315. return 0;
  316. }
  317. std::string to_string() {
  318. fseek(file, 0, SEEK_END);
  319. const size_t size = ftell(file);
  320. fseek(file, 0, SEEK_SET);
  321. std::string out;
  322. out.resize(size);
  323. const size_t read_size = fread(&out[0], 1, size, file);
  324. if (read_size != size) {
  325. printe("Error reading file: %s", strerror(errno));
  326. }
  327. return out;
  328. }
  329. ~File() {
  330. if (fd >= 0) {
  331. # ifdef _WIN32
  332. if (hFile != INVALID_HANDLE_VALUE) {
  333. OVERLAPPED overlapped = {};
  334. UnlockFileEx(hFile, 0, MAXDWORD, MAXDWORD, &overlapped);
  335. }
  336. # else
  337. flock(fd, LOCK_UN);
  338. # endif
  339. }
  340. if (file) {
  341. fclose(file);
  342. }
  343. }
  344. private:
  345. int fd = -1;
  346. # ifdef _WIN32
  347. HANDLE hFile = nullptr;
  348. # endif
  349. };
  350. #ifdef LLAMA_USE_CURL
  351. class HttpClient {
  352. public:
  353. int init(const std::string & url, const std::vector<std::string> & headers, const std::string & output_file,
  354. const bool progress, std::string * response_str = nullptr) {
  355. if (std::filesystem::exists(output_file)) {
  356. return 0;
  357. }
  358. std::string output_file_partial;
  359. curl = curl_easy_init();
  360. if (!curl) {
  361. return 1;
  362. }
  363. progress_data data;
  364. File out;
  365. if (!output_file.empty()) {
  366. output_file_partial = output_file + ".partial";
  367. if (!out.open(output_file_partial, "ab")) {
  368. printe("Failed to open file for writing\n");
  369. return 1;
  370. }
  371. if (out.lock()) {
  372. printe("Failed to exclusively lock file\n");
  373. return 1;
  374. }
  375. }
  376. set_write_options(response_str, out);
  377. data.file_size = set_resume_point(output_file_partial);
  378. set_progress_options(progress, data);
  379. set_headers(headers);
  380. CURLcode res = perform(url);
  381. if (res != CURLE_OK){
  382. printe("Fetching resource '%s' failed: %s\n", url.c_str(), curl_easy_strerror(res));
  383. return 1;
  384. }
  385. if (!output_file.empty()) {
  386. std::filesystem::rename(output_file_partial, output_file);
  387. }
  388. return 0;
  389. }
  390. ~HttpClient() {
  391. if (chunk) {
  392. curl_slist_free_all(chunk);
  393. }
  394. if (curl) {
  395. curl_easy_cleanup(curl);
  396. }
  397. }
  398. private:
  399. CURL * curl = nullptr;
  400. struct curl_slist * chunk = nullptr;
  401. void set_write_options(std::string * response_str, const File & out) {
  402. if (response_str) {
  403. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, capture_data);
  404. curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_str);
  405. } else {
  406. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  407. curl_easy_setopt(curl, CURLOPT_WRITEDATA, out.file);
  408. }
  409. }
  410. size_t set_resume_point(const std::string & output_file) {
  411. size_t file_size = 0;
  412. if (std::filesystem::exists(output_file)) {
  413. file_size = std::filesystem::file_size(output_file);
  414. curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, static_cast<curl_off_t>(file_size));
  415. }
  416. return file_size;
  417. }
  418. void set_progress_options(bool progress, progress_data & data) {
  419. if (progress) {
  420. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  421. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &data);
  422. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, update_progress);
  423. }
  424. }
  425. void set_headers(const std::vector<std::string> & headers) {
  426. if (!headers.empty()) {
  427. if (chunk) {
  428. curl_slist_free_all(chunk);
  429. chunk = 0;
  430. }
  431. for (const auto & header : headers) {
  432. chunk = curl_slist_append(chunk, header.c_str());
  433. }
  434. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  435. }
  436. }
  437. CURLcode perform(const std::string & url) {
  438. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  439. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  440. curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  441. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
  442. return curl_easy_perform(curl);
  443. }
  444. static std::string human_readable_time(double seconds) {
  445. int hrs = static_cast<int>(seconds) / 3600;
  446. int mins = (static_cast<int>(seconds) % 3600) / 60;
  447. int secs = static_cast<int>(seconds) % 60;
  448. if (hrs > 0) {
  449. return fmt("%dh %02dm %02ds", hrs, mins, secs);
  450. } else if (mins > 0) {
  451. return fmt("%dm %02ds", mins, secs);
  452. } else {
  453. return fmt("%ds", secs);
  454. }
  455. }
  456. static std::string human_readable_size(curl_off_t size) {
  457. static const char * suffix[] = { "B", "KB", "MB", "GB", "TB" };
  458. char length = sizeof(suffix) / sizeof(suffix[0]);
  459. int i = 0;
  460. double dbl_size = size;
  461. if (size > 1024) {
  462. for (i = 0; (size / 1024) > 0 && i < length - 1; i++, size /= 1024) {
  463. dbl_size = size / 1024.0;
  464. }
  465. }
  466. return fmt("%.2f %s", dbl_size, suffix[i]);
  467. }
  468. static int update_progress(void * ptr, curl_off_t total_to_download, curl_off_t now_downloaded, curl_off_t,
  469. curl_off_t) {
  470. progress_data * data = static_cast<progress_data *>(ptr);
  471. if (total_to_download <= 0) {
  472. return 0;
  473. }
  474. total_to_download += data->file_size;
  475. const curl_off_t now_downloaded_plus_file_size = now_downloaded + data->file_size;
  476. const curl_off_t percentage = calculate_percentage(now_downloaded_plus_file_size, total_to_download);
  477. std::string progress_prefix = generate_progress_prefix(percentage);
  478. const double speed = calculate_speed(now_downloaded, data->start_time);
  479. const double tim = (total_to_download - now_downloaded) / speed;
  480. std::string progress_suffix =
  481. generate_progress_suffix(now_downloaded_plus_file_size, total_to_download, speed, tim);
  482. int progress_bar_width = calculate_progress_bar_width(progress_prefix, progress_suffix);
  483. std::string progress_bar;
  484. generate_progress_bar(progress_bar_width, percentage, progress_bar);
  485. print_progress(progress_prefix, progress_bar, progress_suffix);
  486. data->printed = true;
  487. return 0;
  488. }
  489. static curl_off_t calculate_percentage(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download) {
  490. return (now_downloaded_plus_file_size * 100) / total_to_download;
  491. }
  492. static std::string generate_progress_prefix(curl_off_t percentage) { return fmt("%3ld%% |", static_cast<long int>(percentage)); }
  493. static double calculate_speed(curl_off_t now_downloaded, const std::chrono::steady_clock::time_point & start_time) {
  494. const auto now = std::chrono::steady_clock::now();
  495. const std::chrono::duration<double> elapsed_seconds = now - start_time;
  496. return now_downloaded / elapsed_seconds.count();
  497. }
  498. static std::string generate_progress_suffix(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download,
  499. double speed, double estimated_time) {
  500. const int width = 10;
  501. return fmt("%*s/%*s%*s/s%*s", width, human_readable_size(now_downloaded_plus_file_size).c_str(), width,
  502. human_readable_size(total_to_download).c_str(), width, human_readable_size(speed).c_str(), width,
  503. human_readable_time(estimated_time).c_str());
  504. }
  505. static int calculate_progress_bar_width(const std::string & progress_prefix, const std::string & progress_suffix) {
  506. int progress_bar_width = get_terminal_width() - progress_prefix.size() - progress_suffix.size() - 3;
  507. if (progress_bar_width < 1) {
  508. progress_bar_width = 1;
  509. }
  510. return progress_bar_width;
  511. }
  512. static std::string generate_progress_bar(int progress_bar_width, curl_off_t percentage,
  513. std::string & progress_bar) {
  514. const curl_off_t pos = (percentage * progress_bar_width) / 100;
  515. for (int i = 0; i < progress_bar_width; ++i) {
  516. progress_bar.append((i < pos) ? "█" : " ");
  517. }
  518. return progress_bar;
  519. }
  520. static void print_progress(const std::string & progress_prefix, const std::string & progress_bar,
  521. const std::string & progress_suffix) {
  522. printe("\r" LOG_CLR_TO_EOL "%s%s| %s", progress_prefix.c_str(), progress_bar.c_str(), progress_suffix.c_str());
  523. }
  524. // Function to write data to a file
  525. static size_t write_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  526. FILE * out = static_cast<FILE *>(stream);
  527. return fwrite(ptr, size, nmemb, out);
  528. }
  529. // Function to capture data into a string
  530. static size_t capture_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  531. std::string * str = static_cast<std::string *>(stream);
  532. str->append(static_cast<char *>(ptr), size * nmemb);
  533. return size * nmemb;
  534. }
  535. };
  536. #endif
  537. class LlamaData {
  538. public:
  539. llama_model_ptr model;
  540. llama_sampler_ptr sampler;
  541. llama_context_ptr context;
  542. std::vector<llama_chat_message> messages; // TODO: switch to common_chat_msg
  543. std::list<std::string> msg_strs;
  544. std::vector<char> fmtted;
  545. int init(Opt & opt) {
  546. model = initialize_model(opt);
  547. if (!model) {
  548. return 1;
  549. }
  550. context = initialize_context(model, opt);
  551. if (!context) {
  552. return 1;
  553. }
  554. sampler = initialize_sampler(opt);
  555. return 0;
  556. }
  557. private:
  558. #ifdef LLAMA_USE_CURL
  559. int download(const std::string & url, const std::string & output_file, const bool progress,
  560. const std::vector<std::string> & headers = {}, std::string * response_str = nullptr) {
  561. HttpClient http;
  562. if (http.init(url, headers, output_file, progress, response_str)) {
  563. return 1;
  564. }
  565. return 0;
  566. }
  567. #else
  568. int download(const std::string &, const std::string &, const bool, const std::vector<std::string> & = {},
  569. std::string * = nullptr) {
  570. printe("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  571. return 1;
  572. }
  573. #endif
  574. // Helper function to handle model tag extraction and URL construction
  575. std::pair<std::string, std::string> extract_model_and_tag(std::string & model, const std::string & base_url) {
  576. std::string model_tag = "latest";
  577. const size_t colon_pos = model.find(':');
  578. if (colon_pos != std::string::npos) {
  579. model_tag = model.substr(colon_pos + 1);
  580. model = model.substr(0, colon_pos);
  581. }
  582. std::string url = base_url + model + "/manifests/" + model_tag;
  583. return { model, url };
  584. }
  585. // Helper function to download and parse the manifest
  586. int download_and_parse_manifest(const std::string & url, const std::vector<std::string> & headers,
  587. nlohmann::json & manifest) {
  588. std::string manifest_str;
  589. int ret = download(url, "", false, headers, &manifest_str);
  590. if (ret) {
  591. return ret;
  592. }
  593. manifest = nlohmann::json::parse(manifest_str);
  594. return 0;
  595. }
  596. int huggingface_dl(std::string & model, const std::string & bn) {
  597. // Find the second occurrence of '/' after protocol string
  598. size_t pos = model.find('/');
  599. pos = model.find('/', pos + 1);
  600. std::string hfr, hff;
  601. std::vector<std::string> headers = { "User-Agent: llama-cpp", "Accept: application/json" };
  602. std::string url;
  603. if (pos == std::string::npos) {
  604. auto [model_name, manifest_url] = extract_model_and_tag(model, "https://huggingface.co/v2/");
  605. hfr = model_name;
  606. nlohmann::json manifest;
  607. int ret = download_and_parse_manifest(manifest_url, headers, manifest);
  608. if (ret) {
  609. return ret;
  610. }
  611. hff = manifest["ggufFile"]["rfilename"];
  612. } else {
  613. hfr = model.substr(0, pos);
  614. hff = model.substr(pos + 1);
  615. }
  616. url = "https://huggingface.co/" + hfr + "/resolve/main/" + hff;
  617. return download(url, bn, true, headers);
  618. }
  619. int ollama_dl(std::string & model, const std::string & bn) {
  620. const std::vector<std::string> headers = { "Accept: application/vnd.docker.distribution.manifest.v2+json" };
  621. if (model.find('/') == std::string::npos) {
  622. model = "library/" + model;
  623. }
  624. auto [model_name, manifest_url] = extract_model_and_tag(model, "https://registry.ollama.ai/v2/");
  625. nlohmann::json manifest;
  626. int ret = download_and_parse_manifest(manifest_url, {}, manifest);
  627. if (ret) {
  628. return ret;
  629. }
  630. std::string layer;
  631. for (const auto & l : manifest["layers"]) {
  632. if (l["mediaType"] == "application/vnd.ollama.image.model") {
  633. layer = l["digest"];
  634. break;
  635. }
  636. }
  637. std::string blob_url = "https://registry.ollama.ai/v2/" + model_name + "/blobs/" + layer;
  638. return download(blob_url, bn, true, headers);
  639. }
  640. int github_dl(const std::string & model, const std::string & bn) {
  641. std::string repository = model;
  642. std::string branch = "main";
  643. const size_t at_pos = model.find('@');
  644. if (at_pos != std::string::npos) {
  645. repository = model.substr(0, at_pos);
  646. branch = model.substr(at_pos + 1);
  647. }
  648. const std::vector<std::string> repo_parts = string_split(repository, "/");
  649. if (repo_parts.size() < 3) {
  650. printe("Invalid GitHub repository format\n");
  651. return 1;
  652. }
  653. const std::string & org = repo_parts[0];
  654. const std::string & project = repo_parts[1];
  655. std::string url = "https://raw.githubusercontent.com/" + org + "/" + project + "/" + branch;
  656. for (size_t i = 2; i < repo_parts.size(); ++i) {
  657. url += "/" + repo_parts[i];
  658. }
  659. return download(url, bn, true);
  660. }
  661. int s3_dl(const std::string & model, const std::string & bn) {
  662. const size_t slash_pos = model.find('/');
  663. if (slash_pos == std::string::npos) {
  664. return 1;
  665. }
  666. const std::string bucket = model.substr(0, slash_pos);
  667. const std::string key = model.substr(slash_pos + 1);
  668. const char * access_key = std::getenv("AWS_ACCESS_KEY_ID");
  669. const char * secret_key = std::getenv("AWS_SECRET_ACCESS_KEY");
  670. if (!access_key || !secret_key) {
  671. printe("AWS credentials not found in environment\n");
  672. return 1;
  673. }
  674. // Generate AWS Signature Version 4 headers
  675. // (Implementation requires HMAC-SHA256 and date handling)
  676. // Get current timestamp
  677. const time_t now = time(nullptr);
  678. const tm tm = *gmtime(&now);
  679. const std::string date = strftime_fmt("%Y%m%d", tm);
  680. const std::string datetime = strftime_fmt("%Y%m%dT%H%M%SZ", tm);
  681. const std::vector<std::string> headers = {
  682. "Authorization: AWS4-HMAC-SHA256 Credential=" + std::string(access_key) + "/" + date +
  683. "/us-east-1/s3/aws4_request",
  684. "x-amz-content-sha256: UNSIGNED-PAYLOAD", "x-amz-date: " + datetime
  685. };
  686. const std::string url = "https://" + bucket + ".s3.amazonaws.com/" + key;
  687. return download(url, bn, true, headers);
  688. }
  689. std::string basename(const std::string & path) {
  690. const size_t pos = path.find_last_of("/\\");
  691. if (pos == std::string::npos) {
  692. return path;
  693. }
  694. return path.substr(pos + 1);
  695. }
  696. int rm_until_substring(std::string & model_, const std::string & substring) {
  697. const std::string::size_type pos = model_.find(substring);
  698. if (pos == std::string::npos) {
  699. return 1;
  700. }
  701. model_ = model_.substr(pos + substring.size()); // Skip past the substring
  702. return 0;
  703. }
  704. int resolve_model(std::string & model_) {
  705. int ret = 0;
  706. if (string_starts_with(model_, "file://") || std::filesystem::exists(model_)) {
  707. rm_until_substring(model_, "://");
  708. return ret;
  709. }
  710. const std::string bn = basename(model_);
  711. if (string_starts_with(model_, "hf://") || string_starts_with(model_, "huggingface://") ||
  712. string_starts_with(model_, "hf.co/")) {
  713. rm_until_substring(model_, "hf.co/");
  714. rm_until_substring(model_, "://");
  715. ret = huggingface_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. }