common.cpp 98 KB

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