common.cpp 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <fstream>
  9. #include <iterator>
  10. #include <iostream>
  11. #include <regex>
  12. #include <sstream>
  13. #include <string>
  14. #include <unordered_map>
  15. #include <unordered_set>
  16. #include <vector>
  17. #include <cinttypes>
  18. #if defined(__APPLE__) && defined(__MACH__)
  19. #include <sys/types.h>
  20. #include <sys/sysctl.h>
  21. #endif
  22. #if defined(_WIN32)
  23. #define WIN32_LEAN_AND_MEAN
  24. #ifndef NOMINMAX
  25. # define NOMINMAX
  26. #endif
  27. #include <codecvt>
  28. #include <locale>
  29. #include <windows.h>
  30. #include <fcntl.h>
  31. #include <io.h>
  32. #else
  33. #include <sys/ioctl.h>
  34. #include <sys/stat.h>
  35. #include <unistd.h>
  36. #endif
  37. #if defined(LLAMA_USE_CURL)
  38. #include <curl/curl.h>
  39. #endif
  40. #if defined(_MSC_VER)
  41. #pragma warning(disable: 4244 4267) // possible loss of data
  42. #endif
  43. #if (defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL))
  44. #define GGML_USE_CUBLAS_SYCL
  45. #endif
  46. #if (defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)) || defined(GGML_USE_VULKAN)
  47. #define GGML_USE_CUBLAS_SYCL_VULKAN
  48. #endif
  49. #if defined(LLAMA_USE_CURL)
  50. #ifdef __linux__
  51. #include <linux/limits.h>
  52. #elif defined(_WIN32)
  53. #define PATH_MAX MAX_PATH
  54. #else
  55. #include <sys/syslimits.h>
  56. #endif
  57. #define LLAMA_CURL_MAX_PATH_LENGTH PATH_MAX
  58. #define LLAMA_CURL_MAX_HEADER_LENGTH 256
  59. #endif // LLAMA_USE_CURL
  60. int32_t get_num_physical_cores() {
  61. #ifdef __linux__
  62. // enumerate the set of thread siblings, num entries is num cores
  63. std::unordered_set<std::string> siblings;
  64. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  65. std::ifstream thread_siblings("/sys/devices/system/cpu"
  66. + std::to_string(cpu) + "/topology/thread_siblings");
  67. if (!thread_siblings.is_open()) {
  68. break; // no more cpus
  69. }
  70. std::string line;
  71. if (std::getline(thread_siblings, line)) {
  72. siblings.insert(line);
  73. }
  74. }
  75. if (!siblings.empty()) {
  76. return static_cast<int32_t>(siblings.size());
  77. }
  78. #elif defined(__APPLE__) && defined(__MACH__)
  79. int32_t num_physical_cores;
  80. size_t len = sizeof(num_physical_cores);
  81. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  82. if (result == 0) {
  83. return num_physical_cores;
  84. }
  85. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  86. if (result == 0) {
  87. return num_physical_cores;
  88. }
  89. #elif defined(_WIN32)
  90. //TODO: Implement
  91. #endif
  92. unsigned int n_threads = std::thread::hardware_concurrency();
  93. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  94. }
  95. void process_escapes(std::string& input) {
  96. std::size_t input_len = input.length();
  97. std::size_t output_idx = 0;
  98. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  99. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  100. switch (input[++input_idx]) {
  101. case 'n': input[output_idx++] = '\n'; break;
  102. case 'r': input[output_idx++] = '\r'; break;
  103. case 't': input[output_idx++] = '\t'; break;
  104. case '\'': input[output_idx++] = '\''; break;
  105. case '\"': input[output_idx++] = '\"'; break;
  106. case '\\': input[output_idx++] = '\\'; break;
  107. case 'x':
  108. // Handle \x12, etc
  109. if (input_idx + 2 < input_len) {
  110. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  111. char *err_p = nullptr;
  112. const long val = std::strtol(x, &err_p, 16);
  113. if (err_p == x + 2) {
  114. input_idx += 2;
  115. input[output_idx++] = char(val);
  116. break;
  117. }
  118. }
  119. // fall through
  120. default: input[output_idx++] = '\\';
  121. input[output_idx++] = input[input_idx]; break;
  122. }
  123. } else {
  124. input[output_idx++] = input[input_idx];
  125. }
  126. }
  127. input.resize(output_idx);
  128. }
  129. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  130. bool result = true;
  131. try {
  132. if (!gpt_params_parse_ex(argc, argv, params)) {
  133. gpt_print_usage(argc, argv, gpt_params());
  134. exit(0);
  135. }
  136. }
  137. catch (const std::invalid_argument & ex) {
  138. fprintf(stderr, "%s\n", ex.what());
  139. gpt_print_usage(argc, argv, gpt_params());
  140. exit(1);
  141. }
  142. return result;
  143. }
  144. bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
  145. bool invalid_param = false;
  146. std::string arg;
  147. const std::string arg_prefix = "--";
  148. llama_sampling_params & sparams = params.sparams;
  149. for (int i = 1; i < argc; i++) {
  150. arg = argv[i];
  151. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  152. std::replace(arg.begin(), arg.end(), '_', '-');
  153. }
  154. bool arg_found = false;
  155. if (arg == "-s" || arg == "--seed") {
  156. arg_found = true;
  157. if (++i >= argc) {
  158. invalid_param = true;
  159. break;
  160. }
  161. params.seed = std::stoul(argv[i]);
  162. }
  163. if (arg == "-t" || arg == "--threads") {
  164. arg_found = true;
  165. if (++i >= argc) {
  166. invalid_param = true;
  167. break;
  168. }
  169. params.n_threads = std::stoi(argv[i]);
  170. if (params.n_threads <= 0) {
  171. params.n_threads = std::thread::hardware_concurrency();
  172. }
  173. }
  174. if (arg == "-tb" || arg == "--threads-batch") {
  175. arg_found = true;
  176. if (++i >= argc) {
  177. invalid_param = true;
  178. break;
  179. }
  180. params.n_threads_batch = std::stoi(argv[i]);
  181. if (params.n_threads_batch <= 0) {
  182. params.n_threads_batch = std::thread::hardware_concurrency();
  183. }
  184. }
  185. if (arg == "-td" || arg == "--threads-draft") {
  186. arg_found = true;
  187. if (++i >= argc) {
  188. invalid_param = true;
  189. break;
  190. }
  191. params.n_threads_draft = std::stoi(argv[i]);
  192. if (params.n_threads_draft <= 0) {
  193. params.n_threads_draft = std::thread::hardware_concurrency();
  194. }
  195. }
  196. if (arg == "-tbd" || arg == "--threads-batch-draft") {
  197. arg_found = true;
  198. if (++i >= argc) {
  199. invalid_param = true;
  200. break;
  201. }
  202. params.n_threads_batch_draft = std::stoi(argv[i]);
  203. if (params.n_threads_batch_draft <= 0) {
  204. params.n_threads_batch_draft = std::thread::hardware_concurrency();
  205. }
  206. }
  207. if (arg == "-p" || arg == "--prompt") {
  208. arg_found = true;
  209. if (++i >= argc) {
  210. invalid_param = true;
  211. break;
  212. }
  213. params.prompt = argv[i];
  214. }
  215. if (arg == "-e" || arg == "--escape") {
  216. arg_found = true;
  217. params.escape = true;
  218. }
  219. if (arg == "--prompt-cache") {
  220. arg_found = true;
  221. if (++i >= argc) {
  222. invalid_param = true;
  223. break;
  224. }
  225. params.path_prompt_cache = argv[i];
  226. }
  227. if (arg == "--prompt-cache-all") {
  228. arg_found = true;
  229. params.prompt_cache_all = true;
  230. }
  231. if (arg == "--prompt-cache-ro") {
  232. arg_found = true;
  233. params.prompt_cache_ro = true;
  234. }
  235. if (arg == "-bf" || arg == "--binary-file") {
  236. arg_found = true;
  237. if (++i >= argc) {
  238. invalid_param = true;
  239. break;
  240. }
  241. std::ifstream file(argv[i], std::ios::binary);
  242. if (!file) {
  243. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  244. invalid_param = true;
  245. break;
  246. }
  247. // store the external file name in params
  248. params.prompt_file = argv[i];
  249. std::ostringstream ss;
  250. ss << file.rdbuf();
  251. params.prompt = ss.str();
  252. fprintf(stderr, "Read %zu bytes from binary file %s\n", params.prompt.size(), argv[i]);
  253. }
  254. if (arg == "-f" || arg == "--file") {
  255. arg_found = true;
  256. if (++i >= argc) {
  257. invalid_param = true;
  258. break;
  259. }
  260. std::ifstream file(argv[i]);
  261. if (!file) {
  262. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  263. invalid_param = true;
  264. break;
  265. }
  266. // store the external file name in params
  267. params.prompt_file = argv[i];
  268. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  269. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  270. params.prompt.pop_back();
  271. }
  272. }
  273. if (arg == "-n" || arg == "--n-predict") {
  274. arg_found = true;
  275. if (++i >= argc) {
  276. invalid_param = true;
  277. break;
  278. }
  279. params.n_predict = std::stoi(argv[i]);
  280. }
  281. if (arg == "--top-k") {
  282. arg_found = true;
  283. if (++i >= argc) {
  284. invalid_param = true;
  285. break;
  286. }
  287. sparams.top_k = std::stoi(argv[i]);
  288. }
  289. if (arg == "-c" || arg == "--ctx-size") {
  290. arg_found = true;
  291. if (++i >= argc) {
  292. invalid_param = true;
  293. break;
  294. }
  295. params.n_ctx = std::stoi(argv[i]);
  296. }
  297. if (arg == "--grp-attn-n" || arg == "-gan") {
  298. arg_found = true;
  299. if (++i >= argc) {
  300. invalid_param = true;
  301. break;
  302. }
  303. params.grp_attn_n = std::stoi(argv[i]);
  304. }
  305. if (arg == "--grp-attn-w" || arg == "-gaw") {
  306. arg_found = true;
  307. if (++i >= argc) {
  308. invalid_param = true;
  309. break;
  310. }
  311. params.grp_attn_w = std::stoi(argv[i]);
  312. }
  313. if (arg == "--rope-freq-base") {
  314. arg_found = true;
  315. if (++i >= argc) {
  316. invalid_param = true;
  317. break;
  318. }
  319. params.rope_freq_base = std::stof(argv[i]);
  320. }
  321. if (arg == "--rope-freq-scale") {
  322. arg_found = true;
  323. if (++i >= argc) {
  324. invalid_param = true;
  325. break;
  326. }
  327. params.rope_freq_scale = std::stof(argv[i]);
  328. }
  329. if (arg == "--rope-scaling") {
  330. arg_found = true;
  331. if (++i >= argc) {
  332. invalid_param = true;
  333. break;
  334. }
  335. std::string value(argv[i]);
  336. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  337. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  338. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  339. else { invalid_param = true; break; }
  340. }
  341. if (arg == "--rope-scale") {
  342. arg_found = true;
  343. if (++i >= argc) {
  344. invalid_param = true;
  345. break;
  346. }
  347. params.rope_freq_scale = 1.0f/std::stof(argv[i]);
  348. }
  349. if (arg == "--yarn-orig-ctx") {
  350. arg_found = true;
  351. if (++i >= argc) {
  352. invalid_param = true;
  353. break;
  354. }
  355. params.yarn_orig_ctx = std::stoi(argv[i]);
  356. }
  357. if (arg == "--yarn-ext-factor") {
  358. arg_found = true;
  359. if (++i >= argc) {
  360. invalid_param = true;
  361. break;
  362. }
  363. params.yarn_ext_factor = std::stof(argv[i]);
  364. }
  365. if (arg == "--yarn-attn-factor") {
  366. arg_found = true;
  367. if (++i >= argc) {
  368. invalid_param = true;
  369. break;
  370. }
  371. params.yarn_attn_factor = std::stof(argv[i]);
  372. }
  373. if (arg == "--yarn-beta-fast") {
  374. arg_found = true;
  375. if (++i >= argc) {
  376. invalid_param = true;
  377. break;
  378. }
  379. params.yarn_beta_fast = std::stof(argv[i]);
  380. }
  381. if (arg == "--yarn-beta-slow") {
  382. arg_found = true;
  383. if (++i >= argc) {
  384. invalid_param = true;
  385. break;
  386. }
  387. params.yarn_beta_slow = std::stof(argv[i]);
  388. }
  389. if (arg == "--pooling") {
  390. arg_found = true;
  391. if (++i >= argc) {
  392. invalid_param = true;
  393. break;
  394. }
  395. std::string value(argv[i]);
  396. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  397. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  398. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  399. else { invalid_param = true; break; }
  400. }
  401. if (arg == "--defrag-thold" || arg == "-dt") {
  402. arg_found = true;
  403. if (++i >= argc) {
  404. invalid_param = true;
  405. break;
  406. }
  407. params.defrag_thold = std::stof(argv[i]);
  408. }
  409. if (arg == "--samplers") {
  410. arg_found = true;
  411. if (++i >= argc) {
  412. invalid_param = true;
  413. break;
  414. }
  415. const auto sampler_names = string_split(argv[i], ';');
  416. sparams.samplers_sequence = sampler_types_from_names(sampler_names, true);
  417. }
  418. if (arg == "--sampling-seq") {
  419. arg_found = true;
  420. if (++i >= argc) {
  421. invalid_param = true;
  422. break;
  423. }
  424. sparams.samplers_sequence = sampler_types_from_chars(argv[i]);
  425. }
  426. if (arg == "--top-p") {
  427. arg_found = true;
  428. if (++i >= argc) {
  429. invalid_param = true;
  430. break;
  431. }
  432. sparams.top_p = std::stof(argv[i]);
  433. }
  434. if (arg == "--min-p") {
  435. arg_found = true;
  436. if (++i >= argc) {
  437. invalid_param = true;
  438. break;
  439. }
  440. sparams.min_p = std::stof(argv[i]);
  441. }
  442. if (arg == "--temp") {
  443. arg_found = true;
  444. if (++i >= argc) {
  445. invalid_param = true;
  446. break;
  447. }
  448. sparams.temp = std::stof(argv[i]);
  449. sparams.temp = std::max(sparams.temp, 0.0f);
  450. }
  451. if (arg == "--tfs") {
  452. arg_found = true;
  453. if (++i >= argc) {
  454. invalid_param = true;
  455. break;
  456. }
  457. sparams.tfs_z = std::stof(argv[i]);
  458. }
  459. if (arg == "--typical") {
  460. arg_found = true;
  461. if (++i >= argc) {
  462. invalid_param = true;
  463. break;
  464. }
  465. sparams.typical_p = std::stof(argv[i]);
  466. }
  467. if (arg == "--repeat-last-n") {
  468. arg_found = true;
  469. if (++i >= argc) {
  470. invalid_param = true;
  471. break;
  472. }
  473. sparams.penalty_last_n = std::stoi(argv[i]);
  474. sparams.n_prev = std::max(sparams.n_prev, sparams.penalty_last_n);
  475. }
  476. if (arg == "--repeat-penalty") {
  477. arg_found = true;
  478. if (++i >= argc) {
  479. invalid_param = true;
  480. break;
  481. }
  482. sparams.penalty_repeat = std::stof(argv[i]);
  483. }
  484. if (arg == "--frequency-penalty") {
  485. arg_found = true;
  486. if (++i >= argc) {
  487. invalid_param = true;
  488. break;
  489. }
  490. sparams.penalty_freq = std::stof(argv[i]);
  491. }
  492. if (arg == "--presence-penalty") {
  493. arg_found = true;
  494. if (++i >= argc) {
  495. invalid_param = true;
  496. break;
  497. }
  498. sparams.penalty_present = std::stof(argv[i]);
  499. }
  500. if (arg == "--dynatemp-range") {
  501. arg_found = true;
  502. if (++i >= argc) {
  503. invalid_param = true;
  504. break;
  505. }
  506. sparams.dynatemp_range = std::stof(argv[i]);
  507. }
  508. if (arg == "--dynatemp-exp") {
  509. arg_found = true;
  510. if (++i >= argc) {
  511. invalid_param = true;
  512. break;
  513. }
  514. sparams.dynatemp_exponent = std::stof(argv[i]);
  515. }
  516. if (arg == "--mirostat") {
  517. arg_found = true;
  518. if (++i >= argc) {
  519. invalid_param = true;
  520. break;
  521. }
  522. sparams.mirostat = std::stoi(argv[i]);
  523. }
  524. if (arg == "--mirostat-lr") {
  525. arg_found = true;
  526. if (++i >= argc) {
  527. invalid_param = true;
  528. break;
  529. }
  530. sparams.mirostat_eta = std::stof(argv[i]);
  531. }
  532. if (arg == "--mirostat-ent") {
  533. arg_found = true;
  534. if (++i >= argc) {
  535. invalid_param = true;
  536. break;
  537. }
  538. sparams.mirostat_tau = std::stof(argv[i]);
  539. }
  540. if (arg == "--cfg-negative-prompt") {
  541. arg_found = true;
  542. if (++i >= argc) {
  543. invalid_param = true;
  544. break;
  545. }
  546. sparams.cfg_negative_prompt = argv[i];
  547. }
  548. if (arg == "--cfg-negative-prompt-file") {
  549. arg_found = true;
  550. if (++i >= argc) {
  551. invalid_param = true;
  552. break;
  553. }
  554. std::ifstream file(argv[i]);
  555. if (!file) {
  556. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  557. invalid_param = true;
  558. break;
  559. }
  560. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(sparams.cfg_negative_prompt));
  561. if (!sparams.cfg_negative_prompt.empty() && sparams.cfg_negative_prompt.back() == '\n') {
  562. sparams.cfg_negative_prompt.pop_back();
  563. }
  564. }
  565. if (arg == "--cfg-scale") {
  566. arg_found = true;
  567. if (++i >= argc) {
  568. invalid_param = true;
  569. break;
  570. }
  571. sparams.cfg_scale = std::stof(argv[i]);
  572. }
  573. if (arg == "-b" || arg == "--batch-size") {
  574. arg_found = true;
  575. if (++i >= argc) {
  576. invalid_param = true;
  577. break;
  578. }
  579. params.n_batch = std::stoi(argv[i]);
  580. }
  581. if (arg == "-ub" || arg == "--ubatch-size") {
  582. arg_found = true;
  583. if (++i >= argc) {
  584. invalid_param = true;
  585. break;
  586. }
  587. params.n_ubatch = std::stoi(argv[i]);
  588. }
  589. if (arg == "--keep") {
  590. arg_found = true;
  591. if (++i >= argc) {
  592. invalid_param = true;
  593. break;
  594. }
  595. params.n_keep = std::stoi(argv[i]);
  596. }
  597. if (arg == "--draft") {
  598. arg_found = true;
  599. if (++i >= argc) {
  600. invalid_param = true;
  601. break;
  602. }
  603. params.n_draft = std::stoi(argv[i]);
  604. }
  605. if (arg == "--chunks") {
  606. arg_found = true;
  607. if (++i >= argc) {
  608. invalid_param = true;
  609. break;
  610. }
  611. params.n_chunks = std::stoi(argv[i]);
  612. }
  613. if (arg == "-np" || arg == "--parallel") {
  614. arg_found = true;
  615. if (++i >= argc) {
  616. invalid_param = true;
  617. break;
  618. }
  619. params.n_parallel = std::stoi(argv[i]);
  620. }
  621. if (arg == "-ns" || arg == "--sequences") {
  622. arg_found = true;
  623. if (++i >= argc) {
  624. invalid_param = true;
  625. break;
  626. }
  627. params.n_sequences = std::stoi(argv[i]);
  628. }
  629. if (arg == "--p-split" || arg == "-ps") {
  630. arg_found = true;
  631. if (++i >= argc) {
  632. invalid_param = true;
  633. break;
  634. }
  635. params.p_split = std::stof(argv[i]);
  636. }
  637. if (arg == "-m" || arg == "--model") {
  638. arg_found = true;
  639. if (++i >= argc) {
  640. invalid_param = true;
  641. break;
  642. }
  643. params.model = argv[i];
  644. }
  645. if (arg == "-mu" || arg == "--model-url") {
  646. if (++i >= argc) {
  647. invalid_param = true;
  648. break;
  649. }
  650. params.model_url = argv[i];
  651. }
  652. if (arg == "-md" || arg == "--model-draft") {
  653. arg_found = true;
  654. if (++i >= argc) {
  655. invalid_param = true;
  656. break;
  657. }
  658. params.model_draft = argv[i];
  659. }
  660. if (arg == "-a" || arg == "--alias") {
  661. arg_found = true;
  662. if (++i >= argc) {
  663. invalid_param = true;
  664. break;
  665. }
  666. params.model_alias = argv[i];
  667. }
  668. if (arg == "--lora") {
  669. arg_found = true;
  670. if (++i >= argc) {
  671. invalid_param = true;
  672. break;
  673. }
  674. params.lora_adapter.emplace_back(argv[i], 1.0f);
  675. params.use_mmap = false;
  676. }
  677. if (arg == "--lora-scaled") {
  678. arg_found = true;
  679. if (++i >= argc) {
  680. invalid_param = true;
  681. break;
  682. }
  683. const char * lora_adapter = argv[i];
  684. if (++i >= argc) {
  685. invalid_param = true;
  686. break;
  687. }
  688. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  689. params.use_mmap = false;
  690. }
  691. if (arg == "--lora-base") {
  692. arg_found = true;
  693. if (++i >= argc) {
  694. invalid_param = true;
  695. break;
  696. }
  697. params.lora_base = argv[i];
  698. }
  699. if (arg == "--control-vector") {
  700. arg_found = true;
  701. if (++i >= argc) {
  702. invalid_param = true;
  703. break;
  704. }
  705. params.control_vectors.push_back({ 1.0f, argv[i], });
  706. }
  707. if (arg == "--control-vector-scaled") {
  708. arg_found = true;
  709. if (++i >= argc) {
  710. invalid_param = true;
  711. break;
  712. }
  713. const char * fname = argv[i];
  714. if (++i >= argc) {
  715. invalid_param = true;
  716. break;
  717. }
  718. params.control_vectors.push_back({ std::stof(argv[i]), fname, });
  719. }
  720. if (arg == "--control-vector-layer-range") {
  721. arg_found = true;
  722. if (++i >= argc) {
  723. invalid_param = true;
  724. break;
  725. }
  726. params.control_vector_layer_start = std::stoi(argv[i]);
  727. if (++i >= argc) {
  728. invalid_param = true;
  729. break;
  730. }
  731. params.control_vector_layer_end = std::stoi(argv[i]);
  732. }
  733. if (arg == "--mmproj") {
  734. arg_found = true;
  735. if (++i >= argc) {
  736. invalid_param = true;
  737. break;
  738. }
  739. params.mmproj = argv[i];
  740. }
  741. if (arg == "--image") {
  742. arg_found = true;
  743. if (++i >= argc) {
  744. invalid_param = true;
  745. break;
  746. }
  747. params.image = argv[i];
  748. }
  749. if (arg == "-i" || arg == "--interactive") {
  750. arg_found = true;
  751. params.interactive = true;
  752. }
  753. if (arg == "--embedding") {
  754. arg_found = true;
  755. params.embedding = true;
  756. }
  757. if (arg == "--interactive-first") {
  758. arg_found = true;
  759. params.interactive_first = true;
  760. }
  761. if (arg == "-ins" || arg == "--instruct") {
  762. arg_found = true;
  763. params.instruct = true;
  764. }
  765. if (arg == "-cml" || arg == "--chatml") {
  766. arg_found = true;
  767. params.chatml = true;
  768. }
  769. if (arg == "--infill") {
  770. arg_found = true;
  771. params.infill = true;
  772. }
  773. if (arg == "-dkvc" || arg == "--dump-kv-cache") {
  774. arg_found = true;
  775. params.dump_kv_cache = true;
  776. }
  777. if (arg == "-nkvo" || arg == "--no-kv-offload") {
  778. arg_found = true;
  779. params.no_kv_offload = true;
  780. }
  781. if (arg == "-ctk" || arg == "--cache-type-k") {
  782. arg_found = true;
  783. params.cache_type_k = argv[++i];
  784. }
  785. if (arg == "-ctv" || arg == "--cache-type-v") {
  786. arg_found = true;
  787. params.cache_type_v = argv[++i];
  788. }
  789. if (arg == "--multiline-input") {
  790. arg_found = true;
  791. params.multiline_input = true;
  792. }
  793. if (arg == "--simple-io") {
  794. arg_found = true;
  795. params.simple_io = true;
  796. }
  797. if (arg == "-cb" || arg == "--cont-batching") {
  798. arg_found = true;
  799. params.cont_batching = true;
  800. }
  801. if (arg == "--color") {
  802. arg_found = true;
  803. params.use_color = true;
  804. }
  805. if (arg == "--mlock") {
  806. arg_found = true;
  807. params.use_mlock = true;
  808. }
  809. if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  810. arg_found = true;
  811. if (++i >= argc) {
  812. invalid_param = true;
  813. break;
  814. }
  815. params.n_gpu_layers = std::stoi(argv[i]);
  816. if (!llama_supports_gpu_offload()) {
  817. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  818. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  819. }
  820. }
  821. if (arg == "--gpu-layers-draft" || arg == "-ngld" || arg == "--n-gpu-layers-draft") {
  822. arg_found = true;
  823. if (++i >= argc) {
  824. invalid_param = true;
  825. break;
  826. }
  827. params.n_gpu_layers_draft = std::stoi(argv[i]);
  828. if (!llama_supports_gpu_offload()) {
  829. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers-draft option will be ignored\n");
  830. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  831. }
  832. }
  833. if (arg == "--main-gpu" || arg == "-mg") {
  834. arg_found = true;
  835. if (++i >= argc) {
  836. invalid_param = true;
  837. break;
  838. }
  839. params.main_gpu = std::stoi(argv[i]);
  840. #ifndef GGML_USE_CUBLAS_SYCL
  841. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL. Setting the main GPU has no effect.\n");
  842. #endif // GGML_USE_CUBLAS_SYCL
  843. }
  844. if (arg == "--split-mode" || arg == "-sm") {
  845. arg_found = true;
  846. if (++i >= argc) {
  847. invalid_param = true;
  848. break;
  849. }
  850. std::string arg_next = argv[i];
  851. if (arg_next == "none") {
  852. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  853. } else if (arg_next == "layer") {
  854. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  855. } else if (arg_next == "row") {
  856. #ifdef GGML_USE_SYCL
  857. fprintf(stderr, "warning: The split mode value:[row] is not supported by llama.cpp with SYCL. It's developing.\nExit!\n");
  858. exit(1);
  859. #endif // GGML_USE_SYCL
  860. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  861. } else {
  862. invalid_param = true;
  863. break;
  864. }
  865. #ifndef GGML_USE_CUBLAS_SYCL
  866. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL. Setting the split mode has no effect.\n");
  867. #endif // GGML_USE_CUBLAS_SYCL
  868. }
  869. if (arg == "--tensor-split" || arg == "-ts") {
  870. arg_found = true;
  871. if (++i >= argc) {
  872. invalid_param = true;
  873. break;
  874. }
  875. std::string arg_next = argv[i];
  876. // split string by , and /
  877. const std::regex regex{R"([,/]+)"};
  878. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  879. std::vector<std::string> split_arg{it, {}};
  880. if (split_arg.size() >= llama_max_devices()) {
  881. invalid_param = true;
  882. break;
  883. }
  884. for (size_t i = 0; i < llama_max_devices(); ++i) {
  885. if (i < split_arg.size()) {
  886. params.tensor_split[i] = std::stof(split_arg[i]);
  887. } else {
  888. params.tensor_split[i] = 0.0f;
  889. }
  890. }
  891. #ifndef GGML_USE_CUBLAS_SYCL_VULKAN
  892. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL/Vulkan. Setting a tensor split has no effect.\n");
  893. #endif // GGML_USE_CUBLAS_SYCL
  894. }
  895. if (arg == "--no-mmap") {
  896. arg_found = true;
  897. params.use_mmap = false;
  898. }
  899. if (arg == "--numa") {
  900. arg_found = true;
  901. if (++i >= argc) {
  902. invalid_param = true;
  903. break;
  904. }
  905. std::string value(argv[i]);
  906. /**/ if (value == "distribute" || value == "") { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  907. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  908. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  909. else { invalid_param = true; break; }
  910. }
  911. if (arg == "--verbose-prompt") {
  912. arg_found = true;
  913. params.verbose_prompt = true;
  914. }
  915. if (arg == "--no-display-prompt") {
  916. arg_found = true;
  917. params.display_prompt = false;
  918. }
  919. if (arg == "-r" || arg == "--reverse-prompt") {
  920. arg_found = true;
  921. if (++i >= argc) {
  922. invalid_param = true;
  923. break;
  924. }
  925. params.antiprompt.emplace_back(argv[i]);
  926. }
  927. if (arg == "-ld" || arg == "--logdir") {
  928. arg_found = true;
  929. if (++i >= argc) {
  930. invalid_param = true;
  931. break;
  932. }
  933. params.logdir = argv[i];
  934. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  935. params.logdir += DIRECTORY_SEPARATOR;
  936. }
  937. }
  938. if (arg == "--save-all-logits" || arg == "--kl-divergence-base") {
  939. arg_found = true;
  940. if (++i >= argc) {
  941. invalid_param = true;
  942. break;
  943. }
  944. params.logits_file = argv[i];
  945. }
  946. if (arg == "--perplexity" || arg == "--all-logits") {
  947. arg_found = true;
  948. params.logits_all = true;
  949. }
  950. if (arg == "--ppl-stride") {
  951. arg_found = true;
  952. if (++i >= argc) {
  953. invalid_param = true;
  954. break;
  955. }
  956. params.ppl_stride = std::stoi(argv[i]);
  957. }
  958. if (arg == "-ptc" || arg == "--print-token-count") {
  959. arg_found = true;
  960. if (++i >= argc) {
  961. invalid_param = true;
  962. break;
  963. }
  964. params.n_print = std::stoi(argv[i]);
  965. }
  966. if (arg == "--ppl-output-type") {
  967. arg_found = true;
  968. if (++i >= argc) {
  969. invalid_param = true;
  970. break;
  971. }
  972. params.ppl_output_type = std::stoi(argv[i]);
  973. }
  974. if (arg == "--hellaswag") {
  975. arg_found = true;
  976. params.hellaswag = true;
  977. }
  978. if (arg == "--hellaswag-tasks") {
  979. arg_found = true;
  980. if (++i >= argc) {
  981. invalid_param = true;
  982. break;
  983. }
  984. params.hellaswag_tasks = std::stoi(argv[i]);
  985. }
  986. if (arg == "--winogrande") {
  987. arg_found = true;
  988. params.winogrande = true;
  989. }
  990. if (arg == "--winogrande-tasks") {
  991. arg_found = true;
  992. if (++i >= argc) {
  993. invalid_param = true;
  994. break;
  995. }
  996. params.winogrande_tasks = std::stoi(argv[i]);
  997. }
  998. if (arg == "--multiple-choice") {
  999. arg_found = true;
  1000. params.multiple_choice = true;
  1001. }
  1002. if (arg == "--multiple-choice-tasks") {
  1003. arg_found = true;
  1004. if (++i >= argc) {
  1005. invalid_param = true;
  1006. break;
  1007. }
  1008. params.multiple_choice_tasks = std::stoi(argv[i]);
  1009. }
  1010. if (arg == "--kl-divergence") {
  1011. arg_found = true;
  1012. params.kl_divergence = true;
  1013. }
  1014. if (arg == "--ignore-eos") {
  1015. arg_found = true;
  1016. params.ignore_eos = true;
  1017. }
  1018. if (arg == "--no-penalize-nl") {
  1019. arg_found = true;
  1020. sparams.penalize_nl = false;
  1021. }
  1022. if (arg == "-l" || arg == "--logit-bias") {
  1023. arg_found = true;
  1024. if (++i >= argc) {
  1025. invalid_param = true;
  1026. break;
  1027. }
  1028. std::stringstream ss(argv[i]);
  1029. llama_token key;
  1030. char sign;
  1031. std::string value_str;
  1032. try {
  1033. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  1034. sparams.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  1035. } else {
  1036. throw std::exception();
  1037. }
  1038. } catch (const std::exception&) {
  1039. invalid_param = true;
  1040. break;
  1041. }
  1042. }
  1043. if (arg == "-h" || arg == "--help") {
  1044. arg_found = true;
  1045. return false;
  1046. }
  1047. if (arg == "--version") {
  1048. arg_found = true;
  1049. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  1050. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  1051. exit(0);
  1052. }
  1053. if (arg == "--random-prompt") {
  1054. arg_found = true;
  1055. params.random_prompt = true;
  1056. }
  1057. if (arg == "--in-prefix-bos") {
  1058. arg_found = true;
  1059. params.input_prefix_bos = true;
  1060. }
  1061. if (arg == "--in-prefix") {
  1062. arg_found = true;
  1063. if (++i >= argc) {
  1064. invalid_param = true;
  1065. break;
  1066. }
  1067. params.input_prefix = argv[i];
  1068. }
  1069. if (arg == "--in-suffix") {
  1070. arg_found = true;
  1071. if (++i >= argc) {
  1072. invalid_param = true;
  1073. break;
  1074. }
  1075. params.input_suffix = argv[i];
  1076. }
  1077. if (arg == "--grammar") {
  1078. arg_found = true;
  1079. if (++i >= argc) {
  1080. invalid_param = true;
  1081. break;
  1082. }
  1083. sparams.grammar = argv[i];
  1084. }
  1085. if (arg == "--grammar-file") {
  1086. arg_found = true;
  1087. if (++i >= argc) {
  1088. invalid_param = true;
  1089. break;
  1090. }
  1091. std::ifstream file(argv[i]);
  1092. if (!file) {
  1093. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1094. invalid_param = true;
  1095. break;
  1096. }
  1097. std::copy(
  1098. std::istreambuf_iterator<char>(file),
  1099. std::istreambuf_iterator<char>(),
  1100. std::back_inserter(sparams.grammar)
  1101. );
  1102. }
  1103. if (arg == "--override-kv") {
  1104. arg_found = true;
  1105. if (++i >= argc) {
  1106. invalid_param = true;
  1107. break;
  1108. }
  1109. char * sep = strchr(argv[i], '=');
  1110. if (sep == nullptr || sep - argv[i] >= 128) {
  1111. fprintf(stderr, "error: Malformed KV override: %s\n", argv[i]);
  1112. invalid_param = true;
  1113. break;
  1114. }
  1115. struct llama_model_kv_override kvo;
  1116. std::strncpy(kvo.key, argv[i], sep - argv[i]);
  1117. kvo.key[sep - argv[i]] = 0;
  1118. sep++;
  1119. if (strncmp(sep, "int:", 4) == 0) {
  1120. sep += 4;
  1121. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  1122. kvo.int_value = std::atol(sep);
  1123. } else if (strncmp(sep, "float:", 6) == 0) {
  1124. sep += 6;
  1125. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  1126. kvo.float_value = std::atof(sep);
  1127. } else if (strncmp(sep, "bool:", 5) == 0) {
  1128. sep += 5;
  1129. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  1130. if (std::strcmp(sep, "true") == 0) {
  1131. kvo.bool_value = true;
  1132. } else if (std::strcmp(sep, "false") == 0) {
  1133. kvo.bool_value = false;
  1134. } else {
  1135. fprintf(stderr, "error: Invalid boolean value for KV override: %s\n", argv[i]);
  1136. invalid_param = true;
  1137. break;
  1138. }
  1139. } else {
  1140. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  1141. invalid_param = true;
  1142. break;
  1143. }
  1144. params.kv_overrides.push_back(kvo);
  1145. #ifndef LOG_DISABLE_LOGS
  1146. // Parse args for logging parameters
  1147. }
  1148. if ( log_param_single_parse( argv[i] ) ) {
  1149. arg_found = true;
  1150. // Do nothing, log_param_single_parse automatically does it's thing
  1151. // and returns if a match was found and parsed.
  1152. }
  1153. if ( log_param_pair_parse( /*check_but_dont_parse*/ true, argv[i] ) ) {
  1154. arg_found = true;
  1155. // We have a matching known parameter requiring an argument,
  1156. // now we need to check if there is anything after this argv
  1157. // and flag invalid_param or parse it.
  1158. if (++i >= argc) {
  1159. invalid_param = true;
  1160. break;
  1161. }
  1162. if( !log_param_pair_parse( /*check_but_dont_parse*/ false, argv[i-1], argv[i]) ) {
  1163. invalid_param = true;
  1164. break;
  1165. }
  1166. // End of Parse args for logging parameters
  1167. #endif // LOG_DISABLE_LOGS
  1168. }
  1169. if (!arg_found) {
  1170. throw std::invalid_argument("error: unknown argument: " + arg);
  1171. }
  1172. }
  1173. if (invalid_param) {
  1174. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  1175. }
  1176. if (params.prompt_cache_all &&
  1177. (params.interactive || params.interactive_first ||
  1178. params.instruct)) {
  1179. throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
  1180. }
  1181. if (params.escape) {
  1182. process_escapes(params.prompt);
  1183. process_escapes(params.input_prefix);
  1184. process_escapes(params.input_suffix);
  1185. process_escapes(sparams.cfg_negative_prompt);
  1186. for (auto & antiprompt : params.antiprompt) {
  1187. process_escapes(antiprompt);
  1188. }
  1189. }
  1190. if (!params.kv_overrides.empty()) {
  1191. params.kv_overrides.emplace_back();
  1192. params.kv_overrides.back().key[0] = 0;
  1193. }
  1194. return true;
  1195. }
  1196. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  1197. const llama_sampling_params & sparams = params.sparams;
  1198. std::string sampler_type_chars;
  1199. std::string sampler_type_names;
  1200. for (const auto sampler_type : sparams.samplers_sequence) {
  1201. sampler_type_chars += static_cast<char>(sampler_type);
  1202. sampler_type_names += sampler_type_to_name_string(sampler_type) + ";";
  1203. }
  1204. sampler_type_names.pop_back();
  1205. printf("\n");
  1206. printf("usage: %s [options]\n", argv[0]);
  1207. printf("\n");
  1208. printf("options:\n");
  1209. printf(" -h, --help show this help message and exit\n");
  1210. printf(" --version show version and build info\n");
  1211. printf(" -i, --interactive run in interactive mode\n");
  1212. printf(" --interactive-first run in interactive mode and wait for input right away\n");
  1213. printf(" -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  1214. printf(" -cml, --chatml run in chatml mode (use with ChatML-compatible models)\n");
  1215. printf(" --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  1216. printf(" -r PROMPT, --reverse-prompt PROMPT\n");
  1217. printf(" halt generation at PROMPT, return control in interactive mode\n");
  1218. printf(" (can be specified more than once for multiple prompts).\n");
  1219. printf(" --color colorise output to distinguish prompt and user input from generations\n");
  1220. printf(" -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  1221. printf(" -t N, --threads N number of threads to use during generation (default: %d)\n", params.n_threads);
  1222. printf(" -tb N, --threads-batch N\n");
  1223. printf(" number of threads to use during batch and prompt processing (default: same as --threads)\n");
  1224. printf(" -td N, --threads-draft N");
  1225. printf(" number of threads to use during generation (default: same as --threads)\n");
  1226. printf(" -tbd N, --threads-batch-draft N\n");
  1227. printf(" number of threads to use during batch and prompt processing (default: same as --threads-draft)\n");
  1228. printf(" -p PROMPT, --prompt PROMPT\n");
  1229. printf(" prompt to start generation with (default: empty)\n");
  1230. printf(" -e, --escape process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  1231. printf(" --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  1232. printf(" --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  1233. printf(" not supported with --interactive or other interactive options\n");
  1234. printf(" --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  1235. printf(" --random-prompt start with a randomized prompt.\n");
  1236. printf(" --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  1237. printf(" --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  1238. printf(" --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  1239. printf(" -f FNAME, --file FNAME\n");
  1240. printf(" prompt file to start generation.\n");
  1241. printf(" -bf FNAME, --binary-file FNAME\n");
  1242. printf(" binary file containing multiple choice tasks.\n");
  1243. printf(" -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)\n", params.n_predict);
  1244. printf(" -c N, --ctx-size N size of the prompt context (default: %d, 0 = loaded from model)\n", params.n_ctx);
  1245. printf(" -b N, --batch-size N logical maximum batch size (default: %d)\n", params.n_batch);
  1246. printf(" -ub N, --ubatch-size N\n");
  1247. printf(" physical maximum batch size (default: %d)\n", params.n_ubatch);
  1248. printf(" --samplers samplers that will be used for generation in the order, separated by \';\'\n");
  1249. printf(" (default: %s)\n", sampler_type_names.c_str());
  1250. printf(" --sampling-seq simplified sequence for samplers that will be used (default: %s)\n", sampler_type_chars.c_str());
  1251. printf(" --top-k N top-k sampling (default: %d, 0 = disabled)\n", sparams.top_k);
  1252. printf(" --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)sparams.top_p);
  1253. printf(" --min-p N min-p sampling (default: %.1f, 0.0 = disabled)\n", (double)sparams.min_p);
  1254. printf(" --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)sparams.tfs_z);
  1255. printf(" --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)sparams.typical_p);
  1256. printf(" --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", sparams.penalty_last_n);
  1257. printf(" --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)sparams.penalty_repeat);
  1258. printf(" --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_present);
  1259. printf(" --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_freq);
  1260. printf(" --dynatemp-range N dynamic temperature range (default: %.1f, 0.0 = disabled)\n", (double)sparams.dynatemp_range);
  1261. printf(" --dynatemp-exp N dynamic temperature exponent (default: %.1f)\n", (double)sparams.dynatemp_exponent);
  1262. printf(" --mirostat N use Mirostat sampling.\n");
  1263. printf(" Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  1264. printf(" (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", sparams.mirostat);
  1265. printf(" --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)sparams.mirostat_eta);
  1266. printf(" --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)sparams.mirostat_tau);
  1267. printf(" -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  1268. printf(" modifies the likelihood of token appearing in the completion,\n");
  1269. printf(" i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  1270. printf(" or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  1271. printf(" --grammar GRAMMAR BNF-like grammar to constrain generations (see samples in grammars/ dir)\n");
  1272. printf(" --grammar-file FNAME file to read grammar from\n");
  1273. printf(" --cfg-negative-prompt PROMPT\n");
  1274. printf(" negative prompt to use for guidance. (default: empty)\n");
  1275. printf(" --cfg-negative-prompt-file FNAME\n");
  1276. printf(" negative prompt file to use for guidance. (default: empty)\n");
  1277. printf(" --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", sparams.cfg_scale);
  1278. printf(" --rope-scaling {none,linear,yarn}\n");
  1279. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  1280. printf(" --rope-scale N RoPE context scaling factor, expands context by a factor of N\n");
  1281. printf(" --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: loaded from model)\n");
  1282. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  1283. printf(" --yarn-orig-ctx N YaRN: original context size of model (default: 0 = model training context size)\n");
  1284. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  1285. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  1286. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  1287. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  1288. printf(" --pooling {none,mean,cls}\n");
  1289. printf(" pooling type for embeddings, use model default if unspecified\n");
  1290. printf(" -dt N, --defrag-thold N\n");
  1291. printf(" KV cache defragmentation threshold (default: %.1f, < 0 - disabled)\n", params.defrag_thold);
  1292. printf(" --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  1293. printf(" --no-penalize-nl do not penalize newline token\n");
  1294. printf(" --temp N temperature (default: %.1f)\n", (double)sparams.temp);
  1295. printf(" --all-logits return logits for all tokens in the batch (default: disabled)\n");
  1296. printf(" --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  1297. printf(" --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  1298. printf(" --winogrande compute Winogrande score over random tasks from datafile supplied with -f\n");
  1299. printf(" --winogrande-tasks N number of tasks to use when computing the Winogrande score (default: %zu)\n", params.winogrande_tasks);
  1300. printf(" --multiple-choice compute multiple choice score over random tasks from datafile supplied with -f\n");
  1301. printf(" --multiple-choice-tasks N number of tasks to use when computing the multiple choice score (default: %zu)\n", params.winogrande_tasks);
  1302. printf(" --kl-divergence computes KL-divergence to logits provided via --kl-divergence-base\n");
  1303. printf(" --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  1304. printf(" --draft N number of tokens to draft for speculative decoding (default: %d)\n", params.n_draft);
  1305. printf(" --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  1306. printf(" -np N, --parallel N number of parallel sequences to decode (default: %d)\n", params.n_parallel);
  1307. printf(" -ns N, --sequences N number of sequences to decode (default: %d)\n", params.n_sequences);
  1308. printf(" -ps N, --p-split N speculative decoding split probability (default: %.1f)\n", (double)params.p_split);
  1309. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  1310. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA. see examples/llava/README.md\n");
  1311. printf(" --image IMAGE_FILE path to an image file. use with multimodal models\n");
  1312. if (llama_supports_mlock()) {
  1313. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1314. }
  1315. if (llama_supports_mmap()) {
  1316. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1317. }
  1318. printf(" --numa TYPE attempt optimizations that help on some NUMA systems\n");
  1319. printf(" - distribute: spread execution evenly over all nodes\n");
  1320. printf(" - isolate: only spawn threads on CPUs on the node that execution started on\n");
  1321. printf(" - numactl: use the CPU map provided by numactl\n");
  1322. printf(" if run without this previously, it is recommended to drop the system page cache before using this\n");
  1323. printf(" see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  1324. if (llama_supports_gpu_offload()) {
  1325. printf(" -ngl N, --n-gpu-layers N\n");
  1326. printf(" number of layers to store in VRAM\n");
  1327. printf(" -ngld N, --n-gpu-layers-draft N\n");
  1328. printf(" number of layers to store in VRAM for the draft model\n");
  1329. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  1330. printf(" how to split the model across multiple GPUs, one of:\n");
  1331. printf(" - none: use one GPU only\n");
  1332. printf(" - layer (default): split layers and KV across GPUs\n");
  1333. printf(" - row: split rows across GPUs\n");
  1334. printf(" -ts SPLIT, --tensor-split SPLIT\n");
  1335. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  1336. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  1337. printf(" or for intermediate results and KV (with split-mode = row) (default: %d)\n", params.main_gpu);
  1338. }
  1339. printf(" --verbose-prompt print a verbose prompt before generation (default: %s)\n", params.verbose_prompt ? "true" : "false");
  1340. printf(" --no-display-prompt don't print prompt at generation (default: %s)\n", !params.display_prompt ? "true" : "false");
  1341. printf(" -gan N, --grp-attn-n N\n");
  1342. printf(" group-attention factor (default: %d)\n", params.grp_attn_n);
  1343. printf(" -gaw N, --grp-attn-w N\n");
  1344. printf(" group-attention width (default: %.1f)\n", (double)params.grp_attn_w);
  1345. printf(" -dkvc, --dump-kv-cache\n");
  1346. printf(" verbose print of the KV cache\n");
  1347. printf(" -nkvo, --no-kv-offload\n");
  1348. printf(" disable KV offload\n");
  1349. printf(" -ctk TYPE, --cache-type-k TYPE\n");
  1350. printf(" KV cache data type for K (default: %s)\n", params.cache_type_k.c_str());
  1351. printf(" -ctv TYPE, --cache-type-v TYPE\n");
  1352. printf(" KV cache data type for V (default: %s)\n", params.cache_type_v.c_str());
  1353. printf(" --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  1354. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1355. printf(" --lora-scaled FNAME S apply LoRA adapter with user defined scaling S (implies --no-mmap)\n");
  1356. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1357. printf(" --control-vector FNAME\n");
  1358. printf(" add a control vector\n");
  1359. printf(" --control-vector-scaled FNAME S\n");
  1360. printf(" add a control vector with user defined scaling S\n");
  1361. printf(" --control-vector-layer-range START END\n");
  1362. printf(" layer range to apply the control vector(s) to, start and end inclusive\n");
  1363. printf(" -m FNAME, --model FNAME\n");
  1364. printf(" model path (default: %s)\n", params.model.c_str());
  1365. printf(" -mu MODEL_URL, --model-url MODEL_URL\n");
  1366. printf(" model download url (default: %s)\n", params.model_url.c_str());
  1367. printf(" -md FNAME, --model-draft FNAME\n");
  1368. printf(" draft model for speculative decoding\n");
  1369. printf(" -ld LOGDIR, --logdir LOGDIR\n");
  1370. printf(" path under which to save YAML logs (no logging if unset)\n");
  1371. printf(" --override-kv KEY=TYPE:VALUE\n");
  1372. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  1373. printf(" types: int, float, bool. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  1374. printf(" -ptc N, --print-token-count N\n");
  1375. printf(" print token count every N tokens (default: %d)\n", params.n_print);
  1376. printf("\n");
  1377. #ifndef LOG_DISABLE_LOGS
  1378. log_print_usage();
  1379. #endif // LOG_DISABLE_LOGS
  1380. }
  1381. std::string get_system_info(const gpt_params & params) {
  1382. std::ostringstream os;
  1383. os << "system_info: n_threads = " << params.n_threads;
  1384. if (params.n_threads_batch != -1) {
  1385. os << " (n_threads_batch = " << params.n_threads_batch << ")";
  1386. }
  1387. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  1388. return os.str();
  1389. }
  1390. std::string gpt_random_prompt(std::mt19937 & rng) {
  1391. const int r = rng() % 10;
  1392. switch (r) {
  1393. case 0: return "So";
  1394. case 1: return "Once upon a time";
  1395. case 2: return "When";
  1396. case 3: return "The";
  1397. case 4: return "After";
  1398. case 5: return "If";
  1399. case 6: return "import";
  1400. case 7: return "He";
  1401. case 8: return "She";
  1402. case 9: return "They";
  1403. }
  1404. GGML_UNREACHABLE();
  1405. }
  1406. //
  1407. // String utils
  1408. //
  1409. std::vector<std::string> string_split(std::string input, char separator) {
  1410. std::vector<std::string> parts;
  1411. size_t separator_pos = input.find(separator);
  1412. while (separator_pos != std::string::npos) {
  1413. std::string part = input.substr(0, separator_pos);
  1414. parts.emplace_back(part);
  1415. input = input.substr(separator_pos + 1);
  1416. separator_pos = input.find(separator);
  1417. }
  1418. parts.emplace_back(input);
  1419. return parts;
  1420. }
  1421. std::vector<llama_sampler_type> sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
  1422. std::unordered_map<std::string, llama_sampler_type> sampler_canonical_name_map {
  1423. {"top_k", llama_sampler_type::TOP_K},
  1424. {"top_p", llama_sampler_type::TOP_P},
  1425. {"typical_p", llama_sampler_type::TYPICAL_P},
  1426. {"min_p", llama_sampler_type::MIN_P},
  1427. {"tfs_z", llama_sampler_type::TFS_Z},
  1428. {"temperature", llama_sampler_type::TEMPERATURE}
  1429. };
  1430. // since samplers names are written multiple ways
  1431. // make it ready for both system names and input names
  1432. std::unordered_map<std::string, llama_sampler_type> sampler_alt_name_map {
  1433. {"top-k", llama_sampler_type::TOP_K},
  1434. {"top-p", llama_sampler_type::TOP_P},
  1435. {"nucleus", llama_sampler_type::TOP_P},
  1436. {"typical-p", llama_sampler_type::TYPICAL_P},
  1437. {"typical", llama_sampler_type::TYPICAL_P},
  1438. {"min-p", llama_sampler_type::MIN_P},
  1439. {"tfs-z", llama_sampler_type::TFS_Z},
  1440. {"tfs", llama_sampler_type::TFS_Z},
  1441. {"temp", llama_sampler_type::TEMPERATURE}
  1442. };
  1443. std::vector<llama_sampler_type> sampler_types;
  1444. sampler_types.reserve(names.size());
  1445. for (const auto & name : names)
  1446. {
  1447. auto sampler_item = sampler_canonical_name_map.find(name);
  1448. if (sampler_item != sampler_canonical_name_map.end())
  1449. {
  1450. sampler_types.push_back(sampler_item->second);
  1451. }
  1452. else
  1453. {
  1454. if (allow_alt_names)
  1455. {
  1456. sampler_item = sampler_alt_name_map.find(name);
  1457. if (sampler_item != sampler_alt_name_map.end())
  1458. {
  1459. sampler_types.push_back(sampler_item->second);
  1460. }
  1461. }
  1462. }
  1463. }
  1464. return sampler_types;
  1465. }
  1466. std::vector<llama_sampler_type> sampler_types_from_chars(const std::string & names_string) {
  1467. std::unordered_map<char, llama_sampler_type> sampler_name_map {
  1468. {'k', llama_sampler_type::TOP_K},
  1469. {'p', llama_sampler_type::TOP_P},
  1470. {'y', llama_sampler_type::TYPICAL_P},
  1471. {'m', llama_sampler_type::MIN_P},
  1472. {'f', llama_sampler_type::TFS_Z},
  1473. {'t', llama_sampler_type::TEMPERATURE}
  1474. };
  1475. std::vector<llama_sampler_type> sampler_types;
  1476. sampler_types.reserve(names_string.size());
  1477. for (const auto & c : names_string) {
  1478. const auto sampler_item = sampler_name_map.find(c);
  1479. if (sampler_item != sampler_name_map.end()) {
  1480. sampler_types.push_back(sampler_item->second);
  1481. }
  1482. }
  1483. return sampler_types;
  1484. }
  1485. std::string sampler_type_to_name_string(llama_sampler_type sampler_type) {
  1486. switch (sampler_type) {
  1487. case llama_sampler_type::TOP_K: return "top_k";
  1488. case llama_sampler_type::TFS_Z: return "tfs_z";
  1489. case llama_sampler_type::TYPICAL_P: return "typical_p";
  1490. case llama_sampler_type::TOP_P: return "top_p";
  1491. case llama_sampler_type::MIN_P: return "min_p";
  1492. case llama_sampler_type::TEMPERATURE: return "temperature";
  1493. default : return "";
  1494. }
  1495. }
  1496. //
  1497. // Model utils
  1498. //
  1499. struct llama_model_params llama_model_params_from_gpt_params(const gpt_params & params) {
  1500. auto mparams = llama_model_default_params();
  1501. if (params.n_gpu_layers != -1) {
  1502. mparams.n_gpu_layers = params.n_gpu_layers;
  1503. }
  1504. mparams.main_gpu = params.main_gpu;
  1505. mparams.split_mode = params.split_mode;
  1506. mparams.tensor_split = params.tensor_split;
  1507. mparams.use_mmap = params.use_mmap;
  1508. mparams.use_mlock = params.use_mlock;
  1509. if (params.kv_overrides.empty()) {
  1510. mparams.kv_overrides = NULL;
  1511. } else {
  1512. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  1513. mparams.kv_overrides = params.kv_overrides.data();
  1514. }
  1515. return mparams;
  1516. }
  1517. static ggml_type kv_cache_type_from_str(const std::string & s) {
  1518. if (s == "f32") {
  1519. return GGML_TYPE_F32;
  1520. }
  1521. if (s == "f16") {
  1522. return GGML_TYPE_F16;
  1523. }
  1524. if (s == "q8_0") {
  1525. return GGML_TYPE_Q8_0;
  1526. }
  1527. if (s == "q4_0") {
  1528. return GGML_TYPE_Q4_0;
  1529. }
  1530. if (s == "q4_1") {
  1531. return GGML_TYPE_Q4_1;
  1532. }
  1533. if (s == "q5_0") {
  1534. return GGML_TYPE_Q5_0;
  1535. }
  1536. if (s == "q5_1") {
  1537. return GGML_TYPE_Q5_1;
  1538. }
  1539. throw std::runtime_error("Invalid cache type: " + s);
  1540. }
  1541. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  1542. auto cparams = llama_context_default_params();
  1543. cparams.n_ctx = params.n_ctx;
  1544. cparams.n_seq_max = params.n_parallel;
  1545. cparams.n_batch = params.n_batch;
  1546. cparams.n_ubatch = params.n_ubatch;
  1547. cparams.n_threads = params.n_threads;
  1548. cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  1549. cparams.seed = params.seed;
  1550. cparams.logits_all = params.logits_all;
  1551. cparams.embeddings = params.embedding;
  1552. cparams.rope_scaling_type = params.rope_scaling_type;
  1553. cparams.rope_freq_base = params.rope_freq_base;
  1554. cparams.rope_freq_scale = params.rope_freq_scale;
  1555. cparams.yarn_ext_factor = params.yarn_ext_factor;
  1556. cparams.yarn_attn_factor = params.yarn_attn_factor;
  1557. cparams.yarn_beta_fast = params.yarn_beta_fast;
  1558. cparams.yarn_beta_slow = params.yarn_beta_slow;
  1559. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  1560. cparams.pooling_type = params.pooling_type;
  1561. cparams.defrag_thold = params.defrag_thold;
  1562. cparams.offload_kqv = !params.no_kv_offload;
  1563. cparams.type_k = kv_cache_type_from_str(params.cache_type_k);
  1564. cparams.type_v = kv_cache_type_from_str(params.cache_type_v);
  1565. return cparams;
  1566. }
  1567. void llama_batch_clear(struct llama_batch & batch) {
  1568. batch.n_tokens = 0;
  1569. }
  1570. void llama_batch_add(
  1571. struct llama_batch & batch,
  1572. llama_token id,
  1573. llama_pos pos,
  1574. const std::vector<llama_seq_id> & seq_ids,
  1575. bool logits) {
  1576. batch.token [batch.n_tokens] = id;
  1577. batch.pos [batch.n_tokens] = pos;
  1578. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1579. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1580. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1581. }
  1582. batch.logits [batch.n_tokens] = logits;
  1583. batch.n_tokens++;
  1584. }
  1585. #ifdef LLAMA_USE_CURL
  1586. struct llama_model * llama_load_model_from_url(const char * model_url, const char * path_model,
  1587. struct llama_model_params params) {
  1588. // Basic validation of the model_url
  1589. if (!model_url || strlen(model_url) == 0) {
  1590. fprintf(stderr, "%s: invalid model_url\n", __func__);
  1591. return NULL;
  1592. }
  1593. // Initialize libcurl globally
  1594. auto curl = curl_easy_init();
  1595. if (!curl) {
  1596. fprintf(stderr, "%s: error initializing libcurl\n", __func__);
  1597. return NULL;
  1598. }
  1599. // Set the URL, allow to follow http redirection
  1600. curl_easy_setopt(curl, CURLOPT_URL, model_url);
  1601. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1602. #if defined(_WIN32)
  1603. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  1604. // operating system. Currently implemented under MS-Windows.
  1605. curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  1606. #endif
  1607. // Check if the file already exists locally
  1608. struct stat model_file_info;
  1609. auto file_exists = (stat(path_model, &model_file_info) == 0);
  1610. // If the file exists, check for ${path_model}.etag or ${path_model}.lastModified files
  1611. char etag[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1612. char etag_path[LLAMA_CURL_MAX_PATH_LENGTH] = {0};
  1613. snprintf(etag_path, sizeof(etag_path), "%s.etag", path_model);
  1614. char last_modified[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1615. char last_modified_path[LLAMA_CURL_MAX_PATH_LENGTH] = {0};
  1616. snprintf(last_modified_path, sizeof(last_modified_path), "%s.lastModified", path_model);
  1617. if (file_exists) {
  1618. auto * f_etag = fopen(etag_path, "r");
  1619. if (f_etag) {
  1620. if (!fgets(etag, sizeof(etag), f_etag)) {
  1621. fprintf(stderr, "%s: unable to read file %s\n", __func__, etag_path);
  1622. } else {
  1623. fprintf(stderr, "%s: previous model file found %s: %s\n", __func__, etag_path, etag);
  1624. }
  1625. fclose(f_etag);
  1626. }
  1627. auto * f_last_modified = fopen(last_modified_path, "r");
  1628. if (f_last_modified) {
  1629. if (!fgets(last_modified, sizeof(last_modified), f_last_modified)) {
  1630. fprintf(stderr, "%s: unable to read file %s\n", __func__, last_modified_path);
  1631. } else {
  1632. fprintf(stderr, "%s: previous model file found %s: %s\n", __func__, last_modified_path,
  1633. last_modified);
  1634. }
  1635. fclose(f_last_modified);
  1636. }
  1637. }
  1638. // Send a HEAD request to retrieve the etag and last-modified headers
  1639. struct llama_load_model_from_url_headers {
  1640. char etag[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1641. char last_modified[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1642. };
  1643. llama_load_model_from_url_headers headers;
  1644. {
  1645. typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
  1646. auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
  1647. llama_load_model_from_url_headers *headers = (llama_load_model_from_url_headers *) userdata;
  1648. const char * etag_prefix = "etag: ";
  1649. if (strncmp(buffer, etag_prefix, strlen(etag_prefix)) == 0) {
  1650. strncpy(headers->etag, buffer + strlen(etag_prefix), n_items - strlen(etag_prefix) - 2); // Remove CRLF
  1651. }
  1652. const char * last_modified_prefix = "last-modified: ";
  1653. if (strncmp(buffer, last_modified_prefix, strlen(last_modified_prefix)) == 0) {
  1654. strncpy(headers->last_modified, buffer + strlen(last_modified_prefix),
  1655. n_items - strlen(last_modified_prefix) - 2); // Remove CRLF
  1656. }
  1657. return n_items;
  1658. };
  1659. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  1660. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); // hide head request progress
  1661. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
  1662. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headers);
  1663. CURLcode res = curl_easy_perform(curl);
  1664. if (res != CURLE_OK) {
  1665. curl_easy_cleanup(curl);
  1666. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  1667. return NULL;
  1668. }
  1669. long http_code = 0;
  1670. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
  1671. if (http_code != 200) {
  1672. // HEAD not supported, we don't know if the file has changed
  1673. // force trigger downloading
  1674. file_exists = false;
  1675. fprintf(stderr, "%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  1676. }
  1677. }
  1678. // If the ETag or the Last-Modified headers are different: trigger a new download
  1679. if (!file_exists || strcmp(etag, headers.etag) != 0 || strcmp(last_modified, headers.last_modified) != 0) {
  1680. char path_model_temporary[LLAMA_CURL_MAX_PATH_LENGTH] = {0};
  1681. snprintf(path_model_temporary, sizeof(path_model_temporary), "%s.downloadInProgress", path_model);
  1682. if (file_exists) {
  1683. fprintf(stderr, "%s: deleting previous downloaded model file: %s\n", __func__, path_model);
  1684. if (remove(path_model) != 0) {
  1685. curl_easy_cleanup(curl);
  1686. fprintf(stderr, "%s: unable to delete file: %s\n", __func__, path_model);
  1687. return NULL;
  1688. }
  1689. }
  1690. // Set the output file
  1691. auto * outfile = fopen(path_model_temporary, "wb");
  1692. if (!outfile) {
  1693. curl_easy_cleanup(curl);
  1694. fprintf(stderr, "%s: error opening local file for writing: %s\n", __func__, path_model);
  1695. return NULL;
  1696. }
  1697. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
  1698. auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
  1699. return fwrite(data, size, nmemb, (FILE *)fd);
  1700. };
  1701. curl_easy_setopt(curl, CURLOPT_NOBODY, 0L);
  1702. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  1703. curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
  1704. // display download progress
  1705. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  1706. // start the download
  1707. fprintf(stderr, "%s: downloading model from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
  1708. model_url, path_model, headers.etag, headers.last_modified);
  1709. auto res = curl_easy_perform(curl);
  1710. if (res != CURLE_OK) {
  1711. fclose(outfile);
  1712. curl_easy_cleanup(curl);
  1713. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  1714. return NULL;
  1715. }
  1716. long http_code = 0;
  1717. curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code);
  1718. if (http_code < 200 || http_code >= 400) {
  1719. fclose(outfile);
  1720. curl_easy_cleanup(curl);
  1721. fprintf(stderr, "%s: invalid http status code received: %ld\n", __func__, http_code);
  1722. return NULL;
  1723. }
  1724. // Clean up
  1725. fclose(outfile);
  1726. // Write the new ETag to the .etag file
  1727. if (strlen(headers.etag) > 0) {
  1728. auto * etag_file = fopen(etag_path, "w");
  1729. if (etag_file) {
  1730. fputs(headers.etag, etag_file);
  1731. fclose(etag_file);
  1732. fprintf(stderr, "%s: model etag saved %s: %s\n", __func__, etag_path, headers.etag);
  1733. }
  1734. }
  1735. // Write the new lastModified to the .etag file
  1736. if (strlen(headers.last_modified) > 0) {
  1737. auto * last_modified_file = fopen(last_modified_path, "w");
  1738. if (last_modified_file) {
  1739. fputs(headers.last_modified, last_modified_file);
  1740. fclose(last_modified_file);
  1741. fprintf(stderr, "%s: model last modified saved %s: %s\n", __func__, last_modified_path,
  1742. headers.last_modified);
  1743. }
  1744. }
  1745. if (rename(path_model_temporary, path_model) != 0) {
  1746. curl_easy_cleanup(curl);
  1747. fprintf(stderr, "%s: unable to rename file: %s to %s\n", __func__, path_model_temporary, path_model);
  1748. return NULL;
  1749. }
  1750. }
  1751. curl_easy_cleanup(curl);
  1752. return llama_load_model_from_file(path_model, params);
  1753. }
  1754. #else
  1755. struct llama_model * llama_load_model_from_url(const char * /*model_url*/, const char * /*path_model*/,
  1756. struct llama_model_params /*params*/) {
  1757. fprintf(stderr, "%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  1758. return nullptr;
  1759. }
  1760. #endif // LLAMA_USE_CURL
  1761. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  1762. auto mparams = llama_model_params_from_gpt_params(params);
  1763. llama_model * model = nullptr;
  1764. if (!params.model_url.empty()) {
  1765. model = llama_load_model_from_url(params.model_url.c_str(), params.model.c_str(), mparams);
  1766. } else {
  1767. model = llama_load_model_from_file(params.model.c_str(), mparams);
  1768. }
  1769. if (model == NULL) {
  1770. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  1771. return std::make_tuple(nullptr, nullptr);
  1772. }
  1773. auto cparams = llama_context_params_from_gpt_params(params);
  1774. llama_context * lctx = llama_new_context_with_model(model, cparams);
  1775. if (lctx == NULL) {
  1776. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  1777. llama_free_model(model);
  1778. return std::make_tuple(nullptr, nullptr);
  1779. }
  1780. if (!params.control_vectors.empty()) {
  1781. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  1782. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_n_layer(model);
  1783. const auto cvec = llama_control_vector_load(params.control_vectors);
  1784. if (cvec.n_embd == -1) {
  1785. llama_free(lctx);
  1786. llama_free_model(model);
  1787. return std::make_tuple(nullptr, nullptr);
  1788. }
  1789. int err = llama_control_vector_apply(lctx,
  1790. cvec.data.data(),
  1791. cvec.data.size(),
  1792. cvec.n_embd,
  1793. params.control_vector_layer_start,
  1794. params.control_vector_layer_end);
  1795. if (err) {
  1796. llama_free(lctx);
  1797. llama_free_model(model);
  1798. return std::make_tuple(nullptr, nullptr);
  1799. }
  1800. }
  1801. for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
  1802. const std::string& lora_adapter = std::get<0>(params.lora_adapter[i]);
  1803. float lora_scale = std::get<1>(params.lora_adapter[i]);
  1804. int err = llama_model_apply_lora_from_file(model,
  1805. lora_adapter.c_str(),
  1806. lora_scale,
  1807. ((i > 0) || params.lora_base.empty())
  1808. ? NULL
  1809. : params.lora_base.c_str(),
  1810. params.n_threads);
  1811. if (err != 0) {
  1812. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  1813. llama_free(lctx);
  1814. llama_free_model(model);
  1815. return std::make_tuple(nullptr, nullptr);
  1816. }
  1817. }
  1818. if (params.ignore_eos) {
  1819. params.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  1820. }
  1821. {
  1822. LOG("warming up the model with an empty run\n");
  1823. std::vector<llama_token> tmp = { llama_token_bos(model), llama_token_eos(model), };
  1824. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
  1825. llama_kv_cache_clear(lctx);
  1826. llama_synchronize(lctx);
  1827. llama_reset_timings(lctx);
  1828. }
  1829. return std::make_tuple(model, lctx);
  1830. }
  1831. //
  1832. // Vocab utils
  1833. //
  1834. std::vector<llama_token> llama_tokenize(
  1835. const struct llama_context * ctx,
  1836. const std::string & text,
  1837. bool add_bos,
  1838. bool special) {
  1839. return llama_tokenize(llama_get_model(ctx), text, add_bos, special);
  1840. }
  1841. std::vector<llama_token> llama_tokenize(
  1842. const struct llama_model * model,
  1843. const std::string & text,
  1844. bool add_bos,
  1845. bool special) {
  1846. // upper limit for the number of tokens
  1847. int n_tokens = text.length() + add_bos;
  1848. std::vector<llama_token> result(n_tokens);
  1849. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  1850. if (n_tokens < 0) {
  1851. result.resize(-n_tokens);
  1852. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  1853. GGML_ASSERT(check == -n_tokens);
  1854. } else {
  1855. result.resize(n_tokens);
  1856. }
  1857. return result;
  1858. }
  1859. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1860. std::vector<char> result(8, 0);
  1861. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1862. if (n_tokens < 0) {
  1863. result.resize(-n_tokens);
  1864. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1865. GGML_ASSERT(check == -n_tokens);
  1866. } else {
  1867. result.resize(n_tokens);
  1868. }
  1869. return std::string(result.data(), result.size());
  1870. }
  1871. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  1872. const llama_token bos_id = llama_token_bos(llama_get_model(ctx));
  1873. std::string piece;
  1874. std::string result;
  1875. for (size_t i = 0; i < tokens.size(); ++i) {
  1876. piece = llama_token_to_piece(ctx, tokens[i]);
  1877. // remove the leading space of the first non-BOS token
  1878. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  1879. piece = piece.substr(1);
  1880. }
  1881. result += piece;
  1882. }
  1883. return result;
  1884. }
  1885. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  1886. std::string piece;
  1887. std::string result;
  1888. for (size_t i = 0; i < tokens.size(); ++i) {
  1889. piece = llama_token_to_piece(ctx, tokens[i]);
  1890. result += piece;
  1891. }
  1892. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1893. return result;
  1894. }
  1895. bool llama_should_add_bos_token(const llama_model * model) {
  1896. const int add_bos = llama_add_bos_token(model);
  1897. return add_bos != -1 ? bool(add_bos) : (llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM);
  1898. }
  1899. //
  1900. // YAML utils
  1901. //
  1902. // returns true if successful, false otherwise
  1903. bool create_directory_with_parents(const std::string & path) {
  1904. #ifdef _WIN32
  1905. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  1906. std::wstring wpath = converter.from_bytes(path);
  1907. // if the path already exists, check whether it's a directory
  1908. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  1909. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1910. return true;
  1911. }
  1912. size_t pos_slash = 0;
  1913. // process path from front to back, procedurally creating directories
  1914. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  1915. const std::wstring subpath = wpath.substr(0, pos_slash);
  1916. const wchar_t * test = subpath.c_str();
  1917. const bool success = CreateDirectoryW(test, NULL);
  1918. if (!success) {
  1919. const DWORD error = GetLastError();
  1920. // if the path already exists, ensure that it's a directory
  1921. if (error == ERROR_ALREADY_EXISTS) {
  1922. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  1923. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1924. return false;
  1925. }
  1926. } else {
  1927. return false;
  1928. }
  1929. }
  1930. pos_slash += 1;
  1931. }
  1932. return true;
  1933. #else
  1934. // if the path already exists, check whether it's a directory
  1935. struct stat info;
  1936. if (stat(path.c_str(), &info) == 0) {
  1937. return S_ISDIR(info.st_mode);
  1938. }
  1939. size_t pos_slash = 1; // skip leading slashes for directory creation
  1940. // process path from front to back, procedurally creating directories
  1941. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  1942. const std::string subpath = path.substr(0, pos_slash);
  1943. struct stat info;
  1944. // if the path already exists, ensure that it's a directory
  1945. if (stat(subpath.c_str(), &info) == 0) {
  1946. if (!S_ISDIR(info.st_mode)) {
  1947. return false;
  1948. }
  1949. } else {
  1950. // create parent directories
  1951. const int ret = mkdir(subpath.c_str(), 0755);
  1952. if (ret != 0) {
  1953. return false;
  1954. }
  1955. }
  1956. pos_slash += 1;
  1957. }
  1958. return true;
  1959. #endif // _WIN32
  1960. }
  1961. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  1962. if (data.empty()) {
  1963. fprintf(stream, "%s:\n", prop_name);
  1964. return;
  1965. }
  1966. fprintf(stream, "%s: [", prop_name);
  1967. for (size_t i = 0; i < data.size() - 1; ++i) {
  1968. fprintf(stream, "%e, ", data[i]);
  1969. }
  1970. fprintf(stream, "%e]\n", data.back());
  1971. }
  1972. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  1973. if (data.empty()) {
  1974. fprintf(stream, "%s:\n", prop_name);
  1975. return;
  1976. }
  1977. fprintf(stream, "%s: [", prop_name);
  1978. for (size_t i = 0; i < data.size() - 1; ++i) {
  1979. fprintf(stream, "%d, ", data[i]);
  1980. }
  1981. fprintf(stream, "%d]\n", data.back());
  1982. }
  1983. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data) {
  1984. std::string data_str(data == NULL ? "" : data);
  1985. if (data_str.empty()) {
  1986. fprintf(stream, "%s:\n", prop_name);
  1987. return;
  1988. }
  1989. size_t pos_start = 0;
  1990. size_t pos_found = 0;
  1991. if (!data_str.empty() && (std::isspace(data_str[0]) || std::isspace(data_str.back()))) {
  1992. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  1993. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  1994. data_str = std::regex_replace(data_str, std::regex(R"(\\[^n"])"), R"(\$&)");
  1995. data_str = "\"" + data_str + "\"";
  1996. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1997. return;
  1998. }
  1999. if (data_str.find('\n') == std::string::npos) {
  2000. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  2001. return;
  2002. }
  2003. fprintf(stream, "%s: |\n", prop_name);
  2004. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  2005. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  2006. pos_start = pos_found + 1;
  2007. }
  2008. }
  2009. std::string get_sortable_timestamp() {
  2010. using clock = std::chrono::system_clock;
  2011. const clock::time_point current_time = clock::now();
  2012. const time_t as_time_t = clock::to_time_t(current_time);
  2013. char timestamp_no_ns[100];
  2014. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  2015. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  2016. current_time.time_since_epoch() % 1000000000).count();
  2017. char timestamp_ns[11];
  2018. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  2019. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  2020. }
  2021. void dump_non_result_info_yaml(FILE * stream, const gpt_params & params, const llama_context * lctx,
  2022. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  2023. const llama_sampling_params & sparams = params.sparams;
  2024. fprintf(stream, "build_commit: %s\n", LLAMA_COMMIT);
  2025. fprintf(stream, "build_number: %d\n", LLAMA_BUILD_NUMBER);
  2026. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  2027. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  2028. fprintf(stream, "cpu_has_avx_vnni: %s\n", ggml_cpu_has_avx_vnni() ? "true" : "false");
  2029. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  2030. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  2031. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  2032. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  2033. fprintf(stream, "cpu_has_cublas: %s\n", ggml_cpu_has_cublas() ? "true" : "false");
  2034. fprintf(stream, "cpu_has_vulkan: %s\n", ggml_cpu_has_vulkan() ? "true" : "false");
  2035. fprintf(stream, "cpu_has_clblast: %s\n", ggml_cpu_has_clblast() ? "true" : "false");
  2036. fprintf(stream, "cpu_has_kompute: %s\n", ggml_cpu_has_kompute() ? "true" : "false");
  2037. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  2038. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  2039. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  2040. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  2041. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  2042. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  2043. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  2044. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  2045. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  2046. fprintf(stream, "cpu_has_matmul_int8: %s\n", ggml_cpu_has_matmul_int8() ? "true" : "false");
  2047. #ifdef NDEBUG
  2048. fprintf(stream, "debug: false\n");
  2049. #else
  2050. fprintf(stream, "debug: true\n");
  2051. #endif // NDEBUG
  2052. fprintf(stream, "model_desc: %s\n", model_desc);
  2053. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(llama_get_model(lctx)));
  2054. #ifdef __OPTIMIZE__
  2055. fprintf(stream, "optimize: true\n");
  2056. #else
  2057. fprintf(stream, "optimize: false\n");
  2058. #endif // __OPTIMIZE__
  2059. fprintf(stream, "time: %s\n", timestamp.c_str());
  2060. fprintf(stream, "\n");
  2061. fprintf(stream, "###############\n");
  2062. fprintf(stream, "# User Inputs #\n");
  2063. fprintf(stream, "###############\n");
  2064. fprintf(stream, "\n");
  2065. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  2066. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  2067. dump_string_yaml_multiline(stream, "cfg_negative_prompt", sparams.cfg_negative_prompt.c_str());
  2068. fprintf(stream, "cfg_scale: %f # default: 1.0\n", sparams.cfg_scale);
  2069. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  2070. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  2071. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  2072. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  2073. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  2074. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", sparams.penalty_freq);
  2075. dump_string_yaml_multiline(stream, "grammar", sparams.grammar.c_str());
  2076. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  2077. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  2078. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  2079. const auto logit_bias_eos = sparams.logit_bias.find(llama_token_eos(llama_get_model(lctx)));
  2080. const bool ignore_eos = logit_bias_eos != sparams.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  2081. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  2082. dump_string_yaml_multiline(stream, "in_prefix", params.input_prefix.c_str());
  2083. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  2084. dump_string_yaml_multiline(stream, "in_suffix", params.input_prefix.c_str());
  2085. fprintf(stream, "instruct: %s # default: false\n", params.instruct ? "true" : "false");
  2086. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  2087. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  2088. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  2089. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  2090. fprintf(stream, "logit_bias:\n");
  2091. for (std::pair<llama_token, float> lb : sparams.logit_bias) {
  2092. if (ignore_eos && lb.first == logit_bias_eos->first) {
  2093. continue;
  2094. }
  2095. fprintf(stream, " %d: %f", lb.first, lb.second);
  2096. }
  2097. fprintf(stream, "lora:\n");
  2098. for (std::tuple<std::string, float> la : params.lora_adapter) {
  2099. if (std::get<1>(la) != 1.0f) {
  2100. continue;
  2101. }
  2102. fprintf(stream, " - %s\n", std::get<0>(la).c_str());
  2103. }
  2104. fprintf(stream, "lora_scaled:\n");
  2105. for (std::tuple<std::string, float> la : params.lora_adapter) {
  2106. if (std::get<1>(la) == 1.0f) {
  2107. continue;
  2108. }
  2109. fprintf(stream, " - %s: %f\n", std::get<0>(la).c_str(), std::get<1>(la));
  2110. }
  2111. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  2112. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  2113. fprintf(stream, "min_keep: %d # default: 0 (disabled)\n", sparams.min_keep);
  2114. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", sparams.mirostat);
  2115. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", sparams.mirostat_tau);
  2116. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", sparams.mirostat_eta);
  2117. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  2118. fprintf(stream, "model: %s # default: models/7B/ggml-model.bin\n", params.model.c_str());
  2119. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  2120. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  2121. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  2122. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  2123. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", sparams.n_probs);
  2124. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  2125. fprintf(stream, "no_penalize_nl: %s # default: false\n", !sparams.penalize_nl ? "true" : "false");
  2126. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  2127. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  2128. fprintf(stream, "presence_penalty: %f # default: 0.0\n", sparams.penalty_present);
  2129. dump_string_yaml_multiline(stream, "prompt", params.prompt.c_str());
  2130. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  2131. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  2132. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  2133. dump_vector_int_yaml(stream, "prompt_tokens", prompt_tokens);
  2134. fprintf(stream, "random_prompt: %s # default: false\n", params.random_prompt ? "true" : "false");
  2135. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", sparams.penalty_repeat);
  2136. fprintf(stream, "reverse_prompt:\n");
  2137. for (std::string ap : params.antiprompt) {
  2138. size_t pos = 0;
  2139. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  2140. ap.replace(pos, 1, "\\n");
  2141. pos += 1;
  2142. }
  2143. fprintf(stream, " - %s\n", ap.c_str());
  2144. }
  2145. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  2146. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  2147. fprintf(stream, "seed: %u # default: -1 (random seed)\n", params.seed);
  2148. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  2149. fprintf(stream, "cont_batching: %s # default: false\n", params.cont_batching ? "true" : "false");
  2150. fprintf(stream, "temp: %f # default: 0.8\n", sparams.temp);
  2151. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + llama_max_devices());
  2152. dump_vector_float_yaml(stream, "tensor_split", tensor_split_vector);
  2153. fprintf(stream, "tfs: %f # default: 1.0\n", sparams.tfs_z);
  2154. fprintf(stream, "threads: %d # default: %u\n", params.n_threads, std::thread::hardware_concurrency());
  2155. fprintf(stream, "top_k: %d # default: 40\n", sparams.top_k);
  2156. fprintf(stream, "top_p: %f # default: 0.95\n", sparams.top_p);
  2157. fprintf(stream, "min_p: %f # default: 0.0\n", sparams.min_p);
  2158. fprintf(stream, "typical_p: %f # default: 1.0\n", sparams.typical_p);
  2159. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  2160. fprintf(stream, "display_prompt: %s # default: true\n", params.display_prompt ? "true" : "false");
  2161. }
  2162. //
  2163. // KV cache utils
  2164. //
  2165. void dump_kv_cache_view(const llama_kv_cache_view & view, int row_size) {
  2166. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  2167. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d",
  2168. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2169. llama_kv_cache_view_cell * c_curr = view.cells;
  2170. llama_seq_id * cs_curr = view.cells_sequences;
  2171. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2172. if (i % row_size == 0) {
  2173. printf("\n%5d: ", i);
  2174. }
  2175. int seq_count = 0;
  2176. for (int j = 0; j < view.n_seq_max; j++) {
  2177. if (cs_curr[j] >= 0) { seq_count++; }
  2178. }
  2179. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  2180. }
  2181. printf("\n=== Done dumping\n");
  2182. }
  2183. void dump_kv_cache_view_seqs(const llama_kv_cache_view & view, int row_size) {
  2184. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2185. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d\n",
  2186. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2187. std::unordered_map<llama_seq_id, size_t> seqs;
  2188. llama_kv_cache_view_cell * c_curr = view.cells;
  2189. llama_seq_id * cs_curr = view.cells_sequences;
  2190. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2191. for (int j = 0; j < view.n_seq_max; j++) {
  2192. if (cs_curr[j] < 0) { continue; }
  2193. if (seqs.find(cs_curr[j]) == seqs.end()) {
  2194. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2195. const size_t sz = seqs.size();
  2196. seqs[cs_curr[j]] = sz;
  2197. }
  2198. }
  2199. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2200. }
  2201. printf("=== Sequence legend: ");
  2202. for (const auto & it : seqs) {
  2203. printf("%zu=%d, ", it.second, it.first);
  2204. }
  2205. printf("'+'=other sequence ids");
  2206. c_curr = view.cells;
  2207. cs_curr = view.cells_sequences;
  2208. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2209. if (i % row_size == 0) {
  2210. printf("\n%5d: ", i);
  2211. }
  2212. for (int j = 0; j < view.n_seq_max; j++) {
  2213. if (cs_curr[j] >= 0) {
  2214. const auto & it = seqs.find(cs_curr[j]);
  2215. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  2216. } else {
  2217. putchar('.');
  2218. }
  2219. }
  2220. putchar(' ');
  2221. }
  2222. printf("\n=== Done dumping\n");
  2223. }
  2224. void llama_embd_normalize(const float * inp, float * out, int n) {
  2225. double sum = 0.0;
  2226. for (int i = 0; i < n; i++) {
  2227. sum += inp[i] * inp[i];
  2228. }
  2229. sum = sqrt(sum);
  2230. const float norm = sum > 0.0 ? 1.0f / sum : 0.0f;
  2231. for (int i = 0; i < n; i++) {
  2232. out[i] = inp[i] * norm;
  2233. }
  2234. }
  2235. float llama_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  2236. double sum = 0.0;
  2237. double sum1 = 0.0;
  2238. double sum2 = 0.0;
  2239. for (int i = 0; i < n; i++) {
  2240. sum += embd1[i] * embd2[i];
  2241. sum1 += embd1[i] * embd1[i];
  2242. sum2 += embd2[i] * embd2[i];
  2243. }
  2244. return sum / (sqrt(sum1) * sqrt(sum2));
  2245. }
  2246. //
  2247. // Control vector utils
  2248. //
  2249. static llama_control_vector_data llama_control_vector_load_one(const llama_control_vector_load_info & load_info) {
  2250. int32_t n_tensors;
  2251. size_t n_bytes = 0;
  2252. uint32_t max_direction_layer = 0;
  2253. llama_control_vector_data result = { -1, {} };
  2254. // calculate size of ctx needed for tensors, ensure tensors are f32, and find max layer
  2255. {
  2256. struct ggml_init_params meta_params = {
  2257. /* .mem_size = */ ggml_tensor_overhead() * 128 + ggml_graph_overhead(),
  2258. /* .mem_buffer = */ nullptr,
  2259. /* .no_alloc = */ true,
  2260. };
  2261. ggml_context * meta_ctx = ggml_init(meta_params);
  2262. struct gguf_init_params meta_gguf_params = {
  2263. /* .no_alloc = */ true,
  2264. /* .ctx = */ &meta_ctx,
  2265. };
  2266. struct gguf_context * meta_ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  2267. if (!meta_ctx_gguf) {
  2268. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2269. ggml_free(meta_ctx);
  2270. return result;
  2271. }
  2272. n_tensors = gguf_get_n_tensors(meta_ctx_gguf);
  2273. for (int i = 0; i < n_tensors; i++) {
  2274. std::string name = gguf_get_tensor_name(meta_ctx_gguf, i);
  2275. // split on '.'
  2276. size_t dotpos = name.find('.');
  2277. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  2278. try {
  2279. uint32_t layer = std::stoi(name.substr(dotpos + 1));
  2280. if (layer == 0) {
  2281. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2282. ggml_free(meta_ctx);
  2283. gguf_free(meta_ctx_gguf);
  2284. return result;
  2285. }
  2286. if (layer > max_direction_layer) {
  2287. max_direction_layer = layer;
  2288. }
  2289. } catch (...) {
  2290. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2291. ggml_free(meta_ctx);
  2292. gguf_free(meta_ctx_gguf);
  2293. return result;
  2294. }
  2295. }
  2296. struct ggml_tensor * tensor_meta = ggml_get_tensor(meta_ctx, name.c_str());
  2297. if (tensor_meta->type != GGML_TYPE_F32 || ggml_n_dims(tensor_meta) != 1) {
  2298. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2299. ggml_free(meta_ctx);
  2300. gguf_free(meta_ctx_gguf);
  2301. return result;
  2302. }
  2303. if (result.n_embd == -1) {
  2304. result.n_embd = ggml_nelements(tensor_meta);
  2305. } else if (ggml_nelements(tensor_meta) != result.n_embd) {
  2306. fprintf(stderr, "%s: direction tensor sizes mismatched in %s\n", __func__, load_info.fname.c_str());
  2307. ggml_free(meta_ctx);
  2308. gguf_free(meta_ctx_gguf);
  2309. return result;
  2310. }
  2311. n_bytes += ggml_nbytes(tensor_meta);
  2312. }
  2313. ggml_free(meta_ctx);
  2314. gguf_free(meta_ctx_gguf);
  2315. }
  2316. if (n_tensors == 0) {
  2317. fprintf(stderr, "%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  2318. return result;
  2319. }
  2320. // load and scale tensors into final control vector context
  2321. struct ggml_init_params ggml_params = {
  2322. /* .mem_size = */ ggml_tensor_overhead() * n_tensors + n_bytes,
  2323. /* .mem_buffer = */ nullptr,
  2324. /* .no_alloc = */ false,
  2325. };
  2326. struct ggml_context * ctx = ggml_init(ggml_params);
  2327. struct gguf_init_params params = {
  2328. /*.no_alloc = */ false,
  2329. /*.ctx = */ &ctx,
  2330. };
  2331. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), params);
  2332. if (!ctx_gguf) {
  2333. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2334. ggml_free(ctx);
  2335. return result;
  2336. }
  2337. // do not store data for layer 0 (it's not used)
  2338. result.data.resize(result.n_embd * max_direction_layer);
  2339. for (uint32_t il = 1; il <= max_direction_layer; il++) {
  2340. const std::string name = "direction." + std::to_string(il);
  2341. const ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  2342. float * dst = result.data.data() + result.n_embd * (il - 1);
  2343. if (tensor) {
  2344. const float * src = (const float *) tensor->data;
  2345. for (int j = 0; j < result.n_embd; j++) {
  2346. dst[j] = src[j] * load_info.strength;
  2347. }
  2348. } else {
  2349. for (int j = 0; j < result.n_embd; j++) {
  2350. dst[j] = 0.0f;
  2351. }
  2352. }
  2353. }
  2354. return result;
  2355. }
  2356. llama_control_vector_data llama_control_vector_load(const std::vector<llama_control_vector_load_info> & load_infos) {
  2357. llama_control_vector_data result = { -1, {} };
  2358. for (const auto & info : load_infos) {
  2359. auto cur = llama_control_vector_load_one(info);
  2360. if (cur.n_embd == -1) {
  2361. return result;
  2362. }
  2363. if (result.n_embd != -1 && (result.n_embd != cur.n_embd || result.data.size() != cur.data.size())) {
  2364. fprintf(stderr, "%s: control vector in %s does not match previous vector dimensions\n", __func__, info.fname.c_str());
  2365. return result;
  2366. }
  2367. if (result.n_embd == -1) {
  2368. result = std::move(cur);
  2369. } else {
  2370. for (size_t i = 0; i < cur.data.size(); i++) {
  2371. result.data[i] += cur.data[i];
  2372. }
  2373. }
  2374. }
  2375. if (result.n_embd == -1) {
  2376. fprintf(stderr, "%s: no vectors passed\n", __func__);
  2377. }
  2378. return result;
  2379. }