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 read_all(const std::string & filename){
  281. open(filename, "r");
  282. lock();
  283. if (!file) {
  284. printe("Error opening file '%s': %s", filename.c_str(), strerror(errno));
  285. return "";
  286. }
  287. fseek(file, 0, SEEK_END);
  288. size_t size = ftell(file);
  289. fseek(file, 0, SEEK_SET);
  290. std::string out;
  291. out.resize(size);
  292. size_t read_size = fread(&out[0], 1, size, file);
  293. if (read_size != size) {
  294. printe("Error reading file '%s': %s", filename.c_str(), strerror(errno));
  295. return "";
  296. }
  297. return out;
  298. }
  299. ~File() {
  300. if (fd >= 0) {
  301. # ifdef _WIN32
  302. if (hFile != INVALID_HANDLE_VALUE) {
  303. OVERLAPPED overlapped = {};
  304. UnlockFileEx(hFile, 0, MAXDWORD, MAXDWORD, &overlapped);
  305. }
  306. # else
  307. flock(fd, LOCK_UN);
  308. # endif
  309. }
  310. if (file) {
  311. fclose(file);
  312. }
  313. }
  314. private:
  315. int fd = -1;
  316. # ifdef _WIN32
  317. HANDLE hFile = nullptr;
  318. # endif
  319. };
  320. #ifdef LLAMA_USE_CURL
  321. class HttpClient {
  322. public:
  323. int init(const std::string & url, const std::vector<std::string> & headers, const std::string & output_file,
  324. const bool progress, std::string * response_str = nullptr) {
  325. if (std::filesystem::exists(output_file)) {
  326. return 0;
  327. }
  328. std::string output_file_partial;
  329. curl = curl_easy_init();
  330. if (!curl) {
  331. return 1;
  332. }
  333. progress_data data;
  334. File out;
  335. if (!output_file.empty()) {
  336. output_file_partial = output_file + ".partial";
  337. if (!out.open(output_file_partial, "ab")) {
  338. printe("Failed to open file for writing\n");
  339. return 1;
  340. }
  341. if (out.lock()) {
  342. printe("Failed to exclusively lock file\n");
  343. return 1;
  344. }
  345. }
  346. set_write_options(response_str, out);
  347. data.file_size = set_resume_point(output_file_partial);
  348. set_progress_options(progress, data);
  349. set_headers(headers);
  350. CURLcode res = perform(url);
  351. if (res != CURLE_OK){
  352. printe("Fetching resource '%s' failed: %s\n", url.c_str(), curl_easy_strerror(res));
  353. return 1;
  354. }
  355. if (!output_file.empty()) {
  356. std::filesystem::rename(output_file_partial, output_file);
  357. }
  358. return 0;
  359. }
  360. ~HttpClient() {
  361. if (chunk) {
  362. curl_slist_free_all(chunk);
  363. }
  364. if (curl) {
  365. curl_easy_cleanup(curl);
  366. }
  367. }
  368. private:
  369. CURL * curl = nullptr;
  370. struct curl_slist * chunk = nullptr;
  371. void set_write_options(std::string * response_str, const File & out) {
  372. if (response_str) {
  373. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, capture_data);
  374. curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_str);
  375. } else {
  376. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  377. curl_easy_setopt(curl, CURLOPT_WRITEDATA, out.file);
  378. }
  379. }
  380. size_t set_resume_point(const std::string & output_file) {
  381. size_t file_size = 0;
  382. if (std::filesystem::exists(output_file)) {
  383. file_size = std::filesystem::file_size(output_file);
  384. curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, static_cast<curl_off_t>(file_size));
  385. }
  386. return file_size;
  387. }
  388. void set_progress_options(bool progress, progress_data & data) {
  389. if (progress) {
  390. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  391. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &data);
  392. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, update_progress);
  393. }
  394. }
  395. void set_headers(const std::vector<std::string> & headers) {
  396. if (!headers.empty()) {
  397. if (chunk) {
  398. curl_slist_free_all(chunk);
  399. chunk = 0;
  400. }
  401. for (const auto & header : headers) {
  402. chunk = curl_slist_append(chunk, header.c_str());
  403. }
  404. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  405. }
  406. }
  407. CURLcode perform(const std::string & url) {
  408. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  409. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  410. curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  411. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
  412. return curl_easy_perform(curl);
  413. }
  414. static std::string human_readable_time(double seconds) {
  415. int hrs = static_cast<int>(seconds) / 3600;
  416. int mins = (static_cast<int>(seconds) % 3600) / 60;
  417. int secs = static_cast<int>(seconds) % 60;
  418. if (hrs > 0) {
  419. return fmt("%dh %02dm %02ds", hrs, mins, secs);
  420. } else if (mins > 0) {
  421. return fmt("%dm %02ds", mins, secs);
  422. } else {
  423. return fmt("%ds", secs);
  424. }
  425. }
  426. static std::string human_readable_size(curl_off_t size) {
  427. static const char * suffix[] = { "B", "KB", "MB", "GB", "TB" };
  428. char length = sizeof(suffix) / sizeof(suffix[0]);
  429. int i = 0;
  430. double dbl_size = size;
  431. if (size > 1024) {
  432. for (i = 0; (size / 1024) > 0 && i < length - 1; i++, size /= 1024) {
  433. dbl_size = size / 1024.0;
  434. }
  435. }
  436. return fmt("%.2f %s", dbl_size, suffix[i]);
  437. }
  438. static int update_progress(void * ptr, curl_off_t total_to_download, curl_off_t now_downloaded, curl_off_t,
  439. curl_off_t) {
  440. progress_data * data = static_cast<progress_data *>(ptr);
  441. if (total_to_download <= 0) {
  442. return 0;
  443. }
  444. total_to_download += data->file_size;
  445. const curl_off_t now_downloaded_plus_file_size = now_downloaded + data->file_size;
  446. const curl_off_t percentage = calculate_percentage(now_downloaded_plus_file_size, total_to_download);
  447. std::string progress_prefix = generate_progress_prefix(percentage);
  448. const double speed = calculate_speed(now_downloaded, data->start_time);
  449. const double tim = (total_to_download - now_downloaded) / speed;
  450. std::string progress_suffix =
  451. generate_progress_suffix(now_downloaded_plus_file_size, total_to_download, speed, tim);
  452. int progress_bar_width = calculate_progress_bar_width(progress_prefix, progress_suffix);
  453. std::string progress_bar;
  454. generate_progress_bar(progress_bar_width, percentage, progress_bar);
  455. print_progress(progress_prefix, progress_bar, progress_suffix);
  456. data->printed = true;
  457. return 0;
  458. }
  459. static curl_off_t calculate_percentage(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download) {
  460. return (now_downloaded_plus_file_size * 100) / total_to_download;
  461. }
  462. static std::string generate_progress_prefix(curl_off_t percentage) { return fmt("%3ld%% |", static_cast<long int>(percentage)); }
  463. static double calculate_speed(curl_off_t now_downloaded, const std::chrono::steady_clock::time_point & start_time) {
  464. const auto now = std::chrono::steady_clock::now();
  465. const std::chrono::duration<double> elapsed_seconds = now - start_time;
  466. return now_downloaded / elapsed_seconds.count();
  467. }
  468. static std::string generate_progress_suffix(curl_off_t now_downloaded_plus_file_size, curl_off_t total_to_download,
  469. double speed, double estimated_time) {
  470. const int width = 10;
  471. return fmt("%*s/%*s%*s/s%*s", width, human_readable_size(now_downloaded_plus_file_size).c_str(), width,
  472. human_readable_size(total_to_download).c_str(), width, human_readable_size(speed).c_str(), width,
  473. human_readable_time(estimated_time).c_str());
  474. }
  475. static int calculate_progress_bar_width(const std::string & progress_prefix, const std::string & progress_suffix) {
  476. int progress_bar_width = get_terminal_width() - progress_prefix.size() - progress_suffix.size() - 3;
  477. if (progress_bar_width < 1) {
  478. progress_bar_width = 1;
  479. }
  480. return progress_bar_width;
  481. }
  482. static std::string generate_progress_bar(int progress_bar_width, curl_off_t percentage,
  483. std::string & progress_bar) {
  484. const curl_off_t pos = (percentage * progress_bar_width) / 100;
  485. for (int i = 0; i < progress_bar_width; ++i) {
  486. progress_bar.append((i < pos) ? "█" : " ");
  487. }
  488. return progress_bar;
  489. }
  490. static void print_progress(const std::string & progress_prefix, const std::string & progress_bar,
  491. const std::string & progress_suffix) {
  492. printe("\r" LOG_CLR_TO_EOL "%s%s| %s", progress_prefix.c_str(), progress_bar.c_str(), progress_suffix.c_str());
  493. }
  494. // Function to write data to a file
  495. static size_t write_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  496. FILE * out = static_cast<FILE *>(stream);
  497. return fwrite(ptr, size, nmemb, out);
  498. }
  499. // Function to capture data into a string
  500. static size_t capture_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  501. std::string * str = static_cast<std::string *>(stream);
  502. str->append(static_cast<char *>(ptr), size * nmemb);
  503. return size * nmemb;
  504. }
  505. };
  506. #endif
  507. class LlamaData {
  508. public:
  509. llama_model_ptr model;
  510. llama_sampler_ptr sampler;
  511. llama_context_ptr context;
  512. std::vector<llama_chat_message> messages; // TODO: switch to common_chat_msg
  513. std::list<std::string> msg_strs;
  514. std::vector<char> fmtted;
  515. int init(Opt & opt) {
  516. model = initialize_model(opt);
  517. if (!model) {
  518. return 1;
  519. }
  520. context = initialize_context(model, opt);
  521. if (!context) {
  522. return 1;
  523. }
  524. sampler = initialize_sampler(opt);
  525. return 0;
  526. }
  527. private:
  528. #ifdef LLAMA_USE_CURL
  529. int download(const std::string & url, const std::string & output_file, const bool progress,
  530. const std::vector<std::string> & headers = {}, std::string * response_str = nullptr) {
  531. HttpClient http;
  532. if (http.init(url, headers, output_file, progress, response_str)) {
  533. return 1;
  534. }
  535. return 0;
  536. }
  537. #else
  538. int download(const std::string &, const std::string &, const bool, const std::vector<std::string> & = {},
  539. std::string * = nullptr) {
  540. printe("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  541. return 1;
  542. }
  543. #endif
  544. // Helper function to handle model tag extraction and URL construction
  545. std::pair<std::string, std::string> extract_model_and_tag(std::string & model, const std::string & base_url) {
  546. std::string model_tag = "latest";
  547. const size_t colon_pos = model.find(':');
  548. if (colon_pos != std::string::npos) {
  549. model_tag = model.substr(colon_pos + 1);
  550. model = model.substr(0, colon_pos);
  551. }
  552. std::string url = base_url + model + "/manifests/" + model_tag;
  553. return { model, url };
  554. }
  555. // Helper function to download and parse the manifest
  556. int download_and_parse_manifest(const std::string & url, const std::vector<std::string> & headers,
  557. nlohmann::json & manifest) {
  558. std::string manifest_str;
  559. int ret = download(url, "", false, headers, &manifest_str);
  560. if (ret) {
  561. return ret;
  562. }
  563. manifest = nlohmann::json::parse(manifest_str);
  564. return 0;
  565. }
  566. int huggingface_dl(std::string & model, const std::string & bn) {
  567. // Find the second occurrence of '/' after protocol string
  568. size_t pos = model.find('/');
  569. pos = model.find('/', pos + 1);
  570. std::string hfr, hff;
  571. std::vector<std::string> headers = { "User-Agent: llama-cpp", "Accept: application/json" };
  572. std::string url;
  573. if (pos == std::string::npos) {
  574. auto [model_name, manifest_url] = extract_model_and_tag(model, "https://huggingface.co/v2/");
  575. hfr = model_name;
  576. nlohmann::json manifest;
  577. int ret = download_and_parse_manifest(manifest_url, headers, manifest);
  578. if (ret) {
  579. return ret;
  580. }
  581. hff = manifest["ggufFile"]["rfilename"];
  582. } else {
  583. hfr = model.substr(0, pos);
  584. hff = model.substr(pos + 1);
  585. }
  586. url = "https://huggingface.co/" + hfr + "/resolve/main/" + hff;
  587. return download(url, bn, true, headers);
  588. }
  589. int ollama_dl(std::string & model, const std::string & bn) {
  590. const std::vector<std::string> headers = { "Accept: application/vnd.docker.distribution.manifest.v2+json" };
  591. if (model.find('/') == std::string::npos) {
  592. model = "library/" + model;
  593. }
  594. auto [model_name, manifest_url] = extract_model_and_tag(model, "https://registry.ollama.ai/v2/");
  595. nlohmann::json manifest;
  596. int ret = download_and_parse_manifest(manifest_url, {}, manifest);
  597. if (ret) {
  598. return ret;
  599. }
  600. std::string layer;
  601. for (const auto & l : manifest["layers"]) {
  602. if (l["mediaType"] == "application/vnd.ollama.image.model") {
  603. layer = l["digest"];
  604. break;
  605. }
  606. }
  607. std::string blob_url = "https://registry.ollama.ai/v2/" + model_name + "/blobs/" + layer;
  608. return download(blob_url, bn, true, headers);
  609. }
  610. int github_dl(const std::string & model, const std::string & bn) {
  611. std::string repository = model;
  612. std::string branch = "main";
  613. const size_t at_pos = model.find('@');
  614. if (at_pos != std::string::npos) {
  615. repository = model.substr(0, at_pos);
  616. branch = model.substr(at_pos + 1);
  617. }
  618. const std::vector<std::string> repo_parts = string_split(repository, "/");
  619. if (repo_parts.size() < 3) {
  620. printe("Invalid GitHub repository format\n");
  621. return 1;
  622. }
  623. const std::string & org = repo_parts[0];
  624. const std::string & project = repo_parts[1];
  625. std::string url = "https://raw.githubusercontent.com/" + org + "/" + project + "/" + branch;
  626. for (size_t i = 2; i < repo_parts.size(); ++i) {
  627. url += "/" + repo_parts[i];
  628. }
  629. return download(url, bn, true);
  630. }
  631. int s3_dl(const std::string & model, const std::string & bn) {
  632. const size_t slash_pos = model.find('/');
  633. if (slash_pos == std::string::npos) {
  634. return 1;
  635. }
  636. const std::string bucket = model.substr(0, slash_pos);
  637. const std::string key = model.substr(slash_pos + 1);
  638. const char * access_key = std::getenv("AWS_ACCESS_KEY_ID");
  639. const char * secret_key = std::getenv("AWS_SECRET_ACCESS_KEY");
  640. if (!access_key || !secret_key) {
  641. printe("AWS credentials not found in environment\n");
  642. return 1;
  643. }
  644. // Generate AWS Signature Version 4 headers
  645. // (Implementation requires HMAC-SHA256 and date handling)
  646. // Get current timestamp
  647. const time_t now = time(nullptr);
  648. const tm tm = *gmtime(&now);
  649. const std::string date = strftime_fmt("%Y%m%d", tm);
  650. const std::string datetime = strftime_fmt("%Y%m%dT%H%M%SZ", tm);
  651. const std::vector<std::string> headers = {
  652. "Authorization: AWS4-HMAC-SHA256 Credential=" + std::string(access_key) + "/" + date +
  653. "/us-east-1/s3/aws4_request",
  654. "x-amz-content-sha256: UNSIGNED-PAYLOAD", "x-amz-date: " + datetime
  655. };
  656. const std::string url = "https://" + bucket + ".s3.amazonaws.com/" + key;
  657. return download(url, bn, true, headers);
  658. }
  659. std::string basename(const std::string & path) {
  660. const size_t pos = path.find_last_of("/\\");
  661. if (pos == std::string::npos) {
  662. return path;
  663. }
  664. return path.substr(pos + 1);
  665. }
  666. int rm_until_substring(std::string & model_, const std::string & substring) {
  667. const std::string::size_type pos = model_.find(substring);
  668. if (pos == std::string::npos) {
  669. return 1;
  670. }
  671. model_ = model_.substr(pos + substring.size()); // Skip past the substring
  672. return 0;
  673. }
  674. int resolve_model(std::string & model_) {
  675. int ret = 0;
  676. if (string_starts_with(model_, "file://") || std::filesystem::exists(model_)) {
  677. rm_until_substring(model_, "://");
  678. return ret;
  679. }
  680. const std::string bn = basename(model_);
  681. if (string_starts_with(model_, "hf://") || string_starts_with(model_, "huggingface://") ||
  682. string_starts_with(model_, "hf.co/")) {
  683. rm_until_substring(model_, "hf.co/");
  684. rm_until_substring(model_, "://");
  685. ret = huggingface_dl(model_, bn);
  686. } else if ((string_starts_with(model_, "https://") || string_starts_with(model_, "http://")) &&
  687. !string_starts_with(model_, "https://ollama.com/library/")) {
  688. ret = download(model_, bn, true);
  689. } else if (string_starts_with(model_, "github:") || string_starts_with(model_, "github://")) {
  690. rm_until_substring(model_, "github:");
  691. rm_until_substring(model_, "://");
  692. ret = github_dl(model_, bn);
  693. } else if (string_starts_with(model_, "s3://")) {
  694. rm_until_substring(model_, "://");
  695. ret = s3_dl(model_, bn);
  696. } else { // ollama:// or nothing
  697. rm_until_substring(model_, "ollama.com/library/");
  698. rm_until_substring(model_, "://");
  699. ret = ollama_dl(model_, bn);
  700. }
  701. model_ = bn;
  702. return ret;
  703. }
  704. // Initializes the model and returns a unique pointer to it
  705. llama_model_ptr initialize_model(Opt & opt) {
  706. ggml_backend_load_all();
  707. resolve_model(opt.model_);
  708. printe("\r" LOG_CLR_TO_EOL "Loading model");
  709. llama_model_ptr model(llama_model_load_from_file(opt.model_.c_str(), opt.model_params));
  710. if (!model) {
  711. printe("%s: error: unable to load model from file: %s\n", __func__, opt.model_.c_str());
  712. }
  713. printe("\r" LOG_CLR_TO_EOL);
  714. return model;
  715. }
  716. // Initializes the context with the specified parameters
  717. llama_context_ptr initialize_context(const llama_model_ptr & model, const Opt & opt) {
  718. llama_context_ptr context(llama_init_from_model(model.get(), opt.ctx_params));
  719. if (!context) {
  720. printe("%s: error: failed to create the llama_context\n", __func__);
  721. }
  722. return context;
  723. }
  724. // Initializes and configures the sampler
  725. llama_sampler_ptr initialize_sampler(const Opt & opt) {
  726. llama_sampler_ptr sampler(llama_sampler_chain_init(llama_sampler_chain_default_params()));
  727. llama_sampler_chain_add(sampler.get(), llama_sampler_init_min_p(0.05f, 1));
  728. llama_sampler_chain_add(sampler.get(), llama_sampler_init_temp(opt.temperature));
  729. llama_sampler_chain_add(sampler.get(), llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
  730. return sampler;
  731. }
  732. };
  733. // Add a message to `messages` and store its content in `msg_strs`
  734. static void add_message(const char * role, const std::string & text, LlamaData & llama_data) {
  735. llama_data.msg_strs.push_back(std::move(text));
  736. llama_data.messages.push_back({ role, llama_data.msg_strs.back().c_str() });
  737. }
  738. // Function to apply the chat template and resize `formatted` if needed
  739. static int apply_chat_template(const struct common_chat_templates * tmpls, LlamaData & llama_data, const bool append, bool use_jinja) {
  740. common_chat_templates_inputs inputs;
  741. for (const auto & msg : llama_data.messages) {
  742. common_chat_msg cmsg;
  743. cmsg.role = msg.role;
  744. cmsg.content = msg.content;
  745. inputs.messages.push_back(cmsg);
  746. }
  747. inputs.add_generation_prompt = append;
  748. inputs.use_jinja = use_jinja;
  749. auto chat_params = common_chat_templates_apply(tmpls, inputs);
  750. // TODO: use other params for tool calls.
  751. auto result = chat_params.prompt;
  752. llama_data.fmtted.resize(result.size() + 1);
  753. memcpy(llama_data.fmtted.data(), result.c_str(), result.size() + 1);
  754. return result.size();
  755. }
  756. // Function to tokenize the prompt
  757. static int tokenize_prompt(const llama_vocab * vocab, const std::string & prompt,
  758. std::vector<llama_token> & prompt_tokens, const LlamaData & llama_data) {
  759. const bool is_first = llama_get_kv_cache_used_cells(llama_data.context.get()) == 0;
  760. const int n_prompt_tokens = -llama_tokenize(vocab, prompt.c_str(), prompt.size(), NULL, 0, is_first, true);
  761. prompt_tokens.resize(n_prompt_tokens);
  762. if (llama_tokenize(vocab, prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), is_first,
  763. true) < 0) {
  764. printe("failed to tokenize the prompt\n");
  765. return -1;
  766. }
  767. return n_prompt_tokens;
  768. }
  769. // Check if we have enough space in the context to evaluate this batch
  770. static int check_context_size(const llama_context_ptr & ctx, const llama_batch & batch) {
  771. const int n_ctx = llama_n_ctx(ctx.get());
  772. const int n_ctx_used = llama_get_kv_cache_used_cells(ctx.get());
  773. if (n_ctx_used + batch.n_tokens > n_ctx) {
  774. printf(LOG_COL_DEFAULT "\n");
  775. printe("context size exceeded\n");
  776. return 1;
  777. }
  778. return 0;
  779. }
  780. // convert the token to a string
  781. static int convert_token_to_string(const llama_vocab * vocab, const llama_token token_id, std::string & piece) {
  782. char buf[256];
  783. int n = llama_token_to_piece(vocab, token_id, buf, sizeof(buf), 0, true);
  784. if (n < 0) {
  785. printe("failed to convert token to piece\n");
  786. return 1;
  787. }
  788. piece = std::string(buf, n);
  789. return 0;
  790. }
  791. static void print_word_and_concatenate_to_response(const std::string & piece, std::string & response) {
  792. printf("%s", piece.c_str());
  793. fflush(stdout);
  794. response += piece;
  795. }
  796. // helper function to evaluate a prompt and generate a response
  797. static int generate(LlamaData & llama_data, const std::string & prompt, std::string & response) {
  798. const llama_vocab * vocab = llama_model_get_vocab(llama_data.model.get());
  799. std::vector<llama_token> tokens;
  800. if (tokenize_prompt(vocab, prompt, tokens, llama_data) < 0) {
  801. return 1;
  802. }
  803. // prepare a batch for the prompt
  804. llama_batch batch = llama_batch_get_one(tokens.data(), tokens.size());
  805. llama_token new_token_id;
  806. while (true) {
  807. check_context_size(llama_data.context, batch);
  808. if (llama_decode(llama_data.context.get(), batch)) {
  809. printe("failed to decode\n");
  810. return 1;
  811. }
  812. // sample the next token, check is it an end of generation?
  813. new_token_id = llama_sampler_sample(llama_data.sampler.get(), llama_data.context.get(), -1);
  814. if (llama_vocab_is_eog(vocab, new_token_id)) {
  815. break;
  816. }
  817. std::string piece;
  818. if (convert_token_to_string(vocab, new_token_id, piece)) {
  819. return 1;
  820. }
  821. print_word_and_concatenate_to_response(piece, response);
  822. // prepare the next batch with the sampled token
  823. batch = llama_batch_get_one(&new_token_id, 1);
  824. }
  825. printf(LOG_COL_DEFAULT);
  826. return 0;
  827. }
  828. static int read_user_input(std::string & user_input) {
  829. static const char * prompt_prefix = "> ";
  830. #ifdef WIN32
  831. printf("\r" LOG_CLR_TO_EOL LOG_COL_DEFAULT "%s", prompt_prefix);
  832. std::getline(std::cin, user_input);
  833. if (std::cin.eof()) {
  834. printf("\n");
  835. return 1;
  836. }
  837. #else
  838. std::unique_ptr<char, decltype(&std::free)> line(const_cast<char *>(linenoise(prompt_prefix)), free);
  839. if (!line) {
  840. return 1;
  841. }
  842. user_input = line.get();
  843. #endif
  844. if (user_input == "/bye") {
  845. return 1;
  846. }
  847. if (user_input.empty()) {
  848. return 2;
  849. }
  850. #ifndef WIN32
  851. linenoiseHistoryAdd(line.get());
  852. #endif
  853. return 0; // Should have data in happy path
  854. }
  855. // Function to generate a response based on the prompt
  856. static int generate_response(LlamaData & llama_data, const std::string & prompt, std::string & response,
  857. const bool stdout_a_terminal) {
  858. // Set response color
  859. if (stdout_a_terminal) {
  860. printf(LOG_COL_YELLOW);
  861. }
  862. if (generate(llama_data, prompt, response)) {
  863. printe("failed to generate response\n");
  864. return 1;
  865. }
  866. // End response with color reset and newline
  867. printf("\n%s", stdout_a_terminal ? LOG_COL_DEFAULT : "");
  868. return 0;
  869. }
  870. // Helper function to apply the chat template and handle errors
  871. 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) {
  872. const int new_len = apply_chat_template(tmpls, llama_data, append, use_jinja);
  873. if (new_len < 0) {
  874. printe("failed to apply the chat template\n");
  875. return -1;
  876. }
  877. output_length = new_len;
  878. return 0;
  879. }
  880. // Helper function to handle user input
  881. static int handle_user_input(std::string & user_input, const std::string & user) {
  882. if (!user.empty()) {
  883. user_input = user;
  884. return 0; // No need for interactive input
  885. }
  886. return read_user_input(user_input); // Returns true if input ends the loop
  887. }
  888. static bool is_stdin_a_terminal() {
  889. #if defined(_WIN32)
  890. HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
  891. DWORD mode;
  892. return GetConsoleMode(hStdin, &mode);
  893. #else
  894. return isatty(STDIN_FILENO);
  895. #endif
  896. }
  897. static bool is_stdout_a_terminal() {
  898. #if defined(_WIN32)
  899. HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  900. DWORD mode;
  901. return GetConsoleMode(hStdout, &mode);
  902. #else
  903. return isatty(STDOUT_FILENO);
  904. #endif
  905. }
  906. // Function to handle user input
  907. static int get_user_input(std::string & user_input, const std::string & user) {
  908. while (true) {
  909. const int ret = handle_user_input(user_input, user);
  910. if (ret == 1) {
  911. return 1;
  912. }
  913. if (ret == 2) {
  914. continue;
  915. }
  916. break;
  917. }
  918. return 0;
  919. }
  920. // Reads a chat template file to be used
  921. static std::string read_chat_template_file(const std::string & chat_template_file) {
  922. if(chat_template_file.empty()){
  923. return "";
  924. }
  925. File file;
  926. std::string chat_template = "";
  927. chat_template = file.read_all(chat_template_file);
  928. if(chat_template.empty()){
  929. printe("Error opening chat template file '%s': %s", chat_template_file.c_str(), strerror(errno));
  930. return "";
  931. }
  932. return chat_template;
  933. }
  934. // Main chat loop function
  935. static int chat_loop(LlamaData & llama_data, const std::string & user, const std::string & chat_template_file, bool use_jinja) {
  936. int prev_len = 0;
  937. llama_data.fmtted.resize(llama_n_ctx(llama_data.context.get()));
  938. std::string chat_template = "";
  939. if(!chat_template_file.empty()){
  940. chat_template = read_chat_template_file(chat_template_file);
  941. }
  942. auto chat_templates = common_chat_templates_init(llama_data.model.get(), chat_template.empty() ? nullptr : chat_template);
  943. static const bool stdout_a_terminal = is_stdout_a_terminal();
  944. while (true) {
  945. // Get user input
  946. std::string user_input;
  947. if (get_user_input(user_input, user) == 1) {
  948. return 0;
  949. }
  950. add_message("user", user.empty() ? user_input : user, llama_data);
  951. int new_len;
  952. if (apply_chat_template_with_error_handling(chat_templates.get(), llama_data, true, new_len, use_jinja) < 0) {
  953. return 1;
  954. }
  955. std::string prompt(llama_data.fmtted.begin() + prev_len, llama_data.fmtted.begin() + new_len);
  956. std::string response;
  957. if (generate_response(llama_data, prompt, response, stdout_a_terminal)) {
  958. return 1;
  959. }
  960. if (!user.empty()) {
  961. break;
  962. }
  963. add_message("assistant", response, llama_data);
  964. if (apply_chat_template_with_error_handling(chat_templates.get(), llama_data, false, prev_len, use_jinja) < 0) {
  965. return 1;
  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.user, opt.chat_template_file, opt.use_jinja)) {
  1016. return 1;
  1017. }
  1018. return 0;
  1019. }