run.cpp 40 KB

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