run.cpp 39 KB

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