common.cpp 114 KB

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