common.cpp 108 KB

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