run.cpp 42 KB

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