common.cpp 107 KB

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