llama.cpp 275 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "ggml.h"
  4. #include "ggml-alloc.h"
  5. #ifdef GGML_USE_CUBLAS
  6. # include "ggml-cuda.h"
  7. #elif defined(GGML_USE_CLBLAST)
  8. # include "ggml-opencl.h"
  9. #endif
  10. #ifdef GGML_USE_METAL
  11. # include "ggml-metal.h"
  12. #endif
  13. #ifdef GGML_USE_MPI
  14. # include "ggml-mpi.h"
  15. #endif
  16. #ifdef GGML_USE_K_QUANTS
  17. # ifndef QK_K
  18. # ifdef GGML_QKK_64
  19. # define QK_K 64
  20. # else
  21. # define QK_K 256
  22. # endif
  23. # endif
  24. #endif
  25. #ifdef __has_include
  26. #if __has_include(<unistd.h>)
  27. #include <unistd.h>
  28. #if defined(_POSIX_MAPPED_FILES)
  29. #include <sys/mman.h>
  30. #endif
  31. #if defined(_POSIX_MEMLOCK_RANGE)
  32. #include <sys/resource.h>
  33. #endif
  34. #endif
  35. #endif
  36. #if defined(_WIN32)
  37. #define WIN32_LEAN_AND_MEAN
  38. #ifndef NOMINMAX
  39. #define NOMINMAX
  40. #endif
  41. #include <windows.h>
  42. #include <io.h>
  43. #include <stdio.h> // for _fseeki64
  44. #endif
  45. #include <algorithm>
  46. #include <array>
  47. #include <cassert>
  48. #include <cinttypes>
  49. #include <climits>
  50. #include <cstdarg>
  51. #include <cstddef>
  52. #include <cstdint>
  53. #include <cstdio>
  54. #include <cstring>
  55. #include <ctime>
  56. #include <fstream>
  57. #include <initializer_list>
  58. #include <map>
  59. #include <memory>
  60. #include <mutex>
  61. #include <numeric>
  62. #include <queue>
  63. #include <random>
  64. #include <regex>
  65. #include <sstream>
  66. #include <thread>
  67. #include <unordered_map>
  68. #include <set>
  69. #if defined(_MSC_VER)
  70. #pragma warning(disable: 4244 4267) // possible loss of data
  71. #endif
  72. #ifdef __GNUC__
  73. #ifdef __MINGW32__
  74. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  75. #else
  76. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  77. #endif
  78. #else
  79. #define LLAMA_ATTRIBUTE_FORMAT(...)
  80. #endif
  81. //
  82. // logging
  83. //
  84. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  85. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  86. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  87. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  88. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  89. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  90. //
  91. // helpers
  92. //
  93. static size_t utf8_len(char src) {
  94. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  95. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  96. return lookup[highbits];
  97. }
  98. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  99. std::string result;
  100. for (size_t pos = 0; ; pos += search.length()) {
  101. auto new_pos = s.find(search, pos);
  102. if (new_pos == std::string::npos) {
  103. result += s.substr(pos, s.size() - pos);
  104. break;
  105. }
  106. result += s.substr(pos, new_pos - pos) + replace;
  107. pos = new_pos;
  108. }
  109. s = std::move(result);
  110. }
  111. #ifdef GGML_USE_CPU_HBM
  112. #include <hbwmalloc.h>
  113. #endif
  114. static void zeros(std::ofstream & file, size_t n) {
  115. char zero = 0;
  116. for (size_t i = 0; i < n; ++i) {
  117. file.write(&zero, 1);
  118. }
  119. }
  120. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  121. static std::string format(const char * fmt, ...) {
  122. va_list ap;
  123. va_list ap2;
  124. va_start(ap, fmt);
  125. va_copy(ap2, ap);
  126. int size = vsnprintf(NULL, 0, fmt, ap);
  127. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  128. std::vector<char> buf(size + 1);
  129. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  130. GGML_ASSERT(size2 == size);
  131. va_end(ap2);
  132. va_end(ap);
  133. return std::string(buf.data(), size);
  134. }
  135. //
  136. // gguf constants (sync with gguf.py)
  137. //
  138. enum llm_arch {
  139. LLM_ARCH_LLAMA,
  140. LLM_ARCH_FALCON,
  141. LLM_ARCH_BAICHUAN,
  142. LLM_ARCH_GPT2,
  143. LLM_ARCH_GPTJ,
  144. LLM_ARCH_GPTNEOX,
  145. LLM_ARCH_MPT,
  146. LLM_ARCH_STARCODER,
  147. LLM_ARCH_UNKNOWN,
  148. };
  149. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  150. { LLM_ARCH_LLAMA, "llama" },
  151. { LLM_ARCH_FALCON, "falcon" },
  152. { LLM_ARCH_GPT2, "gpt2" },
  153. { LLM_ARCH_GPTJ, "gptj" },
  154. { LLM_ARCH_GPTNEOX, "gptneox" },
  155. { LLM_ARCH_MPT, "mpt" },
  156. { LLM_ARCH_BAICHUAN, "baichuan" },
  157. { LLM_ARCH_STARCODER, "starcoder" },
  158. };
  159. enum llm_kv {
  160. LLM_KV_GENERAL_ARCHITECTURE,
  161. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  162. LLM_KV_GENERAL_ALIGNMENT,
  163. LLM_KV_GENERAL_NAME,
  164. LLM_KV_GENERAL_AUTHOR,
  165. LLM_KV_GENERAL_URL,
  166. LLM_KV_GENERAL_DESCRIPTION,
  167. LLM_KV_GENERAL_LICENSE,
  168. LLM_KV_GENERAL_SOURCE_URL,
  169. LLM_KV_GENERAL_SOURCE_HF_REPO,
  170. LLM_KV_CONTEXT_LENGTH,
  171. LLM_KV_EMBEDDING_LENGTH,
  172. LLM_KV_BLOCK_COUNT,
  173. LLM_KV_FEED_FORWARD_LENGTH,
  174. LLM_KV_USE_PARALLEL_RESIDUAL,
  175. LLM_KV_TENSOR_DATA_LAYOUT,
  176. LLM_KV_ATTENTION_HEAD_COUNT,
  177. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  178. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  179. LLM_KV_ATTENTION_CLAMP_KQV,
  180. LLM_KV_ATTENTION_LAYERNORM_EPS,
  181. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  182. LLM_KV_ROPE_DIMENSION_COUNT,
  183. LLM_KV_ROPE_FREQ_BASE,
  184. LLM_KV_ROPE_SCALE_LINEAR,
  185. LLM_KV_TOKENIZER_MODEL,
  186. LLM_KV_TOKENIZER_LIST,
  187. LLM_KV_TOKENIZER_TOKEN_TYPE,
  188. LLM_KV_TOKENIZER_SCORES,
  189. LLM_KV_TOKENIZER_MERGES,
  190. LLM_KV_TOKENIZER_BOS_ID,
  191. LLM_KV_TOKENIZER_EOS_ID,
  192. LLM_KV_TOKENIZER_UNK_ID,
  193. LLM_KV_TOKENIZER_SEP_ID,
  194. LLM_KV_TOKENIZER_PAD_ID,
  195. LLM_KV_TOKENIZER_HF_JSON,
  196. LLM_KV_TOKENIZER_RWKV,
  197. };
  198. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  199. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  200. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  201. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  202. { LLM_KV_GENERAL_NAME, "general.name" },
  203. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  204. { LLM_KV_GENERAL_URL, "general.url" },
  205. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  206. { LLM_KV_GENERAL_LICENSE, "general.license" },
  207. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  208. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  209. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  210. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  211. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  212. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  213. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  214. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  215. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  216. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  217. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  218. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  219. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  220. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  221. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  222. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  223. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  224. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  225. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  226. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  227. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  228. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  229. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  230. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  231. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  232. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  233. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  234. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  235. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  236. };
  237. struct LLM_KV {
  238. LLM_KV(llm_arch arch) : arch(arch) {}
  239. llm_arch arch;
  240. std::string operator()(llm_kv kv) const {
  241. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  242. }
  243. };
  244. enum llm_tensor {
  245. LLM_TENSOR_TOKEN_EMBD,
  246. LLM_TENSOR_POS_EMBD,
  247. LLM_TENSOR_OUTPUT,
  248. LLM_TENSOR_OUTPUT_NORM,
  249. LLM_TENSOR_ROPE_FREQS,
  250. LLM_TENSOR_ATTN_Q,
  251. LLM_TENSOR_ATTN_K,
  252. LLM_TENSOR_ATTN_V,
  253. LLM_TENSOR_ATTN_QKV,
  254. LLM_TENSOR_ATTN_OUT,
  255. LLM_TENSOR_ATTN_NORM,
  256. LLM_TENSOR_ATTN_NORM_2,
  257. LLM_TENSOR_ATTN_ROT_EMBD,
  258. LLM_TENSOR_FFN_GATE,
  259. LLM_TENSOR_FFN_DOWN,
  260. LLM_TENSOR_FFN_UP,
  261. LLM_TENSOR_FFN_NORM,
  262. };
  263. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  264. {
  265. LLM_ARCH_LLAMA,
  266. {
  267. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  268. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  269. { LLM_TENSOR_OUTPUT, "output" },
  270. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  271. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  272. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  273. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  274. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  275. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  276. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  277. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  278. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  279. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  280. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  281. },
  282. },
  283. {
  284. LLM_ARCH_BAICHUAN,
  285. {
  286. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  287. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  288. { LLM_TENSOR_OUTPUT, "output" },
  289. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  290. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  291. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  292. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  293. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  294. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  295. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  296. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  297. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  298. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  299. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  300. },
  301. },
  302. {
  303. LLM_ARCH_FALCON,
  304. {
  305. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  306. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  307. { LLM_TENSOR_OUTPUT, "output" },
  308. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  309. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  310. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  311. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  312. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  313. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  314. },
  315. },
  316. {
  317. LLM_ARCH_GPT2,
  318. {
  319. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  320. },
  321. },
  322. {
  323. LLM_ARCH_GPTJ,
  324. {
  325. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  326. },
  327. },
  328. {
  329. LLM_ARCH_GPTNEOX,
  330. {
  331. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  332. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  333. { LLM_TENSOR_OUTPUT, "output" },
  334. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  335. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  336. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  337. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  338. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  339. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  340. },
  341. },
  342. {
  343. LLM_ARCH_MPT,
  344. {
  345. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  346. },
  347. },
  348. {
  349. LLM_ARCH_STARCODER,
  350. {
  351. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  352. { LLM_TENSOR_POS_EMBD, "position_embd" },
  353. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  354. { LLM_TENSOR_OUTPUT, "output" },
  355. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  356. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  357. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  358. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  359. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  360. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  361. },
  362. },
  363. {
  364. LLM_ARCH_UNKNOWN,
  365. {
  366. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  367. },
  368. },
  369. };
  370. static llm_arch llm_arch_from_string(const std::string & name) {
  371. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  372. if (kv.second == name) {
  373. return kv.first;
  374. }
  375. }
  376. return LLM_ARCH_UNKNOWN;
  377. }
  378. // helper to handle gguf constants
  379. // usage:
  380. //
  381. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  382. //
  383. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  384. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  385. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  386. //
  387. struct LLM_TN {
  388. LLM_TN(llm_arch arch) : arch(arch) {}
  389. llm_arch arch;
  390. std::string operator()(llm_tensor tensor) const {
  391. return LLM_TENSOR_NAMES[arch].at(tensor);
  392. }
  393. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  394. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  395. }
  396. std::string operator()(llm_tensor tensor, int bid) const {
  397. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  398. }
  399. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  400. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  401. }
  402. };
  403. //
  404. // gguf helpers
  405. //
  406. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  407. do { \
  408. const std::string skey(key); \
  409. const int kid = gguf_find_key(ctx, skey.c_str()); \
  410. if (kid >= 0) { \
  411. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  412. if (ktype != (type)) { \
  413. throw std::runtime_error(format("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype))); \
  414. } \
  415. (dst) = func(ctx, kid); \
  416. } else if (req) { \
  417. throw std::runtime_error(format("key not found in model: %s", skey.c_str())); \
  418. } \
  419. } while (0)
  420. //
  421. // ggml helpers
  422. //
  423. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  424. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  425. if (plan.work_size > 0) {
  426. buf.resize(plan.work_size);
  427. plan.work_data = buf.data();
  428. }
  429. ggml_graph_compute(graph, &plan);
  430. }
  431. //
  432. // llama helpers
  433. //
  434. #ifdef GGML_USE_CUBLAS
  435. # define llama_host_malloc(n) ggml_cuda_host_malloc(n)
  436. # define llama_host_free(data) ggml_cuda_host_free(data)
  437. #elif GGML_USE_METAL
  438. # define llama_host_malloc(n) ggml_metal_host_malloc(n)
  439. # define llama_host_free(data) ggml_metal_host_free(data)
  440. #elif GGML_USE_CPU_HBM
  441. # define llama_host_malloc(n) hbw_malloc(n)
  442. # define llama_host_free(data) if (data != NULL) hbw_free(data)
  443. #else
  444. # define llama_host_malloc(n) malloc(n)
  445. # define llama_host_free(data) free(data)
  446. #endif
  447. #if defined(_WIN32)
  448. static std::string llama_format_win_err(DWORD err) {
  449. LPSTR buf;
  450. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  451. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  452. if (!size) {
  453. return "FormatMessageA failed";
  454. }
  455. std::string ret(buf, size);
  456. LocalFree(buf);
  457. return ret;
  458. }
  459. #endif
  460. struct llama_buffer {
  461. void * data = NULL;
  462. size_t size = 0;
  463. // fallback to malloc / free
  464. // useful in cases where CUDA can try to allocate PINNED memory
  465. bool fallback = false;
  466. void resize(size_t n) {
  467. llama_host_free(data);
  468. data = llama_host_malloc(n);
  469. if (!data) {
  470. fallback = true;
  471. data = malloc(n);
  472. } else {
  473. fallback = false;
  474. }
  475. GGML_ASSERT(data);
  476. size = n;
  477. }
  478. ~llama_buffer() {
  479. if (data) {
  480. if (fallback) { // NOLINT
  481. free(data);
  482. } else {
  483. llama_host_free(data);
  484. }
  485. }
  486. data = NULL;
  487. }
  488. };
  489. struct llama_file {
  490. // use FILE * so we don't have to re-open the file to mmap
  491. FILE * fp;
  492. size_t size;
  493. llama_file(const char * fname, const char * mode) {
  494. fp = std::fopen(fname, mode);
  495. if (fp == NULL) {
  496. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  497. }
  498. seek(0, SEEK_END);
  499. size = tell();
  500. seek(0, SEEK_SET);
  501. }
  502. size_t tell() const {
  503. #ifdef _WIN32
  504. __int64 ret = _ftelli64(fp);
  505. #else
  506. long ret = std::ftell(fp);
  507. #endif
  508. GGML_ASSERT(ret != -1); // this really shouldn't fail
  509. return (size_t) ret;
  510. }
  511. void seek(size_t offset, int whence) const {
  512. #ifdef _WIN32
  513. int ret = _fseeki64(fp, (__int64) offset, whence);
  514. #else
  515. int ret = std::fseek(fp, (long) offset, whence);
  516. #endif
  517. GGML_ASSERT(ret == 0); // same
  518. }
  519. void read_raw(void * ptr, size_t len) const {
  520. if (len == 0) {
  521. return;
  522. }
  523. errno = 0;
  524. std::size_t ret = std::fread(ptr, len, 1, fp);
  525. if (ferror(fp)) {
  526. throw std::runtime_error(format("read error: %s", strerror(errno)));
  527. }
  528. if (ret != 1) {
  529. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  530. }
  531. }
  532. uint32_t read_u32() const {
  533. uint32_t ret;
  534. read_raw(&ret, sizeof(ret));
  535. return ret;
  536. }
  537. void write_raw(const void * ptr, size_t len) const {
  538. if (len == 0) {
  539. return;
  540. }
  541. errno = 0;
  542. size_t ret = std::fwrite(ptr, len, 1, fp);
  543. if (ret != 1) {
  544. throw std::runtime_error(format("write error: %s", strerror(errno)));
  545. }
  546. }
  547. void write_u32(std::uint32_t val) const {
  548. write_raw(&val, sizeof(val));
  549. }
  550. ~llama_file() {
  551. if (fp) {
  552. std::fclose(fp);
  553. }
  554. }
  555. };
  556. struct llama_mmap {
  557. void * addr;
  558. size_t size;
  559. llama_mmap(const llama_mmap &) = delete;
  560. #ifdef _POSIX_MAPPED_FILES
  561. static constexpr bool SUPPORTED = true;
  562. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  563. size = file->size;
  564. int fd = fileno(file->fp);
  565. int flags = MAP_SHARED;
  566. // prefetch/readahead impairs performance on NUMA systems
  567. if (numa) { prefetch = 0; }
  568. #ifdef __linux__
  569. if (prefetch) { flags |= MAP_POPULATE; }
  570. #endif
  571. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  572. if (addr == MAP_FAILED) {
  573. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  574. }
  575. if (prefetch > 0) {
  576. // Advise the kernel to preload the mapped memory
  577. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  578. fprintf(stderr, "warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  579. strerror(errno));
  580. }
  581. }
  582. if (numa) {
  583. // advise the kernel not to use readahead
  584. // (because the next page might not belong on the same node)
  585. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  586. fprintf(stderr, "warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  587. strerror(errno));
  588. }
  589. }
  590. }
  591. ~llama_mmap() {
  592. munmap(addr, size);
  593. }
  594. #elif defined(_WIN32)
  595. static constexpr bool SUPPORTED = true;
  596. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  597. (void) numa;
  598. size = file->size;
  599. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  600. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  601. DWORD error = GetLastError();
  602. if (hMapping == NULL) {
  603. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  604. }
  605. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  606. error = GetLastError();
  607. CloseHandle(hMapping);
  608. if (addr == NULL) {
  609. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  610. }
  611. if (prefetch) {
  612. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  613. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  614. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  615. // may fail on pre-Windows 8 systems
  616. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  617. if (pPrefetchVirtualMemory) {
  618. // advise the kernel to preload the mapped memory
  619. WIN32_MEMORY_RANGE_ENTRY range;
  620. range.VirtualAddress = addr;
  621. range.NumberOfBytes = (SIZE_T)size;
  622. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  623. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  624. llama_format_win_err(GetLastError()).c_str());
  625. }
  626. }
  627. }
  628. }
  629. ~llama_mmap() {
  630. if (!UnmapViewOfFile(addr)) {
  631. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  632. llama_format_win_err(GetLastError()).c_str());
  633. }
  634. }
  635. #else
  636. static constexpr bool SUPPORTED = false;
  637. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  638. (void) file;
  639. (void) prefetch;
  640. (void) numa;
  641. throw std::runtime_error(std::string("mmap not supported"));
  642. }
  643. #endif
  644. };
  645. // Represents some region of memory being locked using mlock or VirtualLock;
  646. // will automatically unlock on destruction.
  647. struct llama_mlock {
  648. void * addr = NULL;
  649. size_t size = 0;
  650. bool failed_already = false;
  651. llama_mlock() {}
  652. llama_mlock(const llama_mlock &) = delete;
  653. ~llama_mlock() {
  654. if (size) {
  655. raw_unlock(addr, size);
  656. }
  657. }
  658. void init(void * ptr) {
  659. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  660. addr = ptr;
  661. }
  662. void grow_to(size_t target_size) {
  663. GGML_ASSERT(addr);
  664. if (failed_already) {
  665. return;
  666. }
  667. size_t granularity = lock_granularity();
  668. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  669. if (target_size > size) {
  670. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  671. size = target_size;
  672. } else {
  673. failed_already = true;
  674. }
  675. }
  676. }
  677. #ifdef _POSIX_MEMLOCK_RANGE
  678. static constexpr bool SUPPORTED = true;
  679. static size_t lock_granularity() {
  680. return (size_t) sysconf(_SC_PAGESIZE);
  681. }
  682. #ifdef __APPLE__
  683. #define MLOCK_SUGGESTION \
  684. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  685. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  686. #else
  687. #define MLOCK_SUGGESTION \
  688. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  689. #endif
  690. bool raw_lock(const void * addr, size_t size) const {
  691. if (!mlock(addr, size)) {
  692. return true;
  693. }
  694. char* errmsg = std::strerror(errno);
  695. bool suggest = (errno == ENOMEM);
  696. // Check if the resource limit is fine after all
  697. struct rlimit lock_limit;
  698. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  699. suggest = false;
  700. }
  701. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  702. suggest = false;
  703. }
  704. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  705. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  706. return false;
  707. }
  708. #undef MLOCK_SUGGESTION
  709. static void raw_unlock(void * addr, size_t size) {
  710. if (munlock(addr, size)) {
  711. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  712. }
  713. }
  714. #elif defined(_WIN32)
  715. static constexpr bool SUPPORTED = true;
  716. static size_t lock_granularity() {
  717. SYSTEM_INFO si;
  718. GetSystemInfo(&si);
  719. return (size_t) si.dwPageSize;
  720. }
  721. bool raw_lock(void * ptr, size_t len) const {
  722. for (int tries = 1; ; tries++) {
  723. if (VirtualLock(ptr, len)) {
  724. return true;
  725. }
  726. if (tries == 2) {
  727. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  728. len, size, llama_format_win_err(GetLastError()).c_str());
  729. return false;
  730. }
  731. // It failed but this was only the first try; increase the working
  732. // set size and try again.
  733. SIZE_T min_ws_size, max_ws_size;
  734. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  735. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  736. llama_format_win_err(GetLastError()).c_str());
  737. return false;
  738. }
  739. // Per MSDN: "The maximum number of pages that a process can lock
  740. // is equal to the number of pages in its minimum working set minus
  741. // a small overhead."
  742. // Hopefully a megabyte is enough overhead:
  743. size_t increment = len + 1048576;
  744. // The minimum must be <= the maximum, so we need to increase both:
  745. min_ws_size += increment;
  746. max_ws_size += increment;
  747. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  748. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  749. llama_format_win_err(GetLastError()).c_str());
  750. return false;
  751. }
  752. }
  753. }
  754. static void raw_unlock(void * ptr, size_t len) {
  755. if (!VirtualUnlock(ptr, len)) {
  756. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  757. llama_format_win_err(GetLastError()).c_str());
  758. }
  759. }
  760. #else
  761. static constexpr bool SUPPORTED = false;
  762. static size_t lock_granularity() {
  763. return (size_t) 65536;
  764. }
  765. bool raw_lock(const void * addr, size_t len) const {
  766. fprintf(stderr, "warning: mlock not supported on this system\n");
  767. return false;
  768. }
  769. static void raw_unlock(const void * addr, size_t len) {}
  770. #endif
  771. };
  772. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  773. static void llama_nop(struct ggml_tensor * tensor) { // don't offload by default
  774. (void) tensor;
  775. }
  776. static std::string llama_token_to_str(const struct llama_context * ctx, llama_token token) {
  777. std::vector<char> result(8, 0);
  778. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  779. if (n_tokens < 0) {
  780. result.resize(-n_tokens);
  781. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  782. GGML_ASSERT(check == -n_tokens);
  783. } else {
  784. result.resize(n_tokens);
  785. }
  786. return std::string(result.data(), result.size());
  787. }
  788. //
  789. // globals
  790. //
  791. struct llama_state {
  792. // We save the log callback globally
  793. ggml_log_callback log_callback = llama_log_callback_default;
  794. void * log_callback_user_data = nullptr;
  795. };
  796. static llama_state g_state;
  797. // available llama models
  798. enum e_model {
  799. MODEL_UNKNOWN,
  800. MODEL_1B,
  801. MODEL_3B,
  802. MODEL_7B,
  803. MODEL_13B,
  804. MODEL_15B,
  805. MODEL_30B,
  806. MODEL_34B,
  807. MODEL_40B,
  808. MODEL_65B,
  809. MODEL_70B,
  810. };
  811. static const size_t kB = 1024;
  812. static const size_t MB = kB*kB;
  813. static const size_t GB = kB*kB*kB;
  814. struct llama_hparams {
  815. bool vocab_only;
  816. uint32_t n_vocab;
  817. uint32_t n_ctx_train; // context size the model was trained on
  818. uint32_t n_embd;
  819. uint32_t n_head;
  820. uint32_t n_head_kv;
  821. uint32_t n_layer;
  822. uint32_t n_rot;
  823. uint32_t n_ff;
  824. float f_norm_eps;
  825. float f_norm_rms_eps;
  826. float rope_freq_base_train;
  827. float rope_freq_scale_train;
  828. bool operator!=(const llama_hparams & other) const {
  829. return static_cast<bool>(memcmp(this, &other, sizeof(llama_hparams))); // NOLINT
  830. }
  831. uint32_t n_gqa() const {
  832. return n_head/n_head_kv;
  833. }
  834. uint32_t n_embd_head() const {
  835. return n_embd/n_head;
  836. }
  837. uint32_t n_embd_gqa() const {
  838. return n_embd/n_gqa();
  839. }
  840. };
  841. struct llama_cparams {
  842. uint32_t n_ctx; // context size used during inference
  843. uint32_t n_batch;
  844. uint32_t n_threads; // number of threads to use for generation
  845. uint32_t n_threads_batch; // number of threads to use for batch processing
  846. float rope_freq_base;
  847. float rope_freq_scale;
  848. bool mul_mat_q;
  849. };
  850. struct llama_layer {
  851. // normalization
  852. struct ggml_tensor * attn_norm;
  853. struct ggml_tensor * attn_norm_b;
  854. struct ggml_tensor * attn_norm_2;
  855. struct ggml_tensor * attn_norm_2_b;
  856. // attention
  857. struct ggml_tensor * wq;
  858. struct ggml_tensor * wk;
  859. struct ggml_tensor * wv;
  860. struct ggml_tensor * wo;
  861. struct ggml_tensor * wqkv;
  862. // attention bias
  863. struct ggml_tensor * bo;
  864. struct ggml_tensor * bqkv;
  865. // normalization
  866. struct ggml_tensor * ffn_norm;
  867. struct ggml_tensor * ffn_norm_b;
  868. // ff
  869. struct ggml_tensor * w1; // ffn_gate
  870. struct ggml_tensor * w2; // ffn_down
  871. struct ggml_tensor * w3; // ffn_up
  872. // ff bias
  873. struct ggml_tensor * b2; // ffn_down
  874. struct ggml_tensor * b3; // ffn_up
  875. };
  876. struct llama_kv_cell {
  877. llama_pos pos = -1;
  878. llama_pos delta = 0;
  879. std::set<llama_seq_id> seq_id;
  880. bool has_seq_id(const llama_seq_id & id) const {
  881. return seq_id.find(id) != seq_id.end();
  882. }
  883. };
  884. // ring-buffer of cached KV data
  885. struct llama_kv_cache {
  886. bool has_shift = false;
  887. uint32_t head = 0;
  888. uint32_t size = 0;
  889. // computed before each graph build
  890. uint32_t n = 0;
  891. std::vector<llama_kv_cell> cells;
  892. struct ggml_tensor * k = NULL;
  893. struct ggml_tensor * v = NULL;
  894. struct ggml_context * ctx = NULL;
  895. llama_buffer buf;
  896. ~llama_kv_cache() {
  897. if (ctx) {
  898. ggml_free(ctx);
  899. }
  900. #ifdef GGML_USE_CUBLAS
  901. ggml_cuda_free_data(k);
  902. ggml_cuda_free_data(v);
  903. #endif // GGML_USE_CUBLAS
  904. }
  905. };
  906. struct llama_vocab {
  907. using id = int32_t;
  908. using token = std::string;
  909. using ttype = llama_token_type;
  910. struct token_data {
  911. token text;
  912. float score;
  913. ttype type;
  914. };
  915. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  916. std::unordered_map<token, id> token_to_id;
  917. std::vector<token_data> id_to_token;
  918. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  919. // default LLaMA special tokens
  920. id special_bos_id = 1;
  921. id special_eos_id = 2;
  922. id special_unk_id = 0;
  923. id special_sep_id = -1;
  924. id special_pad_id = -1;
  925. id linefeed_id = 13;
  926. int find_bpe_rank(std::string token_left, std::string token_right) const {
  927. replace_all(token_left, " ", "\u0120");
  928. replace_all(token_left, "\n", "\u010A");
  929. replace_all(token_right, " ", "\u0120");
  930. replace_all(token_right, "\n", "\u010A");
  931. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  932. if (it == bpe_ranks.end()) {
  933. return -1;
  934. }
  935. return it->second;
  936. }
  937. };
  938. struct llama_model {
  939. e_model type = MODEL_UNKNOWN;
  940. llm_arch arch = LLM_ARCH_UNKNOWN;
  941. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  942. std::string name = "n/a";
  943. llama_hparams hparams = {};
  944. llama_vocab vocab;
  945. struct ggml_tensor * tok_embeddings;
  946. struct ggml_tensor * pos_embeddings;
  947. struct ggml_tensor * output_norm;
  948. struct ggml_tensor * output_norm_b;
  949. struct ggml_tensor * output;
  950. std::vector<llama_layer> layers;
  951. int n_gpu_layers;
  952. // context
  953. struct ggml_context * ctx = NULL;
  954. // the model memory buffer
  955. llama_buffer buf;
  956. // model memory mapped file
  957. std::unique_ptr<llama_mmap> mapping;
  958. // objects representing data potentially being locked in memory
  959. llama_mlock mlock_buf;
  960. llama_mlock mlock_mmap;
  961. // for quantize-stats only
  962. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  963. int64_t t_load_us = 0;
  964. int64_t t_start_us = 0;
  965. ~llama_model() {
  966. if (ctx) {
  967. ggml_free(ctx);
  968. }
  969. #ifdef GGML_USE_CUBLAS
  970. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  971. ggml_cuda_free_data(tensors_by_name[i].second);
  972. }
  973. ggml_cuda_free_scratch();
  974. #elif defined(GGML_USE_CLBLAST)
  975. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  976. ggml_cl_free_data(tensors_by_name[i].second);
  977. }
  978. #endif
  979. }
  980. };
  981. struct llama_context {
  982. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  983. ~llama_context() {
  984. #ifdef GGML_USE_METAL
  985. if (ctx_metal) {
  986. ggml_metal_free(ctx_metal);
  987. }
  988. #endif
  989. if (alloc) {
  990. ggml_allocr_free(alloc);
  991. }
  992. }
  993. llama_cparams cparams;
  994. const llama_model & model;
  995. // key + value cache for the self attention
  996. struct llama_kv_cache kv_self;
  997. std::mt19937 rng;
  998. bool has_evaluated_once = false;
  999. int64_t t_start_us;
  1000. int64_t t_load_us;
  1001. int64_t t_sample_us = 0;
  1002. int64_t t_p_eval_us = 0;
  1003. int64_t t_eval_us = 0;
  1004. int32_t n_sample = 0; // number of tokens sampled
  1005. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1006. int32_t n_eval = 0; // number of eval calls
  1007. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1008. std::vector<float> logits;
  1009. bool logits_all = false;
  1010. // input embedding (1-dimensional array: [n_embd])
  1011. std::vector<float> embedding;
  1012. // reusable buffer for `struct ggml_graph_plan.work_data`
  1013. std::vector<uint8_t> work_buffer;
  1014. // memory buffers used to evaluate the model
  1015. llama_buffer buf_compute;
  1016. llama_buffer buf_alloc;
  1017. ggml_allocr * alloc = NULL;
  1018. #ifdef GGML_USE_METAL
  1019. ggml_metal_context * ctx_metal = NULL;
  1020. #endif
  1021. #ifdef GGML_USE_MPI
  1022. ggml_mpi_context * ctx_mpi = NULL;
  1023. #endif
  1024. };
  1025. //
  1026. // kv cache helpers
  1027. //
  1028. static bool llama_kv_cache_init(
  1029. const struct llama_hparams & hparams,
  1030. struct llama_kv_cache & cache,
  1031. ggml_type wtype,
  1032. uint32_t n_ctx,
  1033. int n_gpu_layers) {
  1034. const uint32_t n_embd = hparams.n_embd_gqa();
  1035. const uint32_t n_layer = hparams.n_layer;
  1036. const int64_t n_mem = n_layer*n_ctx;
  1037. const int64_t n_elements = n_embd*n_mem;
  1038. cache.has_shift = false;
  1039. cache.head = 0;
  1040. cache.size = n_ctx;
  1041. cache.cells.clear();
  1042. cache.cells.resize(n_ctx);
  1043. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  1044. struct ggml_init_params params;
  1045. params.mem_size = cache.buf.size;
  1046. params.mem_buffer = cache.buf.data;
  1047. params.no_alloc = false;
  1048. cache.ctx = ggml_init(params);
  1049. if (!cache.ctx) {
  1050. LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
  1051. return false;
  1052. }
  1053. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  1054. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  1055. ggml_set_name(cache.k, "cache_k");
  1056. ggml_set_name(cache.v, "cache_v");
  1057. (void) n_gpu_layers;
  1058. #ifdef GGML_USE_CUBLAS
  1059. size_t vram_kv_cache = 0;
  1060. if (n_gpu_layers > (int)n_layer + 1) {
  1061. ggml_cuda_assign_buffers_no_scratch(cache.v);
  1062. LLAMA_LOG_INFO("%s: offloading v cache to GPU\n", __func__);
  1063. vram_kv_cache += ggml_nbytes(cache.v);
  1064. }
  1065. if (n_gpu_layers > (int)n_layer + 2) {
  1066. ggml_cuda_assign_buffers_no_scratch(cache.k);
  1067. LLAMA_LOG_INFO("%s: offloading k cache to GPU\n", __func__);
  1068. vram_kv_cache += ggml_nbytes(cache.k);
  1069. }
  1070. if (vram_kv_cache > 0) {
  1071. LLAMA_LOG_INFO("%s: VRAM kv self = %.2f MB\n", __func__, vram_kv_cache / 1024.0 / 1024.0);
  1072. }
  1073. #endif // GGML_USE_CUBLAS
  1074. return true;
  1075. }
  1076. // find an empty slot of size "n_tokens" in the cache
  1077. // updates the cache head
  1078. static bool llama_kv_cache_find_slot(
  1079. struct llama_kv_cache & cache,
  1080. const struct llama_batch & batch) {
  1081. const uint32_t n_ctx = cache.size;
  1082. const uint32_t n_tokens = batch.n_tokens;
  1083. if (n_tokens > n_ctx) {
  1084. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1085. return false;
  1086. }
  1087. uint32_t n_tested = 0;
  1088. while (true) {
  1089. if (cache.head + n_tokens > n_ctx) {
  1090. cache.head = 0;
  1091. n_tested += n_ctx - cache.head;
  1092. continue;
  1093. }
  1094. bool found = true;
  1095. for (uint32_t i = 0; i < n_tokens; i++) {
  1096. if (cache.cells[cache.head + i].pos >= 0) {
  1097. found = false;
  1098. cache.head += i + 1;
  1099. n_tested += i + 1;
  1100. break;
  1101. }
  1102. }
  1103. if (found) {
  1104. break;
  1105. }
  1106. if (n_tested >= n_ctx) {
  1107. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1108. return false;
  1109. }
  1110. }
  1111. for (uint32_t i = 0; i < n_tokens; i++) {
  1112. cache.cells[cache.head + i].pos = batch.pos[i];
  1113. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i]);
  1114. }
  1115. return true;
  1116. }
  1117. // find how many cells are currently in use
  1118. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1119. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1120. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1121. return i + 1;
  1122. }
  1123. }
  1124. return 0;
  1125. }
  1126. static void llama_kv_cache_tokens_rm(struct llama_kv_cache & cache, int32_t c0, int32_t c1) {
  1127. if (c0 < 0) c0 = 0;
  1128. if (c1 < 0) c1 = cache.size;
  1129. for (int32_t i = c0; i < c1; ++i) {
  1130. cache.cells[i].pos = -1;
  1131. cache.cells[i].seq_id.clear();
  1132. }
  1133. }
  1134. static void llama_kv_cache_seq_rm(
  1135. struct llama_kv_cache & cache,
  1136. llama_seq_id seq_id,
  1137. llama_pos p0,
  1138. llama_pos p1) {
  1139. for (uint32_t i = 0; i < cache.size; ++i) {
  1140. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1141. cache.cells[i].seq_id.erase(seq_id);
  1142. if (cache.cells[i].seq_id.empty()) {
  1143. cache.cells[i].pos = -1;
  1144. }
  1145. }
  1146. }
  1147. }
  1148. static void llama_kv_cache_seq_cp(
  1149. struct llama_kv_cache & cache,
  1150. llama_seq_id seq_id_src,
  1151. llama_seq_id seq_id_dst,
  1152. llama_pos p0,
  1153. llama_pos p1) {
  1154. for (uint32_t i = 0; i < cache.size; ++i) {
  1155. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1156. cache.cells[i].seq_id.insert(seq_id_dst);
  1157. }
  1158. }
  1159. }
  1160. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1161. for (uint32_t i = 0; i < cache.size; ++i) {
  1162. if (!cache.cells[i].has_seq_id(seq_id)) {
  1163. cache.cells[i].pos = -1;
  1164. cache.cells[i].seq_id.clear();
  1165. }
  1166. }
  1167. }
  1168. static void llama_kv_cache_seq_shift(
  1169. struct llama_kv_cache & cache,
  1170. llama_seq_id seq_id,
  1171. llama_pos p0,
  1172. llama_pos p1,
  1173. llama_pos delta) {
  1174. for (uint32_t i = 0; i < cache.size; ++i) {
  1175. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1176. cache.cells[i].pos += delta;
  1177. if (cache.cells[i].pos < 0) {
  1178. cache.cells[i].pos = -1;
  1179. cache.cells[i].seq_id.clear();
  1180. } else {
  1181. cache.has_shift = true;
  1182. cache.cells[i].delta = delta;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. //
  1188. // model loading and saving
  1189. //
  1190. enum llama_fver {
  1191. GGUF_FILE_VERSION_V1 = 1,
  1192. GGUF_FILE_VERSION_V2 = 2,
  1193. };
  1194. static const char * llama_file_version_name(llama_fver version) {
  1195. switch (version) {
  1196. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1197. case GGUF_FILE_VERSION_V2: return "GGUF V2 (latest)";
  1198. }
  1199. return "unknown";
  1200. }
  1201. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1202. char buf[256];
  1203. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1204. for (size_t i = 1; i < ne.size(); i++) {
  1205. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1206. }
  1207. return buf;
  1208. }
  1209. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1210. char buf[256];
  1211. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1212. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1213. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1214. }
  1215. return buf;
  1216. }
  1217. struct llama_model_loader {
  1218. int n_kv = 0;
  1219. int n_tensors = 0;
  1220. int n_created = 0;
  1221. int64_t n_elements = 0;
  1222. size_t n_bytes = 0;
  1223. bool use_mmap = false;
  1224. llama_file file;
  1225. llama_ftype ftype;
  1226. llama_fver fver;
  1227. std::unique_ptr<llama_mmap> mapping;
  1228. struct gguf_context * ctx_gguf = NULL;
  1229. struct ggml_context * ctx_meta = NULL;
  1230. llama_model_loader(const std::string & fname, bool use_mmap) : file(fname.c_str(), "rb") {
  1231. struct gguf_init_params params = {
  1232. /*.no_alloc = */ true,
  1233. /*.ctx = */ &ctx_meta,
  1234. };
  1235. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1236. if (!ctx_gguf) {
  1237. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1238. }
  1239. n_kv = gguf_get_n_kv(ctx_gguf);
  1240. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1241. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1242. for (int i = 0; i < n_tensors; i++) {
  1243. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1244. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1245. n_elements += ggml_nelements(t);
  1246. n_bytes += ggml_nbytes(t);
  1247. }
  1248. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1249. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1250. // determine file type based on the number of tensors for each quantization and print meta data
  1251. // TODO: make optional
  1252. {
  1253. std::map<enum ggml_type, uint32_t> n_type;
  1254. uint32_t n_type_max = 0;
  1255. enum ggml_type type_max = GGML_TYPE_F32;
  1256. for (int i = 0; i < n_tensors; i++) {
  1257. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1258. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, name);
  1259. n_type[meta->type]++;
  1260. if (n_type_max < n_type[meta->type]) {
  1261. n_type_max = n_type[meta->type];
  1262. type_max = meta->type;
  1263. }
  1264. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, name, ggml_type_name(meta->type), llama_format_tensor_shape(meta).c_str());
  1265. }
  1266. switch (type_max) {
  1267. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1268. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1269. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1270. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1271. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1272. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1273. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1274. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1275. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1276. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1277. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1278. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1279. default:
  1280. {
  1281. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1282. ftype = LLAMA_FTYPE_ALL_F32;
  1283. } break;
  1284. }
  1285. // this is a way to mark that we have "guessed" the file type
  1286. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1287. {
  1288. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  1289. if (kid >= 0) {
  1290. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  1291. }
  1292. }
  1293. for (int i = 0; i < n_kv; i++) {
  1294. const char * name = gguf_get_key(ctx_gguf, i);
  1295. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1296. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-8s\n", __func__, i, name, gguf_type_name(type));
  1297. }
  1298. // print type counts
  1299. for (auto & kv : n_type) {
  1300. if (kv.second == 0) {
  1301. continue;
  1302. }
  1303. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  1304. }
  1305. }
  1306. if (!llama_mmap::SUPPORTED) {
  1307. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  1308. use_mmap = false;
  1309. }
  1310. this->use_mmap = use_mmap;
  1311. }
  1312. ~llama_model_loader() {
  1313. if (ctx_gguf) {
  1314. gguf_free(ctx_gguf);
  1315. }
  1316. if (ctx_meta) {
  1317. ggml_free(ctx_meta);
  1318. }
  1319. }
  1320. std::string get_arch_name() const {
  1321. const auto kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1322. std::string arch_name;
  1323. GGUF_GET_KEY(ctx_gguf, arch_name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_ARCHITECTURE));
  1324. return arch_name;
  1325. }
  1326. enum llm_arch get_arch() const {
  1327. const std::string arch_name = get_arch_name();
  1328. return llm_arch_from_string(arch_name);
  1329. }
  1330. const char * get_tensor_name(int i) const {
  1331. return gguf_get_tensor_name(ctx_gguf, i);
  1332. }
  1333. struct ggml_tensor * get_tensor_meta(int i) const {
  1334. return ggml_get_tensor(ctx_meta, get_tensor_name(i));
  1335. }
  1336. void calc_sizes(size_t & ctx_size_p, size_t & mmapped_size_p) const {
  1337. ctx_size_p = 0;
  1338. mmapped_size_p = 0;
  1339. for (int i = 0; i < n_tensors; i++) {
  1340. struct ggml_tensor * meta = get_tensor_meta(i);
  1341. ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  1342. (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
  1343. }
  1344. }
  1345. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta, ggml_backend backend) {
  1346. if (backend != GGML_BACKEND_CPU) {
  1347. ggml_set_no_alloc(ctx, true);
  1348. }
  1349. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  1350. tensor->backend = backend; // TODO: ggml_set_backend
  1351. ggml_set_name(tensor, ggml_get_name(meta));
  1352. if (backend != GGML_BACKEND_CPU) {
  1353. ggml_set_no_alloc(ctx, use_mmap);
  1354. }
  1355. n_created++;
  1356. return tensor;
  1357. }
  1358. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, ggml_backend backend) {
  1359. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  1360. if (cur == NULL) {
  1361. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  1362. }
  1363. {
  1364. bool is_ok = true;
  1365. for (size_t i = 0; i < ne.size(); ++i) {
  1366. if (ne[i] != cur->ne[i]) {
  1367. is_ok = false;
  1368. break;
  1369. }
  1370. }
  1371. if (!is_ok) {
  1372. throw std::runtime_error(
  1373. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  1374. __func__, name.c_str(),
  1375. llama_format_tensor_shape(ne).c_str(),
  1376. llama_format_tensor_shape(cur).c_str()));
  1377. }
  1378. }
  1379. return create_tensor_for(ctx, cur, backend);
  1380. }
  1381. void done_getting_tensors() const {
  1382. if (n_created != n_tensors) {
  1383. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  1384. }
  1385. }
  1386. size_t file_offset(const char * name) const {
  1387. const int idx = gguf_find_tensor(ctx_gguf, name);
  1388. if (idx < 0) {
  1389. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  1390. }
  1391. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  1392. }
  1393. void load_data_for(struct ggml_tensor * cur) const {
  1394. const size_t offs = file_offset(ggml_get_name(cur));
  1395. if (use_mmap) {
  1396. cur->data = (uint8_t *) mapping->addr + offs;
  1397. } else {
  1398. file.seek(offs, SEEK_SET);
  1399. file.read_raw(cur->data, ggml_nbytes(cur));
  1400. }
  1401. }
  1402. void load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  1403. size_t size_data = 0;
  1404. size_t size_lock = 0;
  1405. size_t size_pref = 0; // prefetch
  1406. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1407. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1408. size_data += ggml_nbytes(cur);
  1409. if (cur->backend == GGML_BACKEND_CPU) {
  1410. size_pref += ggml_nbytes(cur);
  1411. }
  1412. }
  1413. if (use_mmap) {
  1414. mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
  1415. if (lmlock) {
  1416. lmlock->init(mapping->addr);
  1417. }
  1418. }
  1419. size_t done_size = 0;
  1420. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1421. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1422. GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
  1423. if (progress_callback) {
  1424. progress_callback((float) done_size / size_data, progress_callback_user_data);
  1425. }
  1426. // allocate temp buffer if not using mmap
  1427. if (!use_mmap && cur->data == NULL) {
  1428. GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
  1429. #ifdef GGML_USE_CPU_HBM
  1430. cur->data = (uint8_t*)hbw_malloc(ggml_nbytes(cur));
  1431. #else
  1432. cur->data = (uint8_t*)malloc(ggml_nbytes(cur));
  1433. #endif
  1434. }
  1435. load_data_for(cur);
  1436. switch (cur->backend) {
  1437. case GGML_BACKEND_CPU:
  1438. if (use_mmap && lmlock) {
  1439. size_lock += ggml_nbytes(cur);
  1440. lmlock->grow_to(size_lock);
  1441. }
  1442. break;
  1443. #ifdef GGML_USE_CUBLAS
  1444. case GGML_BACKEND_GPU:
  1445. case GGML_BACKEND_GPU_SPLIT:
  1446. // old code:
  1447. //ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  1448. // TODO: test if this works !!
  1449. ggml_cuda_transform_tensor(cur->data, cur);
  1450. if (!use_mmap) {
  1451. free(cur->data);
  1452. }
  1453. break;
  1454. #elif defined(GGML_USE_CLBLAST)
  1455. case GGML_BACKEND_GPU:
  1456. ggml_cl_transform_tensor(cur->data, cur);
  1457. if (!use_mmap) {
  1458. free(cur->data);
  1459. }
  1460. break;
  1461. #endif
  1462. default:
  1463. continue;
  1464. }
  1465. done_size += ggml_nbytes(cur);
  1466. }
  1467. }
  1468. };
  1469. //
  1470. // load LLaMA models
  1471. //
  1472. static std::string llama_model_arch_name(llm_arch arch) {
  1473. auto it = LLM_ARCH_NAMES.find(arch);
  1474. if (it == LLM_ARCH_NAMES.end()) {
  1475. return "unknown";
  1476. }
  1477. return it->second;
  1478. }
  1479. static std::string llama_model_ftype_name(llama_ftype ftype) {
  1480. if (ftype & LLAMA_FTYPE_GUESSED) {
  1481. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  1482. }
  1483. switch (ftype) {
  1484. case LLAMA_FTYPE_ALL_F32: return "all F32";
  1485. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  1486. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  1487. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  1488. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  1489. return "mostly Q4_1, some F16";
  1490. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  1491. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  1492. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  1493. // K-quants
  1494. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  1495. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  1496. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  1497. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  1498. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  1499. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  1500. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  1501. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  1502. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  1503. default: return "unknown, may not work";
  1504. }
  1505. }
  1506. static const char * llama_model_type_name(e_model type) {
  1507. switch (type) {
  1508. case MODEL_1B: return "1B";
  1509. case MODEL_3B: return "3B";
  1510. case MODEL_7B: return "7B";
  1511. case MODEL_13B: return "13B";
  1512. case MODEL_15B: return "15B";
  1513. case MODEL_30B: return "30B";
  1514. case MODEL_34B: return "34B";
  1515. case MODEL_40B: return "40B";
  1516. case MODEL_65B: return "65B";
  1517. case MODEL_70B: return "70B";
  1518. default: return "?B";
  1519. }
  1520. }
  1521. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  1522. model.arch = ml.get_arch();
  1523. if (model.arch == LLM_ARCH_UNKNOWN) {
  1524. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  1525. }
  1526. }
  1527. static void llm_load_hparams(
  1528. llama_model_loader & ml,
  1529. llama_model & model) {
  1530. struct gguf_context * ctx = ml.ctx_gguf;
  1531. const auto kv = LLM_KV(model.arch);
  1532. auto & hparams = model.hparams;
  1533. // get general kv
  1534. GGUF_GET_KEY(ctx, model.name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_NAME));
  1535. // get hparams kv
  1536. GGUF_GET_KEY(ctx, hparams.n_vocab, gguf_get_arr_n, GGUF_TYPE_ARRAY, true, kv(LLM_KV_TOKENIZER_LIST));
  1537. GGUF_GET_KEY(ctx, hparams.n_ctx_train, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_CONTEXT_LENGTH));
  1538. GGUF_GET_KEY(ctx, hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  1539. GGUF_GET_KEY(ctx, hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  1540. GGUF_GET_KEY(ctx, hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  1541. GGUF_GET_KEY(ctx, hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  1542. // n_head_kv is optional, default to n_head
  1543. hparams.n_head_kv = hparams.n_head;
  1544. GGUF_GET_KEY(ctx, hparams.n_head_kv, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ATTENTION_HEAD_COUNT_KV));
  1545. // rope_freq_base (optional)
  1546. hparams.rope_freq_base_train = 10000.0f;
  1547. GGUF_GET_KEY(ctx, hparams.rope_freq_base_train, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_FREQ_BASE));
  1548. // rope_freq_scale (inverse of the kv) is optional
  1549. float ropescale = 1.0f;
  1550. GGUF_GET_KEY(ctx, ropescale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  1551. hparams.rope_freq_scale_train = 1.0f/ropescale;
  1552. // sanity check for n_rot (optional)
  1553. {
  1554. hparams.n_rot = hparams.n_embd / hparams.n_head;
  1555. GGUF_GET_KEY(ctx, hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  1556. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  1557. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  1558. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  1559. }
  1560. }
  1561. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  1562. // gpt-j n_rot = rotary_dim
  1563. }
  1564. // arch-specific KVs
  1565. switch (model.arch) {
  1566. case LLM_ARCH_LLAMA:
  1567. {
  1568. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1569. switch (hparams.n_layer) {
  1570. case 26: model.type = e_model::MODEL_3B; break;
  1571. case 32: model.type = e_model::MODEL_7B; break;
  1572. case 40: model.type = e_model::MODEL_13B; break;
  1573. case 48: model.type = e_model::MODEL_34B; break;
  1574. case 60: model.type = e_model::MODEL_30B; break;
  1575. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  1576. default: model.type = e_model::MODEL_UNKNOWN;
  1577. }
  1578. } break;
  1579. case LLM_ARCH_FALCON:
  1580. {
  1581. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1582. switch (hparams.n_layer) {
  1583. case 32: model.type = e_model::MODEL_7B; break;
  1584. case 60: model.type = e_model::MODEL_40B; break;
  1585. default: model.type = e_model::MODEL_UNKNOWN;
  1586. }
  1587. } break;
  1588. case LLM_ARCH_BAICHUAN:
  1589. {
  1590. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1591. switch (hparams.n_layer) {
  1592. case 32: model.type = e_model::MODEL_7B; break;
  1593. case 40: model.type = e_model::MODEL_13B; break;
  1594. default: model.type = e_model::MODEL_UNKNOWN;
  1595. }
  1596. } break;
  1597. case LLM_ARCH_STARCODER:
  1598. {
  1599. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1600. switch (hparams.n_layer) {
  1601. case 24: model.type = e_model::MODEL_1B; break;
  1602. case 36: model.type = e_model::MODEL_3B; break;
  1603. case 42: model.type = e_model::MODEL_7B; break;
  1604. case 40: model.type = e_model::MODEL_15B; break;
  1605. default: model.type = e_model::MODEL_UNKNOWN;
  1606. }
  1607. } break;
  1608. default: (void)0;
  1609. }
  1610. model.ftype = ml.ftype;
  1611. }
  1612. // TODO: This should probably be in llama.h
  1613. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos);
  1614. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  1615. static void llm_load_vocab(
  1616. llama_model_loader & ml,
  1617. llama_model & model) {
  1618. auto & vocab = model.vocab;
  1619. struct gguf_context * ctx = ml.ctx_gguf;
  1620. const auto kv = LLM_KV(model.arch);
  1621. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  1622. if (token_idx == -1) {
  1623. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1624. }
  1625. const float * scores = nullptr;
  1626. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  1627. if (score_idx != -1) {
  1628. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  1629. }
  1630. const int * toktypes = nullptr;
  1631. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  1632. if (toktype_idx != -1) {
  1633. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  1634. }
  1635. // determine vocab type
  1636. {
  1637. std::string tokenizer_name;
  1638. GGUF_GET_KEY(ctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  1639. if (tokenizer_name == "llama") {
  1640. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1641. // default special tokens
  1642. vocab.special_bos_id = 1;
  1643. vocab.special_eos_id = 2;
  1644. vocab.special_unk_id = 0;
  1645. vocab.special_sep_id = -1;
  1646. vocab.special_pad_id = -1;
  1647. } else if (tokenizer_name == "gpt2") {
  1648. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  1649. // read bpe merges and populate bpe ranks
  1650. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  1651. if (merges_keyidx == -1) {
  1652. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  1653. }
  1654. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  1655. for (int i = 0; i < n_merges; i++) {
  1656. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  1657. std::string first;
  1658. std::string second;
  1659. const size_t pos = word.find(' ', 1);
  1660. if (pos != std::string::npos) {
  1661. first = word.substr(0, pos);
  1662. second = word.substr(pos + 1);
  1663. }
  1664. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  1665. }
  1666. // default special tokens
  1667. vocab.special_bos_id = 11;
  1668. vocab.special_eos_id = 11;
  1669. vocab.special_unk_id = -1;
  1670. vocab.special_sep_id = -1;
  1671. vocab.special_pad_id = -1;
  1672. } else {
  1673. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1674. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  1675. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1676. }
  1677. }
  1678. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  1679. vocab.id_to_token.resize(n_vocab);
  1680. for (uint32_t i = 0; i < n_vocab; i++) {
  1681. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  1682. vocab.token_to_id[word] = i;
  1683. auto & token_data = vocab.id_to_token[i];
  1684. token_data.text = std::move(word);
  1685. token_data.score = scores ? scores[i] : 0.0f;
  1686. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  1687. }
  1688. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  1689. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  1690. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  1691. } else {
  1692. vocab.linefeed_id = llama_tokenize_internal(vocab, "\n", false)[0];
  1693. }
  1694. // special tokens
  1695. GGUF_GET_KEY(ctx, vocab.special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
  1696. GGUF_GET_KEY(ctx, vocab.special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
  1697. GGUF_GET_KEY(ctx, vocab.special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
  1698. GGUF_GET_KEY(ctx, vocab.special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
  1699. GGUF_GET_KEY(ctx, vocab.special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
  1700. }
  1701. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  1702. const auto & hparams = model.hparams;
  1703. const auto & vocab = model.vocab;
  1704. // hparams
  1705. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  1706. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  1707. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  1708. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  1709. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  1710. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  1711. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  1712. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  1713. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  1714. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  1715. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  1716. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  1717. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  1718. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  1719. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  1720. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  1721. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  1722. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  1723. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  1724. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  1725. if (ml.n_bytes < GB) {
  1726. LLAMA_LOG_INFO("%s: model size = %.2f MiB (%.2f BPW) \n", __func__, ml.n_bytes/1024.0/1024.0, ml.n_bytes*8.0/ml.n_elements);
  1727. } else {
  1728. LLAMA_LOG_INFO("%s: model size = %.2f GiB (%.2f BPW) \n", __func__, ml.n_bytes/1024.0/1024.0/1024.0, ml.n_bytes*8.0/ml.n_elements);
  1729. }
  1730. // general kv
  1731. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  1732. // special tokens
  1733. if (vocab.special_bos_id != -1) { LLAMA_LOG_INFO( "%s: BOS token = %d '%s'\n", __func__, vocab.special_bos_id, vocab.id_to_token[vocab.special_bos_id].text.c_str() ); }
  1734. if (vocab.special_eos_id != -1) { LLAMA_LOG_INFO( "%s: EOS token = %d '%s'\n", __func__, vocab.special_eos_id, vocab.id_to_token[vocab.special_eos_id].text.c_str() ); }
  1735. if (vocab.special_unk_id != -1) { LLAMA_LOG_INFO( "%s: UNK token = %d '%s'\n", __func__, vocab.special_unk_id, vocab.id_to_token[vocab.special_unk_id].text.c_str() ); }
  1736. if (vocab.special_sep_id != -1) { LLAMA_LOG_INFO( "%s: SEP token = %d '%s'\n", __func__, vocab.special_sep_id, vocab.id_to_token[vocab.special_sep_id].text.c_str() ); }
  1737. if (vocab.special_pad_id != -1) { LLAMA_LOG_INFO( "%s: PAD token = %d '%s'\n", __func__, vocab.special_pad_id, vocab.id_to_token[vocab.special_pad_id].text.c_str() ); }
  1738. if (vocab.linefeed_id != -1) { LLAMA_LOG_INFO( "%s: LF token = %d '%s'\n", __func__, vocab.linefeed_id, vocab.id_to_token[vocab.linefeed_id].text.c_str() ); }
  1739. }
  1740. static void llm_load_tensors(
  1741. llama_model_loader & ml,
  1742. llama_model & model,
  1743. int n_gpu_layers,
  1744. int main_gpu,
  1745. const float * tensor_split,
  1746. bool use_mlock,
  1747. llama_progress_callback progress_callback,
  1748. void * progress_callback_user_data) {
  1749. model.t_start_us = ggml_time_us();
  1750. auto & ctx = model.ctx;
  1751. auto & hparams = model.hparams;
  1752. model.n_gpu_layers = n_gpu_layers;
  1753. size_t ctx_size;
  1754. size_t mmapped_size;
  1755. ml.calc_sizes(ctx_size, mmapped_size);
  1756. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  1757. // create the ggml context
  1758. {
  1759. model.buf.resize(ctx_size);
  1760. if (use_mlock) {
  1761. model.mlock_buf.init (model.buf.data);
  1762. model.mlock_buf.grow_to(model.buf.size);
  1763. }
  1764. struct ggml_init_params params = {
  1765. /*.mem_size =*/ model.buf.size,
  1766. /*.mem_buffer =*/ model.buf.data,
  1767. /*.no_alloc =*/ ml.use_mmap,
  1768. };
  1769. model.ctx = ggml_init(params);
  1770. if (!model.ctx) {
  1771. throw std::runtime_error(format("ggml_init() failed"));
  1772. }
  1773. }
  1774. (void) main_gpu;
  1775. #ifdef GGML_USE_CUBLAS
  1776. LLAMA_LOG_INFO("%s: using " GGML_CUDA_NAME " for GPU acceleration\n", __func__);
  1777. ggml_cuda_set_main_device(main_gpu);
  1778. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1779. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU_SPLIT
  1780. #elif defined(GGML_USE_CLBLAST)
  1781. LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
  1782. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1783. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU
  1784. #else
  1785. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  1786. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_CPU
  1787. #endif
  1788. // prepare memory for the weights
  1789. size_t vram_weights = 0;
  1790. {
  1791. const int64_t n_embd = hparams.n_embd;
  1792. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1793. const int64_t n_layer = hparams.n_layer;
  1794. const int64_t n_vocab = hparams.n_vocab;
  1795. const auto tn = LLM_TN(model.arch);
  1796. switch (model.arch) {
  1797. case LLM_ARCH_LLAMA:
  1798. {
  1799. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1800. // output
  1801. {
  1802. ggml_backend backend_norm;
  1803. ggml_backend backend_output;
  1804. if (n_gpu_layers > int(n_layer)) {
  1805. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1806. // on Windows however this is detrimental unless everything is on the GPU
  1807. #ifndef _WIN32
  1808. backend_norm = LLAMA_BACKEND_OFFLOAD;
  1809. #else
  1810. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1811. #endif // _WIN32
  1812. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1813. } else {
  1814. backend_norm = GGML_BACKEND_CPU;
  1815. backend_output = GGML_BACKEND_CPU;
  1816. }
  1817. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1818. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1819. if (backend_norm == GGML_BACKEND_GPU) {
  1820. vram_weights += ggml_nbytes(model.output_norm);
  1821. }
  1822. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1823. vram_weights += ggml_nbytes(model.output);
  1824. }
  1825. }
  1826. const uint32_t n_ff = hparams.n_ff;
  1827. const int i_gpu_start = n_layer - n_gpu_layers;
  1828. model.layers.resize(n_layer);
  1829. for (uint32_t i = 0; i < n_layer; ++i) {
  1830. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1831. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1832. auto & layer = model.layers[i];
  1833. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1834. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  1835. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1836. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1837. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1838. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  1839. layer.w1 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  1840. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1841. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1842. if (backend == GGML_BACKEND_GPU) {
  1843. vram_weights +=
  1844. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  1845. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  1846. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1847. }
  1848. }
  1849. } break;
  1850. case LLM_ARCH_BAICHUAN:
  1851. {
  1852. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1853. {
  1854. ggml_backend backend_norm;
  1855. ggml_backend backend_output;
  1856. if (n_gpu_layers > int(n_layer)) {
  1857. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1858. // on Windows however this is detrimental unless everything is on the GPU
  1859. #ifndef _WIN32
  1860. backend_norm = LLAMA_BACKEND_OFFLOAD;
  1861. #else
  1862. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1863. #endif // _WIN32
  1864. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1865. } else {
  1866. backend_norm = GGML_BACKEND_CPU;
  1867. backend_output = GGML_BACKEND_CPU;
  1868. }
  1869. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1870. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1871. if (backend_norm == GGML_BACKEND_GPU) {
  1872. vram_weights += ggml_nbytes(model.output_norm);
  1873. }
  1874. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1875. vram_weights += ggml_nbytes(model.output);
  1876. }
  1877. }
  1878. const uint32_t n_ff = hparams.n_ff;
  1879. const int i_gpu_start = n_layer - n_gpu_layers;
  1880. model.layers.resize(n_layer);
  1881. for (uint32_t i = 0; i < n_layer; ++i) {
  1882. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1883. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1884. auto & layer = model.layers[i];
  1885. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1886. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  1887. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1888. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1889. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1890. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  1891. layer.w1 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  1892. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1893. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1894. if (backend == GGML_BACKEND_GPU) {
  1895. vram_weights +=
  1896. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  1897. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  1898. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1899. }
  1900. }
  1901. } break;
  1902. case LLM_ARCH_FALCON:
  1903. {
  1904. // TODO: CPU-only for now
  1905. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1906. // output
  1907. {
  1908. ggml_backend backend_norm;
  1909. ggml_backend backend_output;
  1910. if (n_gpu_layers > int(n_layer)) {
  1911. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1912. // on Windows however this is detrimental unless everything is on the GPU
  1913. #ifndef _WIN32
  1914. backend_norm = LLAMA_BACKEND_OFFLOAD;
  1915. #else
  1916. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1917. #endif // _WIN32
  1918. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1919. } else {
  1920. backend_norm = GGML_BACKEND_CPU;
  1921. backend_output = GGML_BACKEND_CPU;
  1922. }
  1923. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1924. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  1925. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1926. if (backend_norm == GGML_BACKEND_GPU) {
  1927. vram_weights += ggml_nbytes(model.output_norm);
  1928. vram_weights += ggml_nbytes(model.output_norm_b);
  1929. }
  1930. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1931. vram_weights += ggml_nbytes(model.output);
  1932. }
  1933. }
  1934. const uint32_t n_ff = hparams.n_ff;
  1935. const int i_gpu_start = n_layer - n_gpu_layers;
  1936. model.layers.resize(n_layer);
  1937. for (uint32_t i = 0; i < n_layer; ++i) {
  1938. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1939. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1940. auto & layer = model.layers[i];
  1941. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1942. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  1943. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  1944. layer.attn_norm_2 = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, backend);
  1945. layer.attn_norm_2_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, backend);
  1946. if (backend == GGML_BACKEND_GPU) {
  1947. vram_weights += ggml_nbytes(layer.attn_norm_2);
  1948. vram_weights += ggml_nbytes(layer.attn_norm_2_b);
  1949. }
  1950. }
  1951. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  1952. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1953. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1954. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1955. if (backend == GGML_BACKEND_GPU) {
  1956. vram_weights +=
  1957. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  1958. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.wo) +
  1959. ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1960. }
  1961. }
  1962. } break;
  1963. case LLM_ARCH_STARCODER:
  1964. {
  1965. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1966. model.pos_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, GGML_BACKEND_CPU);
  1967. // output
  1968. {
  1969. ggml_backend backend_norm;
  1970. ggml_backend backend_output;
  1971. if (n_gpu_layers > int(n_layer)) {
  1972. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1973. // on Windows however this is detrimental unless everything is on the GPU
  1974. #ifndef _WIN32
  1975. backend_norm = LLAMA_BACKEND_OFFLOAD;
  1976. #else
  1977. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1978. #endif // _WIN32
  1979. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1980. } else {
  1981. backend_norm = GGML_BACKEND_CPU;
  1982. backend_output = GGML_BACKEND_CPU;
  1983. }
  1984. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1985. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  1986. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1987. if (backend_norm == GGML_BACKEND_GPU) {
  1988. vram_weights += ggml_nbytes(model.output_norm);
  1989. vram_weights += ggml_nbytes(model.output_norm_b);
  1990. }
  1991. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1992. vram_weights += ggml_nbytes(model.output);
  1993. }
  1994. }
  1995. const uint32_t n_ff = hparams.n_ff;
  1996. const int i_gpu_start = n_layer - n_gpu_layers;
  1997. model.layers.resize(n_layer);
  1998. for (uint32_t i = 0; i < n_layer; ++i) {
  1999. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  2000. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  2001. auto & layer = model.layers[i];
  2002. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2003. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2004. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2005. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, backend_split);
  2006. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2007. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend_split);
  2008. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2009. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2010. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, backend_split);
  2011. layer.b2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, backend_split);
  2012. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2013. layer.b3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, backend_split);
  2014. if (backend == GGML_BACKEND_GPU) {
  2015. vram_weights +=
  2016. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  2017. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.bqkv) +
  2018. ggml_nbytes(layer.wo) + ggml_nbytes(layer.bo) +
  2019. ggml_nbytes(layer.ffn_norm) + ggml_nbytes(layer.ffn_norm_b) +
  2020. ggml_nbytes(layer.w2) + ggml_nbytes(layer.b2) +
  2021. ggml_nbytes(layer.w3) + ggml_nbytes(layer.b3);
  2022. }
  2023. }
  2024. } break;
  2025. default:
  2026. throw std::runtime_error("unknown architecture");
  2027. }
  2028. }
  2029. ml.done_getting_tensors();
  2030. // print memory requirements
  2031. {
  2032. // this is the total memory required to run the inference
  2033. size_t mem_required =
  2034. ctx_size +
  2035. mmapped_size - vram_weights; // weights in VRAM not in memory
  2036. LLAMA_LOG_INFO("%s: mem required = %7.2f MB\n", __func__, mem_required / 1024.0 / 1024.0);
  2037. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  2038. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  2039. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  2040. if (n_gpu_layers > (int) hparams.n_layer) {
  2041. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  2042. }
  2043. #ifdef GGML_USE_CUBLAS
  2044. const int max_backend_supported_layers = hparams.n_layer + 3;
  2045. const int max_offloadable_layers = hparams.n_layer + 3;
  2046. #elif defined(GGML_USE_CLBLAST)
  2047. const int max_backend_supported_layers = hparams.n_layer + 1;
  2048. const int max_offloadable_layers = hparams.n_layer + 1;
  2049. #endif // GGML_USE_CUBLAS
  2050. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  2051. LLAMA_LOG_INFO("%s: VRAM used: %.2f MB\n", __func__, vram_weights / 1024.0 / 1024.0);
  2052. #else
  2053. (void) n_gpu_layers;
  2054. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  2055. }
  2056. // populate `tensors_by_name`
  2057. for (int i = 0; i < ml.n_tensors; ++i) {
  2058. struct ggml_tensor * cur = ggml_get_tensor(ctx, ml.get_tensor_name(i));
  2059. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  2060. }
  2061. (void) tensor_split;
  2062. #ifdef GGML_USE_CUBLAS
  2063. {
  2064. ggml_cuda_set_tensor_split(tensor_split);
  2065. }
  2066. #endif
  2067. ml.load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  2068. if (progress_callback) {
  2069. progress_callback(1.0f, progress_callback_user_data);
  2070. }
  2071. model.mapping = std::move(ml.mapping);
  2072. // loading time will be recalculate after the first eval, so
  2073. // we take page faults deferred by mmap() into consideration
  2074. model.t_load_us = ggml_time_us() - model.t_start_us;
  2075. }
  2076. static bool llama_model_load(
  2077. const std::string & fname,
  2078. llama_model & model,
  2079. int n_gpu_layers,
  2080. int main_gpu,
  2081. const float * tensor_split,
  2082. bool use_mmap,
  2083. bool use_mlock,
  2084. bool vocab_only,
  2085. llama_progress_callback progress_callback,
  2086. void *progress_callback_user_data) {
  2087. try {
  2088. llama_model_loader ml(fname, use_mmap);
  2089. model.hparams.vocab_only = vocab_only;
  2090. llm_load_arch (ml, model);
  2091. llm_load_hparams(ml, model);
  2092. llm_load_vocab (ml, model);
  2093. llm_load_print_meta(ml, model);
  2094. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  2095. throw std::runtime_error("vocab size mismatch");
  2096. }
  2097. if (vocab_only) {
  2098. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  2099. return true;
  2100. }
  2101. llm_load_tensors(
  2102. ml, model, n_gpu_layers,
  2103. main_gpu, tensor_split,
  2104. use_mlock, progress_callback, progress_callback_user_data);
  2105. } catch (const std::exception & err) {
  2106. LLAMA_LOG_ERROR("error loading model: %s\n", err.what());
  2107. return false;
  2108. }
  2109. return true;
  2110. }
  2111. static struct ggml_cgraph * llm_build_llama(
  2112. llama_context & lctx,
  2113. const llama_batch & batch) {
  2114. const auto & model = lctx.model;
  2115. const auto & hparams = model.hparams;
  2116. const auto & cparams = lctx.cparams;
  2117. const auto & kv_self = lctx.kv_self;
  2118. GGML_ASSERT(!!kv_self.ctx);
  2119. const int64_t n_embd = hparams.n_embd;
  2120. const int64_t n_layer = hparams.n_layer;
  2121. const int64_t n_ctx = cparams.n_ctx;
  2122. const int64_t n_head = hparams.n_head;
  2123. const int64_t n_head_kv = hparams.n_head_kv;
  2124. const int64_t n_embd_head = hparams.n_embd_head();
  2125. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2126. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2127. const float freq_base = cparams.rope_freq_base;
  2128. const float freq_scale = cparams.rope_freq_scale;
  2129. const float norm_rms_eps = hparams.f_norm_rms_eps;
  2130. const int n_gpu_layers = model.n_gpu_layers;
  2131. const int32_t n_tokens = batch.n_tokens;
  2132. const int32_t n_kv = ggml_allocr_is_measure(lctx.alloc) ? n_ctx : kv_self.n;
  2133. const int32_t kv_head = ggml_allocr_is_measure(lctx.alloc) ? n_ctx - n_tokens : kv_self.head;
  2134. const bool do_rope_shift = ggml_allocr_is_measure(lctx.alloc) || kv_self.has_shift;
  2135. //printf("n_kv = %d\n", n_kv);
  2136. auto & buf_compute = lctx.buf_compute;
  2137. struct ggml_init_params params = {
  2138. /*.mem_size =*/ buf_compute.size,
  2139. /*.mem_buffer =*/ buf_compute.data,
  2140. /*.no_alloc =*/ false,
  2141. };
  2142. params.no_alloc = true;
  2143. struct ggml_context * ctx0 = ggml_init(params);
  2144. ggml_cgraph * gf = ggml_new_graph(ctx0);
  2145. struct ggml_tensor * cur;
  2146. struct ggml_tensor * inpL;
  2147. if (batch.token) {
  2148. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  2149. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  2150. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2151. memcpy(inp_tokens->data, batch.token, n_tokens*ggml_element_size(inp_tokens));
  2152. }
  2153. ggml_set_name(inp_tokens, "inp_tokens");
  2154. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  2155. } else {
  2156. #ifdef GGML_USE_MPI
  2157. GGML_ASSERT(false && "not implemented");
  2158. #endif
  2159. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens);
  2160. ggml_allocr_alloc(lctx.alloc, inpL);
  2161. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2162. memcpy(inpL->data, batch.embd, n_tokens * n_embd * ggml_element_size(inpL));
  2163. }
  2164. }
  2165. const int i_gpu_start = n_layer - n_gpu_layers;
  2166. (void) i_gpu_start;
  2167. // offload functions set the tensor output backend to GPU
  2168. // tensors are GPU-accelerated if any input or the output has been offloaded
  2169. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  2170. offload_func_t offload_func_kq = llama_nop;
  2171. offload_func_t offload_func_v = llama_nop;
  2172. #ifdef GGML_USE_CUBLAS
  2173. if (n_gpu_layers > n_layer) {
  2174. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  2175. }
  2176. if (n_gpu_layers > n_layer + 1) {
  2177. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  2178. }
  2179. if (n_gpu_layers > n_layer + 2) {
  2180. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  2181. }
  2182. #endif // GGML_USE_CUBLAS
  2183. // KQ_scale
  2184. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  2185. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  2186. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  2187. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2188. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd_head)));
  2189. }
  2190. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2191. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  2192. offload_func_kq(KQ_mask);
  2193. ggml_set_name(KQ_mask, "KQ_mask");
  2194. ggml_allocr_alloc(lctx.alloc, KQ_mask);
  2195. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2196. float * data = (float *) KQ_mask->data;
  2197. memset(data, 0, ggml_nbytes(KQ_mask));
  2198. for (int h = 0; h < 1; ++h) {
  2199. for (int j = 0; j < n_tokens; ++j) {
  2200. const llama_pos pos = batch.pos[j];
  2201. const llama_seq_id seq_id = batch.seq_id[j];
  2202. for (int i = 0; i < n_kv; ++i) {
  2203. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  2204. data[h*(n_kv*n_tokens) + j*n_kv + i] = -INFINITY;
  2205. }
  2206. }
  2207. }
  2208. }
  2209. }
  2210. // KQ_pos - contains the positions
  2211. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  2212. offload_func_kq(KQ_pos);
  2213. ggml_set_name(KQ_pos, "KQ_pos");
  2214. ggml_allocr_alloc(lctx.alloc, KQ_pos);
  2215. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2216. int * data = (int *) KQ_pos->data;
  2217. for (int i = 0; i < n_tokens; ++i) {
  2218. data[i] = batch.pos[i];
  2219. }
  2220. }
  2221. // shift the entire K-cache if needed
  2222. if (do_rope_shift) {
  2223. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  2224. offload_func_kq(K_shift);
  2225. ggml_set_name(K_shift, "K_shift");
  2226. ggml_allocr_alloc(lctx.alloc, K_shift);
  2227. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2228. int * data = (int *) K_shift->data;
  2229. for (int i = 0; i < n_ctx; ++i) {
  2230. data[i] = kv_self.cells[i].delta;
  2231. }
  2232. }
  2233. for (int il = 0; il < n_layer; ++il) {
  2234. struct ggml_tensor * tmp =
  2235. ggml_rope_custom_inplace(ctx0,
  2236. ggml_view_3d(ctx0, kv_self.k,
  2237. n_embd_head, n_head_kv, n_ctx,
  2238. ggml_element_size(kv_self.k)*n_embd_head,
  2239. ggml_element_size(kv_self.k)*n_embd_gqa,
  2240. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il),
  2241. K_shift, n_embd_head, 0, 0, freq_base, freq_scale);
  2242. offload_func_kq(tmp);
  2243. ggml_build_forward_expand(gf, tmp);
  2244. }
  2245. }
  2246. for (int il = 0; il < n_layer; ++il) {
  2247. ggml_format_name(inpL, "layer_inp_%d", il);
  2248. offload_func_t offload_func = llama_nop;
  2249. #ifdef GGML_USE_CUBLAS
  2250. if (il >= i_gpu_start) {
  2251. offload_func = ggml_cuda_assign_buffers_no_alloc;
  2252. }
  2253. #endif // GGML_USE_CUBLAS
  2254. struct ggml_tensor * inpSA = inpL;
  2255. // norm
  2256. {
  2257. cur = ggml_rms_norm(ctx0, inpL, norm_rms_eps);
  2258. offload_func(cur);
  2259. ggml_set_name(cur, "rms_norm_0");
  2260. // cur = cur*attn_norm(broadcasted)
  2261. cur = ggml_mul(ctx0, cur, model.layers[il].attn_norm);
  2262. offload_func(cur);
  2263. ggml_set_name(cur, "attention_norm_0");
  2264. }
  2265. // self-attention
  2266. {
  2267. // compute Q and K and RoPE them
  2268. struct ggml_tensor * tmpk = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  2269. offload_func_kq(tmpk);
  2270. ggml_set_name(tmpk, "tmpk");
  2271. struct ggml_tensor * tmpq = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  2272. offload_func_kq(tmpq);
  2273. ggml_set_name(tmpq, "tmpq");
  2274. struct ggml_tensor * Kcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), KQ_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  2275. offload_func_kq(Kcur);
  2276. ggml_set_name(Kcur, "Kcur");
  2277. struct ggml_tensor * Qcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), KQ_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  2278. offload_func_kq(Qcur);
  2279. ggml_set_name(Qcur, "Qcur");
  2280. // store key and value to memory
  2281. {
  2282. // compute the transposed [n_tokens, n_embd] V matrix
  2283. struct ggml_tensor * tmpv = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  2284. offload_func_v(tmpv);
  2285. ggml_set_name(tmpv, "tmpv");
  2286. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, tmpv, n_embd_gqa, n_tokens));
  2287. offload_func_v(Vcur);
  2288. ggml_set_name(Vcur, "Vcur");
  2289. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, n_tokens*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + kv_head));
  2290. offload_func_kq(k);
  2291. ggml_set_name(k, "k");
  2292. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, n_tokens, n_embd_gqa,
  2293. ( n_ctx)*ggml_element_size(kv_self.v),
  2294. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + kv_head*ggml_element_size(kv_self.v));
  2295. offload_func_v(v);
  2296. ggml_set_name(v, "v");
  2297. // important: storing RoPE-ed version of K in the KV cache!
  2298. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  2299. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  2300. }
  2301. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  2302. offload_func_kq(Q);
  2303. ggml_set_name(Q, "Q");
  2304. struct ggml_tensor * K =
  2305. ggml_view_3d(ctx0, kv_self.k,
  2306. n_embd_head, n_kv, n_head_kv,
  2307. ggml_element_size(kv_self.k)*n_embd_gqa,
  2308. ggml_element_size(kv_self.k)*n_embd_head,
  2309. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  2310. offload_func_kq(K);
  2311. ggml_set_name(K, "K");
  2312. // K * Q
  2313. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  2314. offload_func_kq(KQ);
  2315. ggml_set_name(KQ, "KQ");
  2316. // KQ_scaled = KQ / sqrt(n_embd_head)
  2317. // KQ_scaled shape [n_kv, n_tokens, n_head, 1]
  2318. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, KQ_scale);
  2319. offload_func_kq(KQ_scaled);
  2320. ggml_set_name(KQ_scaled, "KQ_scaled");
  2321. // KQ_masked = mask_past(KQ_scaled)
  2322. struct ggml_tensor * KQ_masked = ggml_add(ctx0, KQ_scaled, KQ_mask);
  2323. offload_func_kq(KQ_masked);
  2324. ggml_set_name(KQ_masked, "KQ_masked");
  2325. // KQ = soft_max(KQ_masked)
  2326. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  2327. offload_func_v(KQ_soft_max);
  2328. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  2329. // split cached V into n_head heads
  2330. struct ggml_tensor * V =
  2331. ggml_view_3d(ctx0, kv_self.v,
  2332. n_kv, n_embd_head, n_head_kv,
  2333. ggml_element_size(kv_self.v)*n_ctx,
  2334. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  2335. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  2336. offload_func_v(V);
  2337. ggml_set_name(V, "V");
  2338. #if 1
  2339. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  2340. offload_func_v(KQV);
  2341. ggml_set_name(KQV, "KQV");
  2342. #else
  2343. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  2344. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  2345. // is there a better way?
  2346. struct ggml_tensor * V_cont = ggml_cpy(ctx0, V, ggml_new_tensor_3d(ctx0, kv_self.v->type, n_ctx, n_embd_head, n_head));
  2347. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  2348. #endif
  2349. // KQV_merged = KQV.permute(0, 2, 1, 3)
  2350. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  2351. offload_func_v(KQV_merged);
  2352. ggml_set_name(KQV_merged, "KQV_merged");
  2353. // cur = KQV_merged.contiguous().view(n_embd, n_tokens)
  2354. cur = ggml_cont_2d(ctx0, KQV_merged, n_embd, n_tokens);
  2355. offload_func_v(cur);
  2356. ggml_set_name(cur, "KQV_merged_contiguous");
  2357. // projection (no bias)
  2358. cur = ggml_mul_mat(ctx0,
  2359. model.layers[il].wo,
  2360. cur);
  2361. offload_func(cur);
  2362. ggml_set_name(cur, "result_wo");
  2363. }
  2364. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  2365. offload_func(inpFF);
  2366. ggml_set_name(inpFF, "inpFF");
  2367. // feed-forward network
  2368. {
  2369. // norm
  2370. {
  2371. cur = ggml_rms_norm(ctx0, inpFF, norm_rms_eps);
  2372. offload_func(cur);
  2373. ggml_set_name(cur, "rms_norm_1");
  2374. // cur = cur*ffn_norm(broadcasted)
  2375. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  2376. offload_func(cur);
  2377. ggml_set_name(cur, "ffn_norm");
  2378. }
  2379. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  2380. model.layers[il].w3,
  2381. cur);
  2382. offload_func(tmp);
  2383. ggml_set_name(tmp, "result_w3");
  2384. cur = ggml_mul_mat(ctx0,
  2385. model.layers[il].w1,
  2386. cur);
  2387. offload_func(cur);
  2388. ggml_set_name(cur, "result_w1");
  2389. // SILU activation
  2390. cur = ggml_silu(ctx0, cur);
  2391. offload_func(cur);
  2392. ggml_set_name(cur, "silu");
  2393. cur = ggml_mul(ctx0, cur, tmp);
  2394. offload_func(cur);
  2395. ggml_set_name(cur, "silu_x_result_w3");
  2396. cur = ggml_mul_mat(ctx0,
  2397. model.layers[il].w2,
  2398. cur);
  2399. offload_func(cur);
  2400. ggml_set_name(cur, "result_w2");
  2401. }
  2402. cur = ggml_add(ctx0, cur, inpFF);
  2403. offload_func(cur);
  2404. ggml_set_name(cur, "inpFF_+_result_w2");
  2405. // input for next layer
  2406. inpL = cur;
  2407. }
  2408. cur = inpL;
  2409. // norm
  2410. {
  2411. cur = ggml_rms_norm(ctx0, cur, norm_rms_eps);
  2412. offload_func_nr(cur);
  2413. ggml_set_name(cur, "rms_norm_2");
  2414. // cur = cur*norm(broadcasted)
  2415. cur = ggml_mul(ctx0, cur, model.output_norm);
  2416. // offload_func_nr(cur); // TODO CPU + GPU mirrored backend
  2417. ggml_set_name(cur, "result_norm");
  2418. }
  2419. // lm_head
  2420. cur = ggml_mul_mat(ctx0, model.output, cur);
  2421. ggml_set_name(cur, "result_output");
  2422. ggml_build_forward_expand(gf, cur);
  2423. ggml_free(ctx0);
  2424. return gf;
  2425. }
  2426. static struct ggml_cgraph * llm_build_baichaun(
  2427. llama_context & lctx,
  2428. const llama_batch & batch) {
  2429. const auto & model = lctx.model;
  2430. const auto & hparams = model.hparams;
  2431. const auto & cparams = lctx.cparams;
  2432. const auto & kv_self = lctx.kv_self;
  2433. GGML_ASSERT(!!kv_self.ctx);
  2434. const int64_t n_embd = hparams.n_embd;
  2435. const int64_t n_layer = hparams.n_layer;
  2436. const int64_t n_ctx = cparams.n_ctx;
  2437. const int64_t n_head = hparams.n_head;
  2438. const int64_t n_head_kv = hparams.n_head_kv;
  2439. const int64_t n_embd_head = hparams.n_embd_head();
  2440. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2441. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2442. const float freq_base = cparams.rope_freq_base;
  2443. const float freq_scale = cparams.rope_freq_scale;
  2444. const float norm_rms_eps = hparams.f_norm_rms_eps;
  2445. const int n_gpu_layers = model.n_gpu_layers;
  2446. const int32_t n_tokens = batch.n_tokens;
  2447. const int32_t n_kv = ggml_allocr_is_measure(lctx.alloc) ? n_ctx : kv_self.n;
  2448. const int32_t kv_head = ggml_allocr_is_measure(lctx.alloc) ? n_ctx - n_tokens : kv_self.head;
  2449. const bool do_rope_shift = ggml_allocr_is_measure(lctx.alloc) || kv_self.has_shift;
  2450. auto & buf_compute = lctx.buf_compute;
  2451. struct ggml_init_params params = {
  2452. /*.mem_size =*/ buf_compute.size,
  2453. /*.mem_buffer =*/ buf_compute.data,
  2454. /*.no_alloc =*/ false,
  2455. };
  2456. params.no_alloc = true;
  2457. struct ggml_context * ctx0 = ggml_init(params);
  2458. ggml_cgraph * gf = ggml_new_graph(ctx0);
  2459. struct ggml_tensor * cur;
  2460. struct ggml_tensor * inpL;
  2461. if (batch.token) {
  2462. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  2463. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  2464. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2465. memcpy(inp_tokens->data, batch.token, n_tokens*ggml_element_size(inp_tokens));
  2466. }
  2467. ggml_set_name(inp_tokens, "inp_tokens");
  2468. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  2469. } else {
  2470. #ifdef GGML_USE_MPI
  2471. GGML_ASSERT(false && "not implemented");
  2472. #endif
  2473. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens);
  2474. ggml_allocr_alloc(lctx.alloc, inpL);
  2475. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2476. memcpy(inpL->data, batch.embd, n_tokens * n_embd * ggml_element_size(inpL));
  2477. }
  2478. }
  2479. const int i_gpu_start = n_layer - n_gpu_layers;
  2480. (void) i_gpu_start;
  2481. // offload functions set the tensor output backend to GPU
  2482. // tensors are GPU-accelerated if any input or the output has been offloaded
  2483. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  2484. offload_func_t offload_func_kq = llama_nop;
  2485. offload_func_t offload_func_v = llama_nop;
  2486. #ifdef GGML_USE_CUBLAS
  2487. if (n_gpu_layers > n_layer) {
  2488. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  2489. }
  2490. if (n_gpu_layers > n_layer + 1) {
  2491. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  2492. }
  2493. if (n_gpu_layers > n_layer + 2) {
  2494. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  2495. }
  2496. #endif // GGML_USE_CUBLAS
  2497. // KQ_scale
  2498. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  2499. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  2500. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  2501. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2502. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  2503. }
  2504. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2505. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  2506. offload_func_kq(KQ_mask);
  2507. ggml_set_name(KQ_mask, "KQ_mask");
  2508. ggml_allocr_alloc(lctx.alloc, KQ_mask);
  2509. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2510. float * data = (float *) KQ_mask->data;
  2511. memset(data, 0, ggml_nbytes(KQ_mask));
  2512. for (int h = 0; h < 1; ++h) {
  2513. for (int j = 0; j < n_tokens; ++j) {
  2514. const llama_pos pos = batch.pos[j];
  2515. const llama_seq_id seq_id = batch.seq_id[j];
  2516. for (int i = 0; i < n_kv; ++i) {
  2517. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  2518. data[h*(n_kv*n_tokens) + j*n_kv + i] = -INFINITY;
  2519. }
  2520. }
  2521. }
  2522. }
  2523. }
  2524. // KQ_pos - contains the positions
  2525. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  2526. offload_func_kq(KQ_pos);
  2527. ggml_set_name(KQ_pos, "KQ_pos");
  2528. ggml_allocr_alloc(lctx.alloc, KQ_pos);
  2529. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2530. int * data = (int *) KQ_pos->data;
  2531. for (int i = 0; i < n_tokens; ++i) {
  2532. data[i] = batch.pos[i];
  2533. }
  2534. }
  2535. // shift the entire K-cache if needed
  2536. if (do_rope_shift) {
  2537. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  2538. offload_func_kq(K_shift);
  2539. ggml_set_name(K_shift, "K_shift");
  2540. ggml_allocr_alloc(lctx.alloc, K_shift);
  2541. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2542. int * data = (int *) K_shift->data;
  2543. for (int i = 0; i < n_ctx; ++i) {
  2544. data[i] = kv_self.cells[i].delta;
  2545. }
  2546. }
  2547. for (int il = 0; il < n_layer; ++il) {
  2548. struct ggml_tensor * tmp =
  2549. ggml_rope_custom_inplace(ctx0,
  2550. ggml_view_3d(ctx0, kv_self.k,
  2551. n_embd_head, n_head_kv, n_ctx,
  2552. ggml_element_size(kv_self.k)*n_embd_head,
  2553. ggml_element_size(kv_self.k)*n_embd_gqa,
  2554. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il),
  2555. K_shift, n_embd_head, 0, 0, freq_base, freq_scale);
  2556. offload_func_kq(tmp);
  2557. ggml_build_forward_expand(gf, tmp);
  2558. }
  2559. }
  2560. for (int il = 0; il < n_layer; ++il) {
  2561. ggml_format_name(inpL, "layer_inp_%d", il);
  2562. offload_func_t offload_func = llama_nop;
  2563. #ifdef GGML_USE_CUBLAS
  2564. if (il >= i_gpu_start) {
  2565. offload_func = ggml_cuda_assign_buffers_no_alloc;
  2566. }
  2567. #endif // GGML_USE_CUBLAS
  2568. struct ggml_tensor * inpSA = inpL;
  2569. // norm
  2570. {
  2571. cur = ggml_rms_norm(ctx0, inpL, norm_rms_eps);
  2572. offload_func(cur);
  2573. ggml_set_name(cur, "rms_norm_0");
  2574. // cur = cur*attn_norm(broadcasted)
  2575. cur = ggml_mul(ctx0, cur, model.layers[il].attn_norm);
  2576. offload_func(cur);
  2577. ggml_set_name(cur, "attention_norm_0");
  2578. }
  2579. // self-attention
  2580. {
  2581. // compute Q and K and RoPE them
  2582. struct ggml_tensor * tmpk = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  2583. offload_func_kq(tmpk);
  2584. ggml_set_name(tmpk, "tmpk");
  2585. struct ggml_tensor * tmpq = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  2586. offload_func_kq(tmpq);
  2587. ggml_set_name(tmpq, "tmpq");
  2588. struct ggml_tensor * Kcur;
  2589. struct ggml_tensor * Qcur;
  2590. switch (model.type) {
  2591. case MODEL_7B:
  2592. Kcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), KQ_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  2593. Qcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), KQ_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  2594. break;
  2595. case MODEL_13B:
  2596. Kcur = ggml_reshape_3d(ctx0, tmpk, n_embd/n_head, n_head, n_tokens);
  2597. Qcur = ggml_reshape_3d(ctx0, tmpq, n_embd/n_head, n_head, n_tokens);
  2598. break;
  2599. default:
  2600. GGML_ASSERT(false);
  2601. }
  2602. offload_func_kq(Kcur);
  2603. ggml_set_name(Kcur, "Kcur");
  2604. offload_func_kq(Qcur);
  2605. ggml_set_name(Qcur, "Qcur");
  2606. // store key and value to memory
  2607. {
  2608. // compute the transposed [n_tokens, n_embd] V matrix
  2609. struct ggml_tensor * tmpv = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  2610. offload_func_v(tmpv);
  2611. ggml_set_name(tmpv, "tmpv");
  2612. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, tmpv, n_embd_gqa, n_tokens));
  2613. offload_func_v(Vcur);
  2614. ggml_set_name(Vcur, "Vcur");
  2615. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, n_tokens*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + kv_head));
  2616. offload_func_kq(k);
  2617. ggml_set_name(k, "k");
  2618. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, n_tokens, n_embd_gqa,
  2619. ( n_ctx)*ggml_element_size(kv_self.v),
  2620. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + kv_head*ggml_element_size(kv_self.v));
  2621. offload_func_v(v);
  2622. ggml_set_name(v, "v");
  2623. // important: storing RoPE-ed version of K in the KV cache!
  2624. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  2625. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  2626. }
  2627. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  2628. offload_func_kq(Q);
  2629. ggml_set_name(Q, "Q");
  2630. struct ggml_tensor * K =
  2631. ggml_view_3d(ctx0, kv_self.k,
  2632. n_embd_head, n_kv, n_head_kv,
  2633. ggml_element_size(kv_self.k)*n_embd_gqa,
  2634. ggml_element_size(kv_self.k)*n_embd_head,
  2635. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  2636. offload_func_kq(K);
  2637. ggml_set_name(K, "K");
  2638. // K * Q
  2639. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  2640. offload_func_kq(KQ);
  2641. ggml_set_name(KQ, "KQ");
  2642. // KQ_scaled = KQ / sqrt(n_embd_head)
  2643. // KQ_scaled shape [n_past + n_tokens, n_tokens, n_head, 1]
  2644. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, KQ_scale);
  2645. offload_func_kq(KQ_scaled);
  2646. ggml_set_name(KQ_scaled, "KQ_scaled");
  2647. struct ggml_tensor * KQ_masked;
  2648. struct ggml_tensor * KQ_scaled_alibi;
  2649. switch (model.type) {
  2650. case MODEL_7B:
  2651. KQ_masked = ggml_add(ctx0, KQ_scaled, KQ_mask);
  2652. break;
  2653. case MODEL_13B:
  2654. // TODO: replace with ggml_add()
  2655. KQ_scaled_alibi = ggml_alibi(ctx0, KQ_scaled, /*n_past*/ 0, n_head, 8);
  2656. ggml_set_name(KQ_scaled_alibi, "KQ_scaled_alibi");
  2657. KQ_masked = ggml_add(ctx0, KQ_scaled_alibi, KQ_mask);
  2658. break;
  2659. default:
  2660. GGML_ASSERT(false);
  2661. }
  2662. // KQ = soft_max(KQ_masked)
  2663. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  2664. offload_func_v(KQ_soft_max);
  2665. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  2666. // split cached V into n_head heads
  2667. struct ggml_tensor * V =
  2668. ggml_view_3d(ctx0, kv_self.v,
  2669. n_kv, n_embd_head, n_head_kv,
  2670. ggml_element_size(kv_self.v)*n_ctx,
  2671. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  2672. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  2673. offload_func_v(V);
  2674. ggml_set_name(V, "V");
  2675. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  2676. offload_func_v(KQV);
  2677. ggml_set_name(KQV, "KQV");
  2678. // KQV_merged = KQV.permute(0, 2, 1, 3)
  2679. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  2680. offload_func_v(KQV_merged);
  2681. ggml_set_name(KQV_merged, "KQV_merged");
  2682. // cur = KQV_merged.contiguous().view(n_embd, n_tokens)
  2683. cur = ggml_cont_2d(ctx0, KQV_merged, n_embd, n_tokens);
  2684. offload_func_v(cur);
  2685. ggml_set_name(cur, "KQV_merged_contiguous");
  2686. // projection (no bias)
  2687. cur = ggml_mul_mat(ctx0,
  2688. model.layers[il].wo,
  2689. cur);
  2690. offload_func(cur);
  2691. ggml_set_name(cur, "result_wo");
  2692. }
  2693. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  2694. offload_func(inpFF);
  2695. ggml_set_name(inpFF, "inpFF");
  2696. // feed-forward network
  2697. {
  2698. // norm
  2699. {
  2700. cur = ggml_rms_norm(ctx0, inpFF, norm_rms_eps);
  2701. offload_func(cur);
  2702. ggml_set_name(cur, "rms_norm_1");
  2703. // cur = cur*ffn_norm(broadcasted)
  2704. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  2705. offload_func(cur);
  2706. ggml_set_name(cur, "ffn_norm");
  2707. }
  2708. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  2709. model.layers[il].w3,
  2710. cur);
  2711. offload_func(tmp);
  2712. ggml_set_name(tmp, "result_w3");
  2713. cur = ggml_mul_mat(ctx0,
  2714. model.layers[il].w1,
  2715. cur);
  2716. offload_func(cur);
  2717. ggml_set_name(cur, "result_w1");
  2718. // SILU activation
  2719. cur = ggml_silu(ctx0, cur);
  2720. offload_func(cur);
  2721. ggml_set_name(cur, "silu");
  2722. cur = ggml_mul(ctx0, cur, tmp);
  2723. offload_func(cur);
  2724. ggml_set_name(cur, "silu_x_result_w3");
  2725. cur = ggml_mul_mat(ctx0,
  2726. model.layers[il].w2,
  2727. cur);
  2728. offload_func(cur);
  2729. ggml_set_name(cur, "result_w2");
  2730. }
  2731. cur = ggml_add(ctx0, cur, inpFF);
  2732. offload_func(cur);
  2733. ggml_set_name(cur, "inpFF_+_result_w2");
  2734. // input for next layer
  2735. inpL = cur;
  2736. }
  2737. cur = inpL;
  2738. // norm
  2739. {
  2740. cur = ggml_rms_norm(ctx0, cur, norm_rms_eps);
  2741. offload_func_nr(cur);
  2742. ggml_set_name(cur, "rms_norm_2");
  2743. // cur = cur*norm(broadcasted)
  2744. cur = ggml_mul(ctx0, cur, model.output_norm);
  2745. // offload_func_nr(cur); // TODO CPU + GPU mirrored backend
  2746. ggml_set_name(cur, "result_norm");
  2747. }
  2748. // lm_head
  2749. cur = ggml_mul_mat(ctx0, model.output, cur);
  2750. ggml_set_name(cur, "result_output");
  2751. ggml_build_forward_expand(gf, cur);
  2752. ggml_free(ctx0);
  2753. return gf;
  2754. }
  2755. static struct ggml_cgraph * llm_build_falcon(
  2756. llama_context & lctx,
  2757. const llama_batch & batch) {
  2758. const auto & model = lctx.model;
  2759. const auto & hparams = model.hparams;
  2760. const auto & cparams = lctx.cparams;
  2761. const auto & kv_self = lctx.kv_self;
  2762. GGML_ASSERT(!!kv_self.ctx);
  2763. const int64_t n_embd = hparams.n_embd;
  2764. const int64_t n_layer = hparams.n_layer;
  2765. const int64_t n_ctx = cparams.n_ctx;
  2766. const int64_t n_head = hparams.n_head;
  2767. const int64_t n_head_kv = hparams.n_head_kv;
  2768. const int64_t n_embd_head = hparams.n_embd_head();
  2769. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2770. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2771. const float freq_base = cparams.rope_freq_base;
  2772. const float freq_scale = cparams.rope_freq_scale;
  2773. const float norm_eps = hparams.f_norm_eps;
  2774. const int n_gpu_layers = model.n_gpu_layers;
  2775. const int32_t n_tokens = batch.n_tokens;
  2776. const int32_t n_kv = ggml_allocr_is_measure(lctx.alloc) ? n_ctx : kv_self.n;
  2777. const int32_t kv_head = ggml_allocr_is_measure(lctx.alloc) ? n_ctx - n_tokens : kv_self.head;
  2778. const bool do_rope_shift = ggml_allocr_is_measure(lctx.alloc) || kv_self.has_shift;
  2779. //printf("kv_head = %d, n_kv = %d, n_tokens = %d, n_ctx = %d, is_measure = %d, has_shift = %d\n",
  2780. // kv_head, n_kv, n_tokens, n_ctx, ggml_allocr_is_measure(lctx.alloc), kv_self.has_shift);
  2781. auto & buf_compute = lctx.buf_compute;
  2782. struct ggml_init_params params = {
  2783. /*.mem_size =*/ buf_compute.size,
  2784. /*.mem_buffer =*/ buf_compute.data,
  2785. /*.no_alloc =*/ false,
  2786. };
  2787. params.no_alloc = true;
  2788. struct ggml_context * ctx0 = ggml_init(params);
  2789. ggml_cgraph * gf = ggml_new_graph(ctx0);
  2790. struct ggml_tensor * cur;
  2791. struct ggml_tensor * inpL;
  2792. if (batch.token) {
  2793. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  2794. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  2795. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2796. memcpy(inp_tokens->data, batch.token, n_tokens*ggml_element_size(inp_tokens));
  2797. }
  2798. ggml_set_name(inp_tokens, "inp_tokens");
  2799. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  2800. } else {
  2801. #ifdef GGML_USE_MPI
  2802. GGML_ASSERT(false && "not implemented");
  2803. #endif
  2804. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens);
  2805. ggml_allocr_alloc(lctx.alloc, inpL);
  2806. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2807. memcpy(inpL->data, batch.embd, n_tokens * n_embd * ggml_element_size(inpL));
  2808. }
  2809. }
  2810. const int i_gpu_start = n_layer - n_gpu_layers;
  2811. (void) i_gpu_start;
  2812. // offload functions set the tensor output backend to GPU
  2813. // tensors are GPU-accelerated if any input or the output has been offloaded
  2814. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  2815. offload_func_t offload_func_kq = llama_nop;
  2816. offload_func_t offload_func_v = llama_nop;
  2817. #ifdef GGML_USE_CUBLAS
  2818. if (n_gpu_layers > n_layer) {
  2819. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  2820. }
  2821. if (n_gpu_layers > n_layer + 1) {
  2822. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  2823. }
  2824. if (n_gpu_layers > n_layer + 2) {
  2825. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  2826. }
  2827. #endif // GGML_USE_CUBLAS
  2828. // KQ_scale
  2829. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  2830. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  2831. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  2832. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2833. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  2834. }
  2835. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2836. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  2837. offload_func_kq(KQ_mask);
  2838. ggml_set_name(KQ_mask, "KQ_mask");
  2839. ggml_allocr_alloc(lctx.alloc, KQ_mask);
  2840. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2841. float * data = (float *) KQ_mask->data;
  2842. memset(data, 0, ggml_nbytes(KQ_mask));
  2843. for (int h = 0; h < 1; ++h) {
  2844. for (int j = 0; j < n_tokens; ++j) {
  2845. const llama_pos pos = batch.pos[j];
  2846. const llama_seq_id seq_id = batch.seq_id[j];
  2847. for (int i = 0; i < n_kv; ++i) {
  2848. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  2849. data[h*(n_kv*n_tokens) + j*n_kv + i] = -INFINITY;
  2850. }
  2851. }
  2852. }
  2853. }
  2854. }
  2855. // KQ_pos - contains the positions
  2856. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  2857. offload_func_kq(KQ_pos);
  2858. ggml_set_name(KQ_pos, "KQ_pos");
  2859. ggml_allocr_alloc(lctx.alloc, KQ_pos);
  2860. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2861. int * data = (int *) KQ_pos->data;
  2862. for (int i = 0; i < n_tokens; ++i) {
  2863. data[i] = batch.pos[i];
  2864. }
  2865. }
  2866. // shift the entire K-cache if needed
  2867. if (do_rope_shift) {
  2868. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  2869. offload_func_kq(K_shift);
  2870. ggml_set_name(K_shift, "K_shift");
  2871. ggml_allocr_alloc(lctx.alloc, K_shift);
  2872. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2873. int * data = (int *) K_shift->data;
  2874. for (int i = 0; i < n_ctx; ++i) {
  2875. data[i] = kv_self.cells[i].delta;
  2876. }
  2877. }
  2878. for (int il = 0; il < n_layer; ++il) {
  2879. struct ggml_tensor * tmp =
  2880. ggml_rope_custom_inplace(ctx0,
  2881. ggml_view_3d(ctx0, kv_self.k,
  2882. n_embd_head, n_head_kv, n_ctx,
  2883. ggml_element_size(kv_self.k)*n_embd_head,
  2884. ggml_element_size(kv_self.k)*n_embd_gqa,
  2885. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il),
  2886. K_shift, n_embd_head, 2, 0, freq_base, freq_scale);
  2887. offload_func_kq(tmp);
  2888. ggml_build_forward_expand(gf, tmp);
  2889. }
  2890. }
  2891. for (int il = 0; il < n_layer; ++il) {
  2892. struct ggml_tensor * attn_norm;
  2893. offload_func_t offload_func = llama_nop;
  2894. #ifdef GGML_USE_CUBLAS
  2895. if (il >= i_gpu_start) {
  2896. offload_func = ggml_cuda_assign_buffers_no_alloc;
  2897. }
  2898. #endif // GGML_USE_CUBLAS
  2899. // self-attention
  2900. // TODO: refactor into common function (shared with LLaMA)
  2901. {
  2902. attn_norm = ggml_norm(ctx0, inpL, norm_eps);
  2903. offload_func(attn_norm);
  2904. attn_norm = ggml_add(ctx0,
  2905. ggml_mul(ctx0, attn_norm, model.layers[il].attn_norm),
  2906. model.layers[il].attn_norm_b);
  2907. offload_func(attn_norm->src[0]);
  2908. offload_func(attn_norm);
  2909. if (model.layers[il].attn_norm_2) { // Falcon-40B
  2910. cur = ggml_norm(ctx0, inpL, norm_eps);
  2911. offload_func(cur);
  2912. cur = ggml_add(ctx0,
  2913. ggml_mul(ctx0, cur, model.layers[il].attn_norm_2),
  2914. model.layers[il].attn_norm_2_b);
  2915. offload_func(cur->src[0]);
  2916. offload_func(cur);
  2917. } else { // Falcon 7B
  2918. cur = attn_norm;
  2919. }
  2920. // compute QKV
  2921. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  2922. offload_func_kq(cur);
  2923. // Note that the strides for Kcur, Vcur are set up so that the
  2924. // resulting views are misaligned with the tensor's storage
  2925. // (by applying the K/V offset we shift the tensor's original
  2926. // view to stick out behind the viewed QKV tensor's allocated
  2927. // memory, so to say). This is ok because no actual accesses
  2928. // happen to that out-of-range memory, but it can require some
  2929. // trickery when trying to accurately dump these views for
  2930. // debugging.
  2931. const size_t wsize = ggml_type_size(cur->type);
  2932. // TODO: these 2 ggml_conts are technically not needed, but we add them until CUDA support for
  2933. // non-contiguous views is added for the rope operator
  2934. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_3d(
  2935. ctx0, cur, n_embd_head, n_head, n_tokens,
  2936. wsize * n_embd_head,
  2937. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2938. 0));
  2939. offload_func_kq(tmpq);
  2940. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_3d(
  2941. ctx0, cur, n_embd_head, n_head_kv, n_tokens,
  2942. wsize * n_embd_head,
  2943. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2944. wsize * n_embd_head * n_head));
  2945. offload_func_kq(tmpk);
  2946. struct ggml_tensor * tmpv = ggml_view_3d(
  2947. ctx0, cur, n_embd_head, n_head_kv, n_tokens,
  2948. wsize * n_embd_head,
  2949. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2950. wsize * n_embd_head * (n_head + n_head_kv));
  2951. offload_func_v(tmpv);
  2952. // using mode = 2 for neox mode
  2953. struct ggml_tensor * Qcur = ggml_rope_custom(ctx0, tmpq, KQ_pos, n_embd_head, 2, 0, freq_base, freq_scale);
  2954. offload_func_kq(Qcur);
  2955. struct ggml_tensor * Kcur = ggml_rope_custom(ctx0, tmpk, KQ_pos, n_embd_head, 2, 0, freq_base, freq_scale);
  2956. offload_func_kq(Kcur);
  2957. {
  2958. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_cont(ctx0, tmpv), n_embd_gqa, n_tokens));
  2959. offload_func_v(Vcur);
  2960. offload_func_v(Vcur->src[0]->src[0]);
  2961. ggml_set_name(Vcur, "Vcur");
  2962. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, n_tokens*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + kv_head));
  2963. offload_func_kq(k);
  2964. ggml_set_name(k, "k");
  2965. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, n_tokens, n_embd_gqa,
  2966. ( n_ctx)*ggml_element_size(kv_self.v),
  2967. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + kv_head*ggml_element_size(kv_self.v));
  2968. offload_func_v(v);
  2969. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  2970. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  2971. }
  2972. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  2973. offload_func_kq(Q);
  2974. ggml_set_name(Q, "Q");
  2975. struct ggml_tensor * K =
  2976. ggml_view_3d(ctx0, kv_self.k,
  2977. n_embd_head, n_kv, n_head_kv,
  2978. ggml_element_size(kv_self.k)*n_embd_gqa,
  2979. ggml_element_size(kv_self.k)*n_embd_head,
  2980. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  2981. offload_func_kq(K);
  2982. ggml_set_name(K, "K");
  2983. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  2984. offload_func_kq(KQ);
  2985. ggml_set_name(KQ, "KQ");
  2986. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, KQ_scale);
  2987. offload_func_kq(KQ_scaled);
  2988. ggml_set_name(KQ_scaled, "KQ_scaled");
  2989. struct ggml_tensor * KQ_masked = ggml_add(ctx0, KQ_scaled, KQ_mask);
  2990. offload_func_kq(KQ_masked);
  2991. ggml_set_name(KQ_masked, "KQ_masked");
  2992. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  2993. offload_func_v(KQ_soft_max);
  2994. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  2995. struct ggml_tensor * V =
  2996. ggml_view_3d(ctx0, kv_self.v,
  2997. n_kv, n_embd_head, n_head_kv,
  2998. ggml_element_size(kv_self.v)*n_ctx,
  2999. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  3000. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  3001. offload_func_v(V);
  3002. ggml_set_name(V, "V");
  3003. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  3004. offload_func_v(KQV);
  3005. ggml_set_name(KQV, "KQV");
  3006. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  3007. offload_func_v(KQV_merged);
  3008. ggml_set_name(KQV_merged, "KQV_merged");
  3009. cur = ggml_cont_2d(ctx0, KQV_merged, n_embd, n_tokens);
  3010. offload_func_v(cur);
  3011. ggml_set_name(cur, "KQV_merged_contiguous");
  3012. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  3013. offload_func(cur);
  3014. ggml_set_name(cur, "result_wo");
  3015. }
  3016. struct ggml_tensor * attn_out = cur;
  3017. // feed forward
  3018. {
  3019. struct ggml_tensor * inpFF = attn_norm;
  3020. cur = ggml_mul_mat(ctx0, model.layers[il].w3, inpFF);
  3021. offload_func(cur);
  3022. cur = ggml_gelu(ctx0, cur);
  3023. offload_func(cur);
  3024. cur = ggml_mul_mat(ctx0, model.layers[il].w2, cur);
  3025. offload_func(cur);
  3026. }
  3027. cur = ggml_add(ctx0, cur, attn_out);
  3028. offload_func(cur);
  3029. cur = ggml_add(ctx0, cur, inpL);
  3030. offload_func(cur);
  3031. // input for next layer
  3032. inpL = cur;
  3033. }
  3034. cur = inpL;
  3035. // norm
  3036. {
  3037. cur = ggml_norm(ctx0, cur, norm_eps);
  3038. offload_func_nr(cur);
  3039. cur = ggml_add(ctx0,
  3040. ggml_mul(ctx0, cur, model.output_norm),
  3041. model.output_norm_b);
  3042. ggml_set_name(cur, "result_norm");
  3043. }
  3044. cur = ggml_mul_mat(ctx0, model.output, cur);
  3045. ggml_set_name(cur, "result_output");
  3046. ggml_build_forward_expand(gf, cur);
  3047. ggml_free(ctx0);
  3048. return gf;
  3049. }
  3050. static struct ggml_cgraph * llm_build_starcoder(
  3051. llama_context & lctx,
  3052. const llama_batch & batch) {
  3053. const auto & model = lctx.model;
  3054. const auto & hparams = model.hparams;
  3055. const auto & cparams = lctx.cparams;
  3056. const auto & kv_self = lctx.kv_self;
  3057. GGML_ASSERT(!!kv_self.ctx);
  3058. const int64_t n_embd = hparams.n_embd;
  3059. const int64_t n_layer = hparams.n_layer;
  3060. const int64_t n_ctx = cparams.n_ctx;
  3061. const int64_t n_head = hparams.n_head;
  3062. const int64_t n_head_kv = hparams.n_head_kv;
  3063. const int64_t n_embd_head = hparams.n_embd_head();
  3064. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3065. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3066. const float norm_eps = hparams.f_norm_eps;
  3067. const int32_t n_tokens = batch.n_tokens;
  3068. const int32_t n_kv = ggml_allocr_is_measure(lctx.alloc) ? n_ctx : kv_self.n;
  3069. const int32_t kv_head = ggml_allocr_is_measure(lctx.alloc) ? n_ctx - n_tokens : kv_self.head;
  3070. auto & buf_compute = lctx.buf_compute;
  3071. struct ggml_init_params params = {
  3072. /*.mem_size =*/ buf_compute.size,
  3073. /*.mem_buffer =*/ buf_compute.data,
  3074. /*.no_alloc =*/ false,
  3075. };
  3076. params.no_alloc = true;
  3077. struct ggml_context * ctx0 = ggml_init(params);
  3078. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3079. struct ggml_tensor * cur;
  3080. struct ggml_tensor * token;
  3081. struct ggml_tensor * position;
  3082. struct ggml_tensor * inpL;
  3083. if (batch.token) {
  3084. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3085. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  3086. if (!ggml_allocr_is_measure(lctx.alloc)) {
  3087. memcpy(inp_tokens->data, batch.token, n_tokens*ggml_element_size(inp_tokens));
  3088. }
  3089. ggml_set_name(inp_tokens, "inp_tokens");
  3090. token = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  3091. } else {
  3092. #ifdef GGML_USE_MPI
  3093. GGML_ASSERT(false && "not implemented");
  3094. #endif
  3095. token = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_tokens);
  3096. ggml_allocr_alloc(lctx.alloc, token);
  3097. if (!ggml_allocr_is_measure(lctx.alloc)) {
  3098. memcpy(token->data, batch.embd, n_tokens * n_embd * ggml_element_size(token));
  3099. }
  3100. }
  3101. {
  3102. // Compute position embeddings.
  3103. struct ggml_tensor * inp_positions = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3104. ggml_allocr_alloc(lctx.alloc, inp_positions);
  3105. if (!ggml_allocr_is_measure(lctx.alloc)) {
  3106. for (int i = 0; i < n_tokens; ++i) {
  3107. ((int32_t *) inp_positions->data)[i] = batch.pos[i];
  3108. }
  3109. }
  3110. ggml_set_name(inp_positions, "inp_positions");
  3111. position = ggml_get_rows(ctx0, model.pos_embeddings, inp_positions);
  3112. }
  3113. // KQ_scale
  3114. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3115. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  3116. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  3117. if (!ggml_allocr_is_measure(lctx.alloc)) {
  3118. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  3119. }
  3120. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3121. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3122. ggml_set_name(KQ_mask, "KQ_mask");
  3123. ggml_allocr_alloc(lctx.alloc, KQ_mask);
  3124. if (!ggml_allocr_is_measure(lctx.alloc)) {
  3125. float * data = (float *) KQ_mask->data;
  3126. memset(data, 0, ggml_nbytes(KQ_mask));
  3127. for (int h = 0; h < 1; ++h) {
  3128. for (int j = 0; j < n_tokens; ++j) {
  3129. const llama_pos pos = batch.pos[j];
  3130. const llama_seq_id seq_id = batch.seq_id[j];
  3131. for (int i = 0; i < n_kv; ++i) {
  3132. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  3133. data[h*(n_kv*n_tokens) + j*n_kv + i] = -INFINITY;
  3134. }
  3135. }
  3136. }
  3137. }
  3138. }
  3139. inpL = ggml_add(ctx0, token, position);
  3140. ggml_set_name(inpL, "inpL");
  3141. for (int il = 0; il < n_layer; ++il) {
  3142. {
  3143. // Norm
  3144. cur = ggml_norm(ctx0, inpL, norm_eps);
  3145. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].attn_norm), model.layers[il].attn_norm_b);
  3146. }
  3147. {
  3148. // Self Attention
  3149. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wqkv, cur), model.layers[il].bqkv);
  3150. struct ggml_tensor * tmpq = ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*n_embd);
  3151. struct ggml_tensor * tmpk = ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], sizeof(float)*n_embd);
  3152. struct ggml_tensor * tmpv = ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], sizeof(float)*(n_embd + n_embd_gqa));
  3153. struct ggml_tensor * Qcur = tmpq;
  3154. struct ggml_tensor * Kcur = tmpk;
  3155. {
  3156. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_cont(ctx0, tmpv), n_embd_gqa, n_tokens));
  3157. ggml_set_name(Vcur, "Vcur");
  3158. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, n_tokens*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + kv_head));
  3159. ggml_set_name(k, "k");
  3160. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, n_tokens, n_embd_gqa,
  3161. ( n_ctx)*ggml_element_size(kv_self.v),
  3162. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + kv_head*ggml_element_size(kv_self.v));
  3163. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  3164. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  3165. }
  3166. struct ggml_tensor * Q =
  3167. ggml_permute(ctx0,
  3168. ggml_cpy(ctx0,
  3169. Qcur,
  3170. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd_head, n_head, n_tokens)),
  3171. 0, 2, 1, 3);
  3172. ggml_set_name(Q, "Q");
  3173. struct ggml_tensor * K =
  3174. ggml_view_3d(ctx0, kv_self.k,
  3175. n_embd_head, n_kv, n_head_kv,
  3176. ggml_element_size(kv_self.k)*n_embd_gqa,
  3177. ggml_element_size(kv_self.k)*n_embd_head,
  3178. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  3179. ggml_set_name(K, "K");
  3180. // K * Q
  3181. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  3182. ggml_set_name(KQ, "KQ");
  3183. // KQ_scaled = KQ / sqrt(n_embd_head)
  3184. // KQ_scaled shape [n_past + n_tokens, n_tokens, n_head, 1]
  3185. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  3186. ggml_set_name(KQ_scaled, "KQ_scaled");
  3187. // KQ_masked = mask_past(KQ_scaled)
  3188. struct ggml_tensor * KQ_masked = ggml_add(ctx0, KQ_scaled, KQ_mask);
  3189. ggml_set_name(KQ_masked, "KQ_masked");
  3190. // KQ = soft_max(KQ_masked)
  3191. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  3192. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  3193. // split cached V into n_head heads
  3194. struct ggml_tensor * V =
  3195. ggml_view_3d(ctx0, kv_self.v,
  3196. n_kv, n_embd_head, n_head_kv,
  3197. ggml_element_size(kv_self.v)*n_ctx,
  3198. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  3199. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  3200. ggml_set_name(V, "V");
  3201. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  3202. ggml_set_name(KQV, "KQV");
  3203. // KQV_merged = KQV.permute(0, 2, 1, 3)
  3204. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  3205. ggml_set_name(KQV_merged, "KQV_merged");
  3206. // cur = KQV_merged.contiguous().view(n_embd, n_tokens)
  3207. cur = ggml_cont_2d(ctx0, KQV_merged, n_embd, n_tokens);
  3208. ggml_set_name(cur, "KQV_merged_contiguous");
  3209. }
  3210. // Projection
  3211. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wo, cur), model.layers[il].bo);
  3212. // Add the input
  3213. cur = ggml_add(ctx0, cur, inpL);
  3214. struct ggml_tensor * inpFF = cur;
  3215. // FF
  3216. {
  3217. // Norm
  3218. {
  3219. cur = ggml_norm(ctx0, inpFF, norm_eps);
  3220. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.layers[il].ffn_norm), model.layers[il].ffn_norm_b);
  3221. }
  3222. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].w3, cur), model.layers[il].b3);
  3223. // GELU activation
  3224. cur = ggml_gelu(ctx0, cur);
  3225. // Projection
  3226. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].w2, cur), model.layers[il].b2);
  3227. }
  3228. inpL = ggml_add(ctx0, cur, inpFF);
  3229. }
  3230. // Output Norm
  3231. {
  3232. cur = ggml_norm(ctx0, inpL, norm_eps);
  3233. cur = ggml_add(ctx0, ggml_mul(ctx0, cur, model.output_norm), model.output_norm_b);
  3234. }
  3235. ggml_set_name(cur, "result_norm");
  3236. cur = ggml_mul_mat(ctx0, model.output, cur);
  3237. ggml_set_name(cur, "result_output");
  3238. ggml_build_forward_expand(gf, cur);
  3239. ggml_free(ctx0);
  3240. return gf;
  3241. }
  3242. static struct ggml_cgraph * llama_build_graph(
  3243. llama_context & lctx,
  3244. const llama_batch & batch) {
  3245. const auto & model = lctx.model;
  3246. struct ggml_cgraph * result = NULL;
  3247. switch (model.arch) {
  3248. case LLM_ARCH_LLAMA:
  3249. {
  3250. result = llm_build_llama(lctx, batch);
  3251. } break;
  3252. case LLM_ARCH_BAICHUAN:
  3253. {
  3254. result = llm_build_baichaun(lctx, batch);
  3255. } break;
  3256. case LLM_ARCH_FALCON:
  3257. {
  3258. result = llm_build_falcon(lctx, batch);
  3259. } break;
  3260. case LLM_ARCH_STARCODER:
  3261. {
  3262. result = llm_build_starcoder(lctx, batch);
  3263. } break;
  3264. default:
  3265. GGML_ASSERT(false);
  3266. }
  3267. return result;
  3268. }
  3269. // decode a batch of tokens by evaluating the transformer
  3270. //
  3271. // - lctx: llama context
  3272. // - batch: batch to evaluate
  3273. // - n_threads: number of threads to use
  3274. //
  3275. // return 0 on success
  3276. // return positive int on warning
  3277. // return negative int on error
  3278. //
  3279. static int llama_decode_internal(
  3280. llama_context & lctx,
  3281. llama_batch batch) {
  3282. const uint32_t n_tokens = batch.n_tokens;
  3283. if (n_tokens == 0) {
  3284. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  3285. return -1;
  3286. }
  3287. const auto & model = lctx.model;
  3288. const auto & hparams = model.hparams;
  3289. const auto & cparams = lctx.cparams;
  3290. const auto n_batch = cparams.n_batch;
  3291. GGML_ASSERT(n_tokens <= n_batch);
  3292. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  3293. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  3294. const int64_t t_start_us = ggml_time_us();
  3295. #ifdef GGML_USE_MPI
  3296. // TODO: needs fix after #3228
  3297. GGML_ASSERT(false && "not implemented");
  3298. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  3299. #endif
  3300. GGML_ASSERT(n_threads > 0);
  3301. auto & kv_self = lctx.kv_self;
  3302. GGML_ASSERT(!!kv_self.ctx);
  3303. const int64_t n_embd = hparams.n_embd;
  3304. const int64_t n_vocab = hparams.n_vocab;
  3305. // helpers for smoother batch API transistion
  3306. // after deprecating the llama_eval calls, these will be removed
  3307. std::vector<llama_pos> pos;
  3308. std::vector<llama_seq_id> seq_id;
  3309. if (batch.pos == nullptr) {
  3310. pos.resize(n_tokens);
  3311. for (uint32_t i = 0; i < n_tokens; i++) {
  3312. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  3313. }
  3314. batch.pos = pos.data();
  3315. }
  3316. if (batch.seq_id == nullptr) {
  3317. seq_id.resize(n_tokens);
  3318. for (uint32_t i = 0; i < n_tokens; i++) {
  3319. seq_id[i] = batch.all_seq_id;
  3320. }
  3321. batch.seq_id = seq_id.data();
  3322. }
  3323. // we always start to search for a free slot from the start of the cache
  3324. // TODO: better strategies can be implemented
  3325. kv_self.head = 0;
  3326. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  3327. return 1;
  3328. }
  3329. // a heuristic, to avoid attending the full cache if it is not yet utilized
  3330. // after enough generations, the benefit from this heuristic disappears
  3331. // if we start defragmenting the cache, the benefit from this will be more important
  3332. //kv_self.n = std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)); // TODO: this might be better for CUDA?
  3333. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, llama_kv_cache_cell_max(kv_self)));
  3334. //printf("kv_self.n = %d\n", kv_self.n);
  3335. ggml_allocr_reset(lctx.alloc);
  3336. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  3337. ggml_allocr_alloc_graph(lctx.alloc, gf);
  3338. #ifdef GGML_USE_CUBLAS
  3339. for (int i = 0; i < gf->n_leafs; i++) {
  3340. ggml_tensor * node = gf->leafs[i];
  3341. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  3342. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  3343. ggml_cuda_copy_to_device(node);
  3344. }
  3345. }
  3346. for (int i = 0; i < gf->n_nodes; i++) {
  3347. ggml_tensor * node = gf->nodes[i];
  3348. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  3349. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  3350. }
  3351. }
  3352. ggml_cuda_set_mul_mat_q(cparams.mul_mat_q);
  3353. #endif
  3354. // LLAMA_LOG_INFO("graph build time: %.3f ms (%d nodes, %d leafs)\n", (ggml_time_us() - t_start_us)/1000.0, gf->n_nodes, gf->n_leafs);
  3355. // for big prompts, if BLAS is enabled, it is better to use only one thread
  3356. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  3357. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  3358. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  3359. // with the BLAS calls. need a better solution
  3360. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  3361. n_threads = std::min(4, n_threads);
  3362. }
  3363. // If all tensors can be run on the GPU then using more than 1 thread is detrimental.
  3364. const bool full_offload_supported = model.arch == LLM_ARCH_LLAMA ||
  3365. model.arch == LLM_ARCH_BAICHUAN ||
  3366. model.arch == LLM_ARCH_FALCON;
  3367. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 3;
  3368. if (ggml_cpu_has_cublas() && full_offload_supported && fully_offloaded) {
  3369. n_threads = 1;
  3370. }
  3371. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  3372. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  3373. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  3374. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  3375. #if GGML_USE_MPI
  3376. const int64_t n_layer = hparams.n_layer;
  3377. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  3378. #endif
  3379. #ifdef GGML_USE_METAL
  3380. if (lctx.ctx_metal) {
  3381. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  3382. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  3383. } else {
  3384. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  3385. }
  3386. #else
  3387. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  3388. #endif
  3389. #if GGML_USE_MPI
  3390. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  3391. #endif
  3392. // update the kv ring buffer
  3393. lctx.kv_self.head += n_tokens;
  3394. lctx.kv_self.has_shift = false;
  3395. #ifdef GGML_PERF
  3396. // print timing information per ggml operation (for debugging purposes)
  3397. // requires GGML_PERF to be defined
  3398. ggml_graph_print(gf);
  3399. #endif
  3400. // plot the computation graph in dot format (for debugging purposes)
  3401. //if (n_past%100 == 0) {
  3402. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  3403. //}
  3404. // extract logits
  3405. {
  3406. auto & logits_out = lctx.logits;
  3407. if (batch.logits) {
  3408. logits_out.resize(n_vocab * n_tokens);
  3409. for (uint32_t i = 0; i < n_tokens; i++) {
  3410. if (batch.logits[i] == 0) {
  3411. continue;
  3412. }
  3413. memcpy(logits_out.data() + (n_vocab*i), (float *) ggml_get_data(res) + (n_vocab*i), sizeof(float)*n_vocab);
  3414. }
  3415. } else if (lctx.logits_all) {
  3416. logits_out.resize(n_vocab * n_tokens);
  3417. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*n_tokens);
  3418. } else {
  3419. logits_out.resize(n_vocab);
  3420. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(n_tokens - 1)), sizeof(float)*n_vocab);
  3421. }
  3422. }
  3423. // extract embeddings
  3424. if (!lctx.embedding.empty()) {
  3425. auto & embedding_out = lctx.embedding;
  3426. embedding_out.resize(n_embd);
  3427. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(n_tokens - 1)), sizeof(float)*n_embd);
  3428. }
  3429. // measure the performance only for the single-token evals
  3430. if (n_tokens == 1) {
  3431. lctx.t_eval_us += ggml_time_us() - t_start_us;
  3432. lctx.n_eval++;
  3433. }
  3434. else if (n_tokens > 1) {
  3435. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  3436. lctx.n_p_eval += n_tokens;
  3437. }
  3438. // get a more accurate load time, upon first eval
  3439. // TODO: fix this
  3440. if (!lctx.has_evaluated_once) {
  3441. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  3442. lctx.has_evaluated_once = true;
  3443. }
  3444. return 0;
  3445. }
  3446. //
  3447. // tokenizer
  3448. //
  3449. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  3450. return vocab.type;
  3451. }
  3452. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  3453. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  3454. }
  3455. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  3456. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  3457. }
  3458. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  3459. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  3460. }
  3461. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  3462. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  3463. }
  3464. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  3465. GGML_ASSERT(llama_is_byte_token(vocab, id));
  3466. const auto& token_data = vocab.id_to_token.at(id);
  3467. auto buf = token_data.text.substr(3, 2);
  3468. return strtol(buf.c_str(), NULL, 16);
  3469. }
  3470. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  3471. char buf[7];
  3472. int result = snprintf(buf, sizeof(buf), "<0x%02X>", ch);
  3473. GGML_ASSERT(0 <= result && result < 7);
  3474. return vocab.token_to_id.at(buf);
  3475. }
  3476. static void llama_escape_whitespace(std::string & text) {
  3477. replace_all(text, " ", "\xe2\x96\x81");
  3478. }
  3479. static void llama_unescape_whitespace(std::string & word) {
  3480. replace_all(word, "\xe2\x96\x81", " ");
  3481. }
  3482. struct llm_symbol {
  3483. using index = int;
  3484. index prev;
  3485. index next;
  3486. const char * text;
  3487. size_t n;
  3488. };
  3489. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  3490. // SPM tokenizer
  3491. // original implementation:
  3492. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  3493. struct llm_bigram_spm {
  3494. struct comparator {
  3495. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  3496. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  3497. }
  3498. };
  3499. using queue_storage = std::vector<llm_bigram_spm>;
  3500. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  3501. llm_symbol::index left;
  3502. llm_symbol::index right;
  3503. float score;
  3504. size_t size;
  3505. };
  3506. struct llm_tokenizer_spm {
  3507. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  3508. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  3509. // split string into utf8 chars
  3510. int index = 0;
  3511. size_t offs = 0;
  3512. while (offs < text.size()) {
  3513. llm_symbol sym;
  3514. size_t len = utf8_len(text[offs]);
  3515. sym.text = text.c_str() + offs;
  3516. sym.n = std::min(len, text.size() - offs);
  3517. offs += sym.n;
  3518. sym.prev = index - 1;
  3519. sym.next = offs == text.size() ? -1 : index + 1;
  3520. index++;
  3521. symbols.emplace_back(sym);
  3522. }
  3523. // seed the work queue with all possible 2-character tokens.
  3524. for (size_t i = 1; i < symbols.size(); ++i) {
  3525. try_add_bigram(i - 1, i);
  3526. }
  3527. // keep substituting the highest frequency pairs for as long as we can.
  3528. while (!work_queue.empty()) {
  3529. auto bigram = work_queue.top();
  3530. work_queue.pop();
  3531. auto & left_sym = symbols[bigram.left];
  3532. auto & right_sym = symbols[bigram.right];
  3533. // if one of the symbols already got merged, skip it.
  3534. if (left_sym.n == 0 || right_sym.n == 0 ||
  3535. left_sym.n + right_sym.n != bigram.size) {
  3536. continue;
  3537. }
  3538. // merge the right sym into the left one
  3539. left_sym.n += right_sym.n;
  3540. right_sym.n = 0;
  3541. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  3542. // remove the right sym from the chain
  3543. left_sym.next = right_sym.next;
  3544. if (right_sym.next >= 0) {
  3545. symbols[right_sym.next].prev = bigram.left;
  3546. }
  3547. // find more substitutions
  3548. try_add_bigram(left_sym.prev, bigram.left);
  3549. try_add_bigram(bigram.left, left_sym.next);
  3550. }
  3551. for (int i = 0; i != -1; i = symbols[i].next) {
  3552. auto & symbol = symbols[i];
  3553. resegment(symbol, output);
  3554. }
  3555. }
  3556. private:
  3557. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  3558. auto text = std::string(symbol.text, symbol.n);
  3559. auto token = vocab.token_to_id.find(text);
  3560. // Do we need to support is_unused?
  3561. if (token != vocab.token_to_id.end()) {
  3562. output.push_back((*token).second);
  3563. return;
  3564. }
  3565. const auto p = rev_merge.find(text);
  3566. if (p == rev_merge.end()) {
  3567. // output any symbols that did not form tokens as bytes.
  3568. for (int j = 0; j < (int)symbol.n; ++j) {
  3569. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  3570. output.push_back(token_id);
  3571. }
  3572. return;
  3573. }
  3574. resegment(symbols[p->second.first], output);
  3575. resegment(symbols[p->second.second], output);
  3576. }
  3577. void try_add_bigram(int left, int right) {
  3578. if (left == -1 || right == -1) {
  3579. return;
  3580. }
  3581. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  3582. auto token = vocab.token_to_id.find(text);
  3583. if (token == vocab.token_to_id.end()) {
  3584. return;
  3585. }
  3586. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  3587. return;
  3588. }
  3589. const auto & tok_data = vocab.id_to_token[(*token).second];
  3590. llm_bigram_spm bigram;
  3591. bigram.left = left;
  3592. bigram.right = right;
  3593. bigram.score = tok_data.score;
  3594. bigram.size = text.size();
  3595. work_queue.push(bigram);
  3596. // Do we need to support is_unused?
  3597. rev_merge[text] = std::make_pair(left, right);
  3598. }
  3599. const llama_vocab & vocab;
  3600. std::vector<llm_symbol> symbols;
  3601. llm_bigram_spm::queue work_queue;
  3602. std::map<std::string, std::pair<int, int>> rev_merge;
  3603. };
  3604. // BPE tokenizer
  3605. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  3606. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  3607. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  3608. struct llm_bigram_bpe {
  3609. struct comparator {
  3610. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  3611. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  3612. }
  3613. };
  3614. using queue_storage = std::vector<llm_bigram_bpe>;
  3615. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  3616. llm_symbol::index left;
  3617. llm_symbol::index right;
  3618. std::string text;
  3619. int rank;
  3620. size_t size;
  3621. };
  3622. struct llm_tokenizer_bpe {
  3623. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  3624. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  3625. int final_prev_index = -1;
  3626. auto word_collection = bpe_gpt2_preprocess(text);
  3627. symbols_final.clear();
  3628. for (auto & word : word_collection) {
  3629. work_queue = llm_bigram_bpe::queue();
  3630. symbols.clear();
  3631. int index = 0;
  3632. size_t offset = 0;
  3633. while (offset < word.size()) {
  3634. llm_symbol sym;
  3635. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  3636. sym.text = word.c_str() + offset;
  3637. sym.n = 1;
  3638. sym.n = char_len;
  3639. offset += sym.n;
  3640. sym.prev = index - 1;
  3641. sym.next = offset == word.size() ? -1 : index + 1;
  3642. index++;
  3643. symbols.emplace_back(sym);
  3644. }
  3645. for (size_t i = 1; i < symbols.size(); ++i) {
  3646. add_new_bigram(i - 1, i);
  3647. }
  3648. // build token(s)
  3649. while (!work_queue.empty()) {
  3650. auto bigram = work_queue.top();
  3651. work_queue.pop();
  3652. auto & left_symbol = symbols[bigram.left];
  3653. auto & right_symbol = symbols[bigram.right];
  3654. if (left_symbol.n == 0 || right_symbol.n == 0) {
  3655. continue;
  3656. }
  3657. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  3658. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  3659. if (left_token + right_token != bigram.text) {
  3660. continue; // Skip this bigram if it's outdated
  3661. }
  3662. // merge the right sym into the left one
  3663. left_symbol.n += right_symbol.n;
  3664. right_symbol.n = 0;
  3665. // remove the right sym from the chain
  3666. left_symbol.next = right_symbol.next;
  3667. if (right_symbol.next >= 0) {
  3668. symbols[right_symbol.next].prev = bigram.left;
  3669. }
  3670. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  3671. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  3672. }
  3673. // add the fnished tokens to the final list keeping correct order for next and prev
  3674. for (auto & sym : symbols) {
  3675. if (sym.n > 0) {
  3676. sym.prev = final_prev_index;
  3677. sym.next = -1;
  3678. if (final_prev_index != -1) {
  3679. symbols_final[final_prev_index].next = symbols_final.size();
  3680. }
  3681. symbols_final.emplace_back(sym);
  3682. final_prev_index = symbols_final.size() - 1;
  3683. }
  3684. }
  3685. }
  3686. symbols = symbols_final;
  3687. if (!symbols.empty()) {
  3688. for (int i = 0; i != -1; i = symbols[i].next) {
  3689. auto & symbol = symbols[i];
  3690. if (symbol.n == 0) {
  3691. continue;
  3692. }
  3693. const std::string str = std::string(symbol.text, symbol.n);
  3694. const auto token = vocab.token_to_id.find(str);
  3695. if (token == vocab.token_to_id.end()) {
  3696. for (auto j = str.begin(); j != str.end(); ++j) {
  3697. std::string byte_str(1, *j);
  3698. auto token_multibyte = vocab.token_to_id.find(byte_str);
  3699. if (token_multibyte == vocab.token_to_id.end()) {
  3700. try {
  3701. llama_token token_byte = llama_byte_to_token(vocab, *j);
  3702. output.push_back(token_byte);
  3703. } catch (const std::out_of_range & err) {
  3704. fprintf(stderr,"ERROR: byte not found in vocab: '%s'\n", byte_str.c_str());
  3705. }
  3706. } else {
  3707. output.push_back((*token_multibyte).second);
  3708. }
  3709. }
  3710. } else {
  3711. output.push_back((*token).second);
  3712. }
  3713. }
  3714. }
  3715. }
  3716. private:
  3717. void add_new_bigram(int left, int right) {
  3718. if (left == -1 || right == -1) {
  3719. return;
  3720. }
  3721. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  3722. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  3723. int rank_found = -1;
  3724. rank_found = vocab.find_bpe_rank(left_token, right_token);
  3725. if (rank_found < 0) {
  3726. return;
  3727. }
  3728. llm_bigram_bpe bigram;
  3729. bigram.left = left;
  3730. bigram.right = right;
  3731. bigram.text = left_token + right_token;
  3732. bigram.size = left_token.size() + right_token.size();
  3733. bigram.rank = rank_found;
  3734. work_queue.push(bigram);
  3735. }
  3736. // probably not 100% correct
  3737. static std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  3738. std::vector<std::string> words;
  3739. // ref: https://github.com/openai/gpt-2/blob/a74da5d99abaaba920de8131d64da2862a8f213b/src/encoder.py#L53
  3740. const std::string pattern = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  3741. const std::regex re(pattern);
  3742. auto words_begin = std::sregex_iterator(text.begin(), text.end(), re);
  3743. auto words_end = std::sregex_iterator();
  3744. auto n_words = std::distance(words_begin, words_end);
  3745. words.reserve(n_words);
  3746. for (auto it = words_begin; it != words_end; ++it) {
  3747. words.push_back(it->str());
  3748. }
  3749. return words;
  3750. }
  3751. const llama_vocab & vocab;
  3752. std::vector<llm_symbol> symbols;
  3753. std::vector<llm_symbol> symbols_final;
  3754. llm_bigram_bpe::queue work_queue;
  3755. };
  3756. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos) {
  3757. std::vector<llama_vocab::id> output;
  3758. // OG tokenizer behavior:
  3759. //
  3760. // tokenizer.encode('', add_bos=True) returns [1]
  3761. // tokenizer.encode('', add_bos=False) returns []
  3762. if (bos && vocab.special_bos_id != -1) {
  3763. output.push_back(vocab.special_bos_id);
  3764. }
  3765. if (raw_text.empty()) {
  3766. return output;
  3767. }
  3768. switch (vocab.type) {
  3769. case LLAMA_VOCAB_TYPE_SPM:
  3770. {
  3771. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  3772. raw_text = " " + raw_text;
  3773. llm_tokenizer_spm tokenizer(vocab);
  3774. llama_escape_whitespace(raw_text);
  3775. tokenizer.tokenize(raw_text, output);
  3776. } break;
  3777. case LLAMA_VOCAB_TYPE_BPE:
  3778. {
  3779. llm_tokenizer_bpe tokenizer(vocab);
  3780. tokenizer.tokenize(raw_text, output);
  3781. } break;
  3782. }
  3783. return output;
  3784. }
  3785. //
  3786. // grammar - internal
  3787. //
  3788. struct llama_partial_utf8 {
  3789. uint32_t value; // bit value so far (unshifted)
  3790. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  3791. };
  3792. struct llama_grammar {
  3793. const std::vector<std::vector<llama_grammar_element>> rules;
  3794. std::vector<std::vector<const llama_grammar_element *>> stacks;
  3795. // buffer for partially generated UTF-8 sequence from accepted tokens
  3796. llama_partial_utf8 partial_utf8;
  3797. };
  3798. struct llama_grammar_candidate {
  3799. size_t index;
  3800. const uint32_t * code_points;
  3801. llama_partial_utf8 partial_utf8;
  3802. };
  3803. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  3804. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  3805. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  3806. const char * src,
  3807. llama_partial_utf8 partial_start) {
  3808. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  3809. const char * pos = src;
  3810. std::vector<uint32_t> code_points;
  3811. uint32_t value = partial_start.value;
  3812. int n_remain = partial_start.n_remain;
  3813. // continue previous decode, if applicable
  3814. while (*pos != 0 && n_remain > 0) {
  3815. uint8_t next_byte = static_cast<uint8_t>(*pos);
  3816. if ((next_byte >> 6) != 2) {
  3817. // invalid sequence, abort
  3818. code_points.push_back(0);
  3819. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  3820. }
  3821. value = (value << 6) + (next_byte & 0x3F);
  3822. ++pos;
  3823. --n_remain;
  3824. }
  3825. if (partial_start.n_remain > 0 && n_remain == 0) {
  3826. code_points.push_back(value);
  3827. }
  3828. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  3829. while (*pos != 0) {
  3830. uint8_t first_byte = static_cast<uint8_t>(*pos);
  3831. uint8_t highbits = first_byte >> 4;
  3832. n_remain = lookup[highbits] - 1;
  3833. if (n_remain < 0) {
  3834. // invalid sequence, abort
  3835. code_points.clear();
  3836. code_points.push_back(0);
  3837. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  3838. }
  3839. uint8_t mask = (1 << (7 - n_remain)) - 1;
  3840. value = first_byte & mask;
  3841. ++pos;
  3842. while (*pos != 0 && n_remain > 0) {
  3843. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  3844. ++pos;
  3845. --n_remain;
  3846. }
  3847. if (n_remain == 0) {
  3848. code_points.push_back(value);
  3849. }
  3850. }
  3851. code_points.push_back(0);
  3852. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  3853. }
  3854. // returns true iff pos points to the end of one of the definitions of a rule
  3855. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  3856. switch (pos->type) {
  3857. case LLAMA_GRETYPE_END: return true; // NOLINT
  3858. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  3859. default: return false;
  3860. }
  3861. }
  3862. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  3863. // asserts that pos is pointing to a char range element
  3864. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  3865. const llama_grammar_element * pos,
  3866. const uint32_t chr) {
  3867. bool found = false;
  3868. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  3869. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  3870. do {
  3871. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  3872. // inclusive range, e.g. [a-z]
  3873. found = found || (pos->value <= chr && chr <= pos[1].value);
  3874. pos += 2;
  3875. } else {
  3876. // exact char match, e.g. [a] or "a"
  3877. found = found || pos->value == chr;
  3878. pos += 1;
  3879. }
  3880. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  3881. return std::make_pair(found == is_positive_char, pos);
  3882. }
  3883. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  3884. // range at pos (regular or inverse range)
  3885. // asserts that pos is pointing to a char range element
  3886. static bool llama_grammar_match_partial_char(
  3887. const llama_grammar_element * pos,
  3888. const llama_partial_utf8 partial_utf8) {
  3889. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  3890. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  3891. uint32_t partial_value = partial_utf8.value;
  3892. int n_remain = partial_utf8.n_remain;
  3893. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  3894. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  3895. return false;
  3896. }
  3897. // range of possible code points this partial UTF-8 sequence could complete to
  3898. uint32_t low = partial_value << (n_remain * 6);
  3899. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  3900. if (low == 0) {
  3901. if (n_remain == 2) {
  3902. low = 1 << 11;
  3903. } else if (n_remain == 3) {
  3904. low = 1 << 16;
  3905. }
  3906. }
  3907. do {
  3908. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  3909. // inclusive range, e.g. [a-z]
  3910. if (pos->value <= high && low <= pos[1].value) {
  3911. return is_positive_char;
  3912. }
  3913. pos += 2;
  3914. } else {
  3915. // exact char match, e.g. [a] or "a"
  3916. if (low <= pos->value && pos->value <= high) {
  3917. return is_positive_char;
  3918. }
  3919. pos += 1;
  3920. }
  3921. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  3922. return !is_positive_char;
  3923. }
  3924. // transforms a grammar pushdown stack into N possible stacks, all ending
  3925. // at a character range (terminal element)
  3926. static void llama_grammar_advance_stack(
  3927. const std::vector<std::vector<llama_grammar_element>> & rules,
  3928. const std::vector<const llama_grammar_element *> & stack,
  3929. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  3930. if (stack.empty()) {
  3931. new_stacks.emplace_back(stack);
  3932. return;
  3933. }
  3934. const llama_grammar_element * pos = stack.back();
  3935. switch (pos->type) {
  3936. case LLAMA_GRETYPE_RULE_REF: {
  3937. const size_t rule_id = static_cast<size_t>(pos->value);
  3938. const llama_grammar_element * subpos = rules[rule_id].data();
  3939. do {
  3940. // init new stack without the top (pos)
  3941. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  3942. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  3943. // if this rule ref is followed by another element, add that to stack
  3944. new_stack.push_back(pos + 1);
  3945. }
  3946. if (!llama_grammar_is_end_of_sequence(subpos)) {
  3947. // if alternate is nonempty, add to stack
  3948. new_stack.push_back(subpos);
  3949. }
  3950. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  3951. while (!llama_grammar_is_end_of_sequence(subpos)) {
  3952. // scan to end of alternate def
  3953. subpos++;
  3954. }
  3955. if (subpos->type == LLAMA_GRETYPE_ALT) {
  3956. // there's another alternate def of this rule to process
  3957. subpos++;
  3958. } else {
  3959. break;
  3960. }
  3961. } while (true);
  3962. break;
  3963. }
  3964. case LLAMA_GRETYPE_CHAR:
  3965. case LLAMA_GRETYPE_CHAR_NOT:
  3966. new_stacks.emplace_back(stack);
  3967. break;
  3968. default:
  3969. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  3970. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  3971. // those
  3972. GGML_ASSERT(false);
  3973. }
  3974. }
  3975. // takes a set of possible pushdown stacks on a grammar, which are required to
  3976. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  3977. // produces the N possible stacks if the given char is accepted at those
  3978. // positions
  3979. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  3980. const std::vector<std::vector<llama_grammar_element>> & rules,
  3981. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3982. const uint32_t chr) {
  3983. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  3984. for (const auto & stack : stacks) {
  3985. if (stack.empty()) {
  3986. continue;
  3987. }
  3988. auto match = llama_grammar_match_char(stack.back(), chr);
  3989. if (match.first) {
  3990. const llama_grammar_element * pos = match.second;
  3991. // update top of stack to next element, if any
  3992. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  3993. if (!llama_grammar_is_end_of_sequence(pos)) {
  3994. new_stack.push_back(pos);
  3995. }
  3996. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  3997. }
  3998. }
  3999. return new_stacks;
  4000. }
  4001. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  4002. const std::vector<std::vector<llama_grammar_element>> & rules,
  4003. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  4004. const std::vector<llama_grammar_candidate> & candidates);
  4005. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  4006. const std::vector<std::vector<llama_grammar_element>> & rules,
  4007. const std::vector<const llama_grammar_element *> & stack,
  4008. const std::vector<llama_grammar_candidate> & candidates) {
  4009. std::vector<llama_grammar_candidate> rejects;
  4010. if (stack.empty()) {
  4011. for (auto tok : candidates) {
  4012. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  4013. rejects.push_back(tok);
  4014. }
  4015. }
  4016. return rejects;
  4017. }
  4018. const llama_grammar_element * stack_pos = stack.back();
  4019. std::vector<llama_grammar_candidate> next_candidates;
  4020. for (auto tok : candidates) {
  4021. if (*tok.code_points == 0) {
  4022. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  4023. // that cannot satisfy this position in grammar
  4024. if (tok.partial_utf8.n_remain != 0 &&
  4025. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  4026. rejects.push_back(tok);
  4027. }
  4028. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  4029. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  4030. } else {
  4031. rejects.push_back(tok);
  4032. }
  4033. }
  4034. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  4035. // update top of stack to next element, if any
  4036. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  4037. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  4038. stack_after.push_back(stack_pos_after);
  4039. }
  4040. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  4041. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  4042. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  4043. for (auto tok : next_rejects) {
  4044. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  4045. }
  4046. return rejects;
  4047. }
  4048. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  4049. const std::vector<std::vector<llama_grammar_element>> & rules,
  4050. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  4051. const std::vector<llama_grammar_candidate> & candidates) {
  4052. GGML_ASSERT(!stacks.empty()); // REVIEW
  4053. if (candidates.empty()) {
  4054. return std::vector<llama_grammar_candidate>();
  4055. }
  4056. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  4057. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  4058. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  4059. }
  4060. return rejects;
  4061. }
  4062. //
  4063. // grammar - external
  4064. //
  4065. struct llama_grammar * llama_grammar_init(
  4066. const llama_grammar_element ** rules,
  4067. size_t n_rules,
  4068. size_t start_rule_index) {
  4069. const llama_grammar_element * pos;
  4070. // copy rule definitions into vectors
  4071. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  4072. for (size_t i = 0; i < n_rules; i++) {
  4073. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  4074. vec_rules[i].push_back(*pos);
  4075. }
  4076. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  4077. }
  4078. // loop over alternates of start rule to build initial stacks
  4079. std::vector<std::vector<const llama_grammar_element *>> stacks;
  4080. pos = rules[start_rule_index];
  4081. do {
  4082. std::vector<const llama_grammar_element *> stack;
  4083. if (!llama_grammar_is_end_of_sequence(pos)) {
  4084. // if alternate is nonempty, add to stack
  4085. stack.push_back(pos);
  4086. }
  4087. llama_grammar_advance_stack(vec_rules, stack, stacks);
  4088. while (!llama_grammar_is_end_of_sequence(pos)) {
  4089. // scan to end of alternate def
  4090. pos++;
  4091. }
  4092. if (pos->type == LLAMA_GRETYPE_ALT) {
  4093. // there's another alternate def of this rule to process
  4094. pos++;
  4095. } else {
  4096. break;
  4097. }
  4098. } while (true);
  4099. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  4100. }
  4101. void llama_grammar_free(struct llama_grammar * grammar) {
  4102. delete grammar;
  4103. }
  4104. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  4105. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  4106. // redirect elements in stacks to point to new rules
  4107. for (size_t is = 0; is < result->stacks.size(); is++) {
  4108. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  4109. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  4110. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  4111. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  4112. result->stacks[is][ie] = &result->rules[ir0][ir1];
  4113. }
  4114. }
  4115. }
  4116. }
  4117. }
  4118. return result;
  4119. }
  4120. //
  4121. // sampling
  4122. //
  4123. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  4124. if (seed == LLAMA_DEFAULT_SEED) {
  4125. seed = time(NULL);
  4126. }
  4127. ctx->rng.seed(seed);
  4128. }
  4129. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  4130. GGML_ASSERT(candidates->size > 0);
  4131. const int64_t t_start_sample_us = ggml_time_us();
  4132. // Sort the logits in descending order
  4133. if (!candidates->sorted) {
  4134. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  4135. return a.logit > b.logit;
  4136. });
  4137. candidates->sorted = true;
  4138. }
  4139. float max_l = candidates->data[0].logit;
  4140. float cum_sum = 0.0f;
  4141. for (size_t i = 0; i < candidates->size; ++i) {
  4142. float p = expf(candidates->data[i].logit - max_l);
  4143. candidates->data[i].p = p;
  4144. cum_sum += p;
  4145. }
  4146. for (size_t i = 0; i < candidates->size; ++i) {
  4147. candidates->data[i].p /= cum_sum;
  4148. }
  4149. if (ctx) {
  4150. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4151. }
  4152. }
  4153. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  4154. const int64_t t_start_sample_us = ggml_time_us();
  4155. k = std::max(k, (int) min_keep);
  4156. k = std::min(k, (int) candidates->size);
  4157. // Sort scores in descending order
  4158. if (!candidates->sorted) {
  4159. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  4160. return a.logit > b.logit;
  4161. };
  4162. if (k == (int) candidates->size) {
  4163. std::sort(candidates->data, candidates->data + candidates->size, comp);
  4164. } else {
  4165. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  4166. }
  4167. candidates->sorted = true;
  4168. }
  4169. candidates->size = k;
  4170. if (ctx) {
  4171. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4172. }
  4173. }
  4174. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  4175. if (p >= 1.0f) {
  4176. return;
  4177. }
  4178. llama_sample_softmax(ctx, candidates);
  4179. const int64_t t_start_sample_us = ggml_time_us();
  4180. // Compute the cumulative probabilities
  4181. float cum_sum = 0.0f;
  4182. size_t last_idx = candidates->size;
  4183. for (size_t i = 0; i < candidates->size; ++i) {
  4184. cum_sum += candidates->data[i].p;
  4185. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  4186. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  4187. if (cum_sum >= p && i + 1 >= min_keep) {
  4188. last_idx = i + 1;
  4189. break;
  4190. }
  4191. }
  4192. // Resize the output vector to keep only the top-p tokens
  4193. candidates->size = last_idx;
  4194. if (ctx) {
  4195. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4196. }
  4197. }
  4198. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  4199. if (z >= 1.0f || candidates->size <= 2) {
  4200. return;
  4201. }
  4202. llama_sample_softmax(nullptr, candidates);
  4203. const int64_t t_start_sample_us = ggml_time_us();
  4204. // Compute the first and second derivatives
  4205. std::vector<float> first_derivatives(candidates->size - 1);
  4206. std::vector<float> second_derivatives(candidates->size - 2);
  4207. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  4208. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  4209. }
  4210. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  4211. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  4212. }
  4213. // Calculate absolute value of second derivatives
  4214. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  4215. second_derivatives[i] = std::abs(second_derivatives[i]);
  4216. }
  4217. // Normalize the second derivatives
  4218. {
  4219. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  4220. if (second_derivatives_sum > 1e-6f) {
  4221. for (float & value : second_derivatives) {
  4222. value /= second_derivatives_sum;
  4223. }
  4224. } else {
  4225. for (float & value : second_derivatives) {
  4226. value = 1.0f / second_derivatives.size();
  4227. }
  4228. }
  4229. }
  4230. float cum_sum = 0.0f;
  4231. size_t last_idx = candidates->size;
  4232. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  4233. cum_sum += second_derivatives[i];
  4234. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  4235. if (cum_sum > z && i >= min_keep) {
  4236. last_idx = i;
  4237. break;
  4238. }
  4239. }
  4240. // Resize the output vector to keep only the tokens above the tail location
  4241. candidates->size = last_idx;
  4242. if (ctx) {
  4243. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4244. }
  4245. }
  4246. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  4247. // Reference implementation:
  4248. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  4249. if (p >= 1.0f) {
  4250. return;
  4251. }
  4252. // Compute the softmax of logits and calculate entropy
  4253. llama_sample_softmax(nullptr, candidates);
  4254. const int64_t t_start_sample_us = ggml_time_us();
  4255. float entropy = 0.0f;
  4256. for (size_t i = 0; i < candidates->size; ++i) {
  4257. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  4258. }
  4259. // Compute the absolute difference between negative log probability and entropy for each candidate
  4260. std::vector<float> shifted_scores;
  4261. for (size_t i = 0; i < candidates->size; ++i) {
  4262. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  4263. shifted_scores.push_back(shifted_score);
  4264. }
  4265. // Sort tokens based on the shifted_scores and their corresponding indices
  4266. std::vector<size_t> indices(candidates->size);
  4267. std::iota(indices.begin(), indices.end(), 0);
  4268. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  4269. return shifted_scores[a] < shifted_scores[b];
  4270. });
  4271. // Compute the cumulative probabilities
  4272. float cum_sum = 0.0f;
  4273. size_t last_idx = indices.size();
  4274. for (size_t i = 0; i < indices.size(); ++i) {
  4275. size_t idx = indices[i];
  4276. cum_sum += candidates->data[idx].p;
  4277. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  4278. if (cum_sum > p && i >= min_keep - 1) {
  4279. last_idx = i + 1;
  4280. break;
  4281. }
  4282. }
  4283. // Resize the output vector to keep only the locally typical tokens
  4284. std::vector<llama_token_data> new_candidates;
  4285. for (size_t i = 0; i < last_idx; ++i) {
  4286. size_t idx = indices[i];
  4287. new_candidates.push_back(candidates->data[idx]);
  4288. }
  4289. // Replace the data in candidates with the new_candidates data
  4290. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  4291. candidates->size = new_candidates.size();
  4292. if (ctx) {
  4293. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4294. }
  4295. }
  4296. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  4297. const int64_t t_start_sample_us = ggml_time_us();
  4298. for (size_t i = 0; i < candidates_p->size; ++i) {
  4299. candidates_p->data[i].logit /= temp;
  4300. }
  4301. if (ctx) {
  4302. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4303. }
  4304. }
  4305. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  4306. llama_sample_temp(ctx, candidates_p, temp);
  4307. }
  4308. void llama_sample_repetition_penalty(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens, size_t last_tokens_size, float penalty) {
  4309. if (last_tokens_size == 0 || penalty == 1.0f) {
  4310. return;
  4311. }
  4312. const int64_t t_start_sample_us = ggml_time_us();
  4313. for (size_t i = 0; i < candidates->size; ++i) {
  4314. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  4315. if (token_iter == last_tokens + last_tokens_size) {
  4316. continue;
  4317. }
  4318. // The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong.
  4319. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  4320. if (candidates->data[i].logit <= 0) {
  4321. candidates->data[i].logit *= penalty;
  4322. } else {
  4323. candidates->data[i].logit /= penalty;
  4324. }
  4325. }
  4326. candidates->sorted = false;
  4327. if (ctx) {
  4328. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4329. }
  4330. }
  4331. void llama_sample_frequency_and_presence_penalties(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens_p, size_t last_tokens_size, float alpha_frequency, float alpha_presence) {
  4332. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  4333. return;
  4334. }
  4335. const int64_t t_start_sample_us = ggml_time_us();
  4336. // Create a frequency map to count occurrences of each token in last_tokens
  4337. std::unordered_map<llama_token, int> token_count;
  4338. for (size_t i = 0; i < last_tokens_size; ++i) {
  4339. token_count[last_tokens_p[i]]++;
  4340. }
  4341. // Apply frequency and presence penalties to the candidates
  4342. for (size_t i = 0; i < candidates->size; ++i) {
  4343. auto token_iter = token_count.find(candidates->data[i].id);
  4344. if (token_iter == token_count.end()) {
  4345. continue;
  4346. }
  4347. int count = token_iter->second;
  4348. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  4349. }
  4350. candidates->sorted = false;
  4351. if (ctx) {
  4352. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4353. }
  4354. }
  4355. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  4356. GGML_ASSERT(ctx);
  4357. const int64_t t_start_sample_us = ggml_time_us();
  4358. bool allow_eos = false;
  4359. for (const auto & stack : grammar->stacks) {
  4360. if (stack.empty()) {
  4361. allow_eos = true;
  4362. break;
  4363. }
  4364. }
  4365. const llama_token eos = llama_token_eos(ctx);
  4366. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  4367. std::vector<llama_grammar_candidate> candidates_grammar;
  4368. for (size_t i = 0; i < candidates->size; ++i) {
  4369. const llama_token id = candidates->data[i].id;
  4370. const std::string piece = llama_token_to_str(ctx, id);
  4371. if (id == eos) {
  4372. if (!allow_eos) {
  4373. candidates->data[i].logit = -INFINITY;
  4374. }
  4375. } else if (piece.empty() || piece[0] == 0) {
  4376. candidates->data[i].logit = -INFINITY;
  4377. } else {
  4378. candidates_decoded.push_back(decode_utf8(piece.c_str(), grammar->partial_utf8));
  4379. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  4380. }
  4381. }
  4382. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  4383. for (const auto & reject : rejects) {
  4384. candidates->data[reject.index].logit = -INFINITY;
  4385. }
  4386. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4387. }
  4388. static void llama_log_softmax(float * array, size_t size) {
  4389. float max_l = *std::max_element(array, array + size);
  4390. float sum = 0.f;
  4391. for (size_t i = 0; i < size; ++i) {
  4392. float p = expf(array[i] - max_l);
  4393. sum += p;
  4394. array[i] = p;
  4395. }
  4396. for (size_t i = 0; i < size; ++i) {
  4397. array[i] = logf(array[i] / sum);
  4398. }
  4399. }
  4400. void llama_sample_classifier_free_guidance(
  4401. struct llama_context * ctx,
  4402. llama_token_data_array * candidates,
  4403. struct llama_context * guidance_ctx,
  4404. float scale) {
  4405. int64_t t_start_sample_us = ggml_time_us();
  4406. GGML_ASSERT(ctx);
  4407. auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  4408. GGML_ASSERT(n_vocab == (int)candidates->size);
  4409. GGML_ASSERT(!candidates->sorted);
  4410. std::vector<float> logits_base;
  4411. logits_base.reserve(candidates->size);
  4412. for (size_t i = 0; i < candidates->size; ++i) {
  4413. logits_base.push_back(candidates->data[i].logit);
  4414. }
  4415. llama_log_softmax(logits_base.data(), candidates->size);
  4416. float* logits_guidance = llama_get_logits(guidance_ctx);
  4417. llama_log_softmax(logits_guidance, n_vocab);
  4418. for (int i = 0; i < n_vocab; ++i) {
  4419. float logit_guidance = logits_guidance[i];
  4420. float logit_base = logits_base[i];
  4421. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  4422. }
  4423. if (ctx) {
  4424. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4425. }
  4426. }
  4427. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  4428. GGML_ASSERT(ctx);
  4429. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  4430. int64_t t_start_sample_us;
  4431. t_start_sample_us = ggml_time_us();
  4432. llama_sample_softmax(nullptr, candidates);
  4433. // Estimate s_hat using the most probable m tokens
  4434. float s_hat = 0.0;
  4435. float sum_ti_bi = 0.0;
  4436. float sum_ti_sq = 0.0;
  4437. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  4438. float t_i = logf(float(i + 2) / float(i + 1));
  4439. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  4440. sum_ti_bi += t_i * b_i;
  4441. sum_ti_sq += t_i * t_i;
  4442. }
  4443. s_hat = sum_ti_bi / sum_ti_sq;
  4444. // Compute k from the estimated s_hat and target surprise value
  4445. float epsilon_hat = s_hat - 1;
  4446. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  4447. // Sample the next word X using top-k sampling
  4448. llama_sample_top_k(nullptr, candidates, int(k), 1);
  4449. if (ctx) {
  4450. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4451. }
  4452. llama_token X = llama_sample_token(ctx, candidates);
  4453. t_start_sample_us = ggml_time_us();
  4454. // Compute error as the difference between observed surprise and target surprise value
  4455. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  4456. return candidate.id == X;
  4457. }));
  4458. float observed_surprise = -log2f(candidates->data[X_idx].p);
  4459. float e = observed_surprise - tau;
  4460. // Update mu using the learning rate and error
  4461. *mu = *mu - eta * e;
  4462. if (ctx) {
  4463. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4464. }
  4465. return X;
  4466. }
  4467. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  4468. int64_t t_start_sample_us;
  4469. t_start_sample_us = ggml_time_us();
  4470. llama_sample_softmax(ctx, candidates);
  4471. // Truncate the words with surprise values greater than mu
  4472. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  4473. return -log2f(candidate.p) > *mu;
  4474. }));
  4475. if (candidates->size == 0) {
  4476. candidates->size = 1;
  4477. }
  4478. if (ctx) {
  4479. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4480. }
  4481. // Normalize the probabilities of the remaining words
  4482. llama_sample_softmax(ctx, candidates);
  4483. // Sample the next word X from the remaining words
  4484. llama_token X = llama_sample_token(ctx, candidates);
  4485. t_start_sample_us = ggml_time_us();
  4486. // Compute error as the difference between observed surprise and target surprise value
  4487. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  4488. return candidate.id == X;
  4489. }));
  4490. float observed_surprise = -log2f(candidates->data[X_idx].p);
  4491. float e = observed_surprise - tau;
  4492. // Update mu using the learning rate and error
  4493. *mu = *mu - eta * e;
  4494. if (ctx) {
  4495. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4496. }
  4497. return X;
  4498. }
  4499. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  4500. const int64_t t_start_sample_us = ggml_time_us();
  4501. // Find max element
  4502. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  4503. return a.logit < b.logit;
  4504. });
  4505. llama_token result = max_iter->id;
  4506. if (ctx) {
  4507. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4508. ctx->n_sample++;
  4509. }
  4510. return result;
  4511. }
  4512. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  4513. GGML_ASSERT(ctx);
  4514. const int64_t t_start_sample_us = ggml_time_us();
  4515. llama_sample_softmax(nullptr, candidates);
  4516. std::vector<float> probs;
  4517. probs.reserve(candidates->size);
  4518. for (size_t i = 0; i < candidates->size; ++i) {
  4519. probs.push_back(candidates->data[i].p);
  4520. }
  4521. std::discrete_distribution<> dist(probs.begin(), probs.end());
  4522. auto & rng = ctx->rng;
  4523. int idx = dist(rng);
  4524. llama_token result = candidates->data[idx].id;
  4525. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4526. ctx->n_sample++;
  4527. return result;
  4528. }
  4529. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  4530. const int64_t t_start_sample_us = ggml_time_us();
  4531. if (token == llama_token_eos(ctx)) {
  4532. for (const auto & stack : grammar->stacks) {
  4533. if (stack.empty()) {
  4534. return;
  4535. }
  4536. }
  4537. GGML_ASSERT(false);
  4538. }
  4539. const std::string piece = llama_token_to_str(ctx, token);
  4540. // Note terminating 0 in decoded string
  4541. const auto decoded = decode_utf8(piece.c_str(), grammar->partial_utf8);
  4542. const auto & code_points = decoded.first;
  4543. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  4544. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  4545. }
  4546. grammar->partial_utf8 = decoded.second;
  4547. GGML_ASSERT(!grammar->stacks.empty());
  4548. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4549. }
  4550. //
  4551. // Beam search
  4552. //
  4553. struct llama_beam {
  4554. std::vector<llama_token> tokens;
  4555. float p; // Cumulative beam probability (renormalized relative to all beams)
  4556. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  4557. // Sort beams by probability. In case of ties, prefer beams at eob.
  4558. bool operator<(const llama_beam & rhs) const {
  4559. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  4560. }
  4561. // Shift off first n tokens and discard them.
  4562. void shift_tokens(const size_t n) {
  4563. if (n) {
  4564. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  4565. tokens.resize(tokens.size() - n);
  4566. }
  4567. }
  4568. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  4569. };
  4570. // A struct for calculating logit-related info.
  4571. struct llama_logit_info {
  4572. const float * const logits;
  4573. const int n_vocab;
  4574. const float max_l;
  4575. const float normalizer;
  4576. struct sum_exp {
  4577. float max_l;
  4578. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  4579. };
  4580. llama_logit_info(llama_context * ctx)
  4581. : logits(llama_get_logits(ctx))
  4582. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  4583. , max_l(*std::max_element(logits, logits + n_vocab))
  4584. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  4585. { }
  4586. llama_token_data get_token_data(const llama_token token_id) const {
  4587. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  4588. return {token_id, logits[token_id], p};
  4589. }
  4590. // Return top k token_data by logit.
  4591. std::vector<llama_token_data> top_k(size_t k) {
  4592. std::vector<llama_token_data> min_heap; // min-heap by logit
  4593. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  4594. min_heap.reserve(k_min);
  4595. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  4596. min_heap.push_back(get_token_data(token_id));
  4597. }
  4598. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  4599. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  4600. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  4601. if (min_heap.front().logit < logits[token_id]) {
  4602. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  4603. min_heap.back().id = token_id;
  4604. min_heap.back().logit = logits[token_id];
  4605. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  4606. }
  4607. }
  4608. return min_heap;
  4609. }
  4610. float probability_from_logit(float logit) const {
  4611. return normalizer * std::exp(logit - max_l);
  4612. }
  4613. };
  4614. struct llama_beam_search_data {
  4615. llama_context * ctx;
  4616. size_t n_beams;
  4617. int n_past;
  4618. int n_predict;
  4619. std::vector<llama_beam> beams;
  4620. std::vector<llama_beam> next_beams;
  4621. // Re-calculated on each loop iteration
  4622. size_t common_prefix_length;
  4623. // Used to communicate to/from callback on beams state.
  4624. std::vector<llama_beam_view> beam_views;
  4625. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  4626. : ctx(ctx)
  4627. , n_beams(n_beams)
  4628. , n_past(n_past)
  4629. , n_predict(n_predict)
  4630. , beam_views(n_beams) {
  4631. beams.reserve(n_beams);
  4632. next_beams.reserve(n_beams);
  4633. }
  4634. // Collapse beams to a single beam given by index.
  4635. void collapse_beams(const size_t beam_idx) {
  4636. if (0u < beam_idx) {
  4637. std::swap(beams[0], beams[beam_idx]);
  4638. }
  4639. beams.resize(1);
  4640. }
  4641. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  4642. // The repetative patterns below reflect the 2 stages of heaps:
  4643. // * Gather elements until the vector is full, then call std::make_heap() on it.
  4644. // * If the heap is full and a new element is found that should be included, pop the
  4645. // least element to the back(), replace it with the new, then push it into the heap.
  4646. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  4647. // Min-heaps use a greater-than comparator.
  4648. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  4649. if (beam.eob) {
  4650. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  4651. if (next_beams.size() < n_beams) {
  4652. next_beams.push_back(std::move(beam));
  4653. if (next_beams.size() == n_beams) {
  4654. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  4655. }
  4656. } else if (next_beams.front().p < beam.p) {
  4657. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  4658. next_beams.back() = std::move(beam);
  4659. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  4660. }
  4661. } else {
  4662. // beam is not at end-of-sentence, so branch with next top_k tokens.
  4663. if (!beam.tokens.empty()) {
  4664. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  4665. }
  4666. llama_logit_info logit_info(ctx);
  4667. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  4668. size_t i=0;
  4669. if (next_beams.size() < n_beams) {
  4670. for (; next_beams.size() < n_beams ; ++i) {
  4671. llama_beam next_beam = beam;
  4672. next_beam.tokens.push_back(next_tokens[i].id);
  4673. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  4674. next_beams.push_back(std::move(next_beam));
  4675. }
  4676. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  4677. } else {
  4678. for (; next_beams.front().p == 0.0f ; ++i) {
  4679. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  4680. next_beams.back() = beam;
  4681. next_beams.back().tokens.push_back(next_tokens[i].id);
  4682. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  4683. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  4684. }
  4685. }
  4686. for (; i < n_beams ; ++i) {
  4687. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  4688. if (next_beams.front().p < next_p) {
  4689. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  4690. next_beams.back() = beam;
  4691. next_beams.back().tokens.push_back(next_tokens[i].id);
  4692. next_beams.back().p = next_p;
  4693. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  4694. }
  4695. }
  4696. }
  4697. }
  4698. // Find common_prefix_length based on beams.
  4699. // Requires beams is not empty.
  4700. size_t find_common_prefix_length() {
  4701. size_t common_prefix_length = beams[0].tokens.size();
  4702. for (size_t i = 1 ; i < beams.size() ; ++i) {
  4703. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  4704. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  4705. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  4706. common_prefix_length = j;
  4707. break;
  4708. }
  4709. }
  4710. }
  4711. return common_prefix_length;
  4712. }
  4713. // Construct beams_state to send back to caller via the callback function.
  4714. // Side effect: set common_prefix_length = find_common_prefix_length();
  4715. llama_beams_state get_beams_state(const bool last_call) {
  4716. for (size_t i = 0 ; i < beams.size() ; ++i) {
  4717. beam_views[i] = beams[i].view();
  4718. }
  4719. common_prefix_length = find_common_prefix_length();
  4720. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  4721. }
  4722. // Loop:
  4723. // * while i < n_predict, AND
  4724. // * any of the beams have not yet reached end-of-beam (eob), AND
  4725. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  4726. // (since all other beam probabilities can only decrease)
  4727. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  4728. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  4729. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  4730. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  4731. !beams[top_beam_index()].eob ; ++i) {
  4732. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  4733. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  4734. if (common_prefix_length) {
  4735. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  4736. n_past += common_prefix_length;
  4737. }
  4738. // Zero-out next_beam probabilities to place them last in following min-heap.
  4739. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  4740. for (llama_beam & beam : beams) {
  4741. beam.shift_tokens(common_prefix_length);
  4742. fill_next_beams_by_top_probabilities(beam);
  4743. }
  4744. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  4745. beams.swap(next_beams);
  4746. renormalize_beam_probabilities(beams);
  4747. }
  4748. collapse_beams(top_beam_index());
  4749. callback(callback_data, get_beams_state(true));
  4750. }
  4751. // As beams grow, the cumulative probabilities decrease.
  4752. // Renormalize them to avoid floating point underflow.
  4753. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  4754. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  4755. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  4756. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  4757. }
  4758. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  4759. size_t top_beam_index() {
  4760. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  4761. }
  4762. // Copy (p,eob) for each beam which may have been changed by the callback.
  4763. void update_beams_from_beam_views() {
  4764. for (size_t i = 0 ; i < beams.size() ; ++i) {
  4765. beams[i].p = beam_views[i].p;
  4766. beams[i].eob = beam_views[i].eob;
  4767. }
  4768. }
  4769. };
  4770. void llama_beam_search(llama_context * ctx,
  4771. llama_beam_search_callback_fn_t callback, void * callback_data,
  4772. size_t n_beams, int n_past, int n_predict) {
  4773. assert(ctx);
  4774. const int64_t t_start_sample_us = ggml_time_us();
  4775. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  4776. beam_search_data.loop(callback, callback_data);
  4777. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  4778. ctx->n_sample++;
  4779. }
  4780. //
  4781. // quantization
  4782. //
  4783. template <typename T>
  4784. struct no_init {
  4785. T value;
  4786. no_init() { /* do nothing */ }
  4787. };
  4788. static void llama_convert_tensor_internal(
  4789. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  4790. const size_t nelements, const int nthread
  4791. ) {
  4792. if (output.size() < nelements) {
  4793. output.resize(nelements);
  4794. }
  4795. float * f32_output = (float *) output.data();
  4796. ggml_type_traits_t qtype;
  4797. if (ggml_is_quantized(tensor->type)) {
  4798. qtype = ggml_internal_get_type_traits(tensor->type);
  4799. if (qtype.to_float == NULL) {
  4800. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  4801. }
  4802. } else if (tensor->type != GGML_TYPE_F16) {
  4803. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  4804. }
  4805. if (nthread < 2) {
  4806. if (tensor->type == GGML_TYPE_F16) {
  4807. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  4808. } else if (ggml_is_quantized(tensor->type)) {
  4809. qtype.to_float(tensor->data, f32_output, nelements);
  4810. } else {
  4811. GGML_ASSERT(false); // unreachable
  4812. }
  4813. return;
  4814. }
  4815. auto block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  4816. auto block_size_bytes = ggml_type_size(tensor->type);
  4817. GGML_ASSERT(nelements % block_size == 0);
  4818. auto nblocks = nelements / block_size;
  4819. auto blocks_per_thread = nblocks / nthread;
  4820. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  4821. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  4822. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  4823. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  4824. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  4825. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  4826. if (typ == GGML_TYPE_F16) {
  4827. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  4828. } else {
  4829. qtype.to_float(inbuf, outbuf, nels);
  4830. }
  4831. };
  4832. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  4833. in_buff_offs += thr_block_bytes;
  4834. out_buff_offs += thr_elems;
  4835. }
  4836. for (auto & w : workers) { w.join(); }
  4837. workers.clear();
  4838. }
  4839. #ifdef GGML_USE_K_QUANTS
  4840. static ggml_type get_k_quant_type(
  4841. ggml_type new_type, const ggml_tensor * tensor, const llama_model & model, llama_ftype ftype, int * i_attention_wv,
  4842. int n_attention_wv, int * i_feed_forward_w2, int n_feed_forward_w2
  4843. ) {
  4844. const std::string name = ggml_get_name(tensor);
  4845. // TODO: avoid hardcoded tensor names - use the TN_* constants
  4846. const auto tn = LLM_TN(model.arch);
  4847. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  4848. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  4849. };
  4850. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  4851. int nx = tensor->ne[0];
  4852. if (model.arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  4853. new_type = GGML_TYPE_Q8_0;
  4854. }
  4855. else if (new_type != GGML_TYPE_Q8_0) {
  4856. new_type = GGML_TYPE_Q6_K;
  4857. }
  4858. } else if (name.find("attn_v.weight") != std::string::npos) {
  4859. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  4860. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  4861. new_type = *i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  4862. }
  4863. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  4864. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  4865. use_more_bits(*i_attention_wv, n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  4866. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && *i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  4867. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  4868. (*i_attention_wv < n_attention_wv/8 || *i_attention_wv >= 7*n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  4869. if (model.type == MODEL_70B) {
  4870. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  4871. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  4872. // nearly negligible increase in model size by quantizing this tensor with more bits:
  4873. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  4874. }
  4875. ++*i_attention_wv;
  4876. } else if (name.find("ffn_down.weight") != std::string::npos) {
  4877. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  4878. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  4879. new_type = *i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K
  4880. : model.arch != LLM_ARCH_FALCON || use_more_bits(*i_feed_forward_w2, n_feed_forward_w2) ? GGML_TYPE_Q4_K
  4881. : GGML_TYPE_Q3_K;
  4882. }
  4883. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  4884. new_type = model.arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  4885. }
  4886. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  4887. if (model.arch == LLM_ARCH_FALCON) {
  4888. new_type = *i_feed_forward_w2 < 2 ? GGML_TYPE_Q6_K :
  4889. use_more_bits(*i_feed_forward_w2, n_feed_forward_w2) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  4890. } else {
  4891. if (use_more_bits(*i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  4892. }
  4893. }
  4894. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(*i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  4895. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && model.arch != LLM_ARCH_FALCON && *i_feed_forward_w2 < 4) {
  4896. new_type = GGML_TYPE_Q5_K;
  4897. }
  4898. ++*i_feed_forward_w2;
  4899. } else if (name.find("attn_output.weight") != std::string::npos) {
  4900. if (model.arch != LLM_ARCH_FALCON) {
  4901. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  4902. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  4903. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  4904. } else {
  4905. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  4906. }
  4907. }
  4908. else if (name.find("attn_qkv.weight") != std::string::npos) {
  4909. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  4910. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  4911. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  4912. }
  4913. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  4914. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  4915. }
  4916. // This can be used to reduce the size of the Q5_K_S model.
  4917. // The associated PPL increase is fully in line with the size reduction
  4918. //else {
  4919. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  4920. //}
  4921. bool convert_incompatible_tensor = false;
  4922. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  4923. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  4924. int nx = tensor->ne[0];
  4925. int ny = tensor->ne[1];
  4926. if (nx % QK_K != 0) {
  4927. LLAMA_LOG_WARN("\n\n%s : tensor cols %d x %d are not divisible by %d, required for k-quants\n", __func__, nx, ny, QK_K);
  4928. convert_incompatible_tensor = true;
  4929. }
  4930. }
  4931. if (convert_incompatible_tensor) {
  4932. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  4933. new_type = GGML_TYPE_F16; //fall back to F16 instead of just failing.
  4934. LLAMA_LOG_WARN("F16 will be used for this tensor instead.\n");
  4935. } else if (name == tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  4936. new_type = GGML_TYPE_Q4_0; //fall back to Q4_0 instead of just failing.
  4937. LLAMA_LOG_WARN("Q4_0 will be used for this tensor instead.\n");
  4938. } else {
  4939. throw std::runtime_error("Unsupported tensor size encountered\n");
  4940. }
  4941. }
  4942. return new_type;
  4943. }
  4944. #endif
  4945. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  4946. ggml_type quantized_type;
  4947. llama_ftype ftype = params->ftype;
  4948. switch (params->ftype) {
  4949. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  4950. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  4951. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  4952. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  4953. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  4954. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  4955. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  4956. #ifdef GGML_USE_K_QUANTS
  4957. // K-quants
  4958. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  4959. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  4960. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  4961. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  4962. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  4963. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  4964. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  4965. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  4966. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  4967. #endif
  4968. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  4969. }
  4970. int nthread = params->nthread;
  4971. if (nthread <= 0) {
  4972. nthread = std::thread::hardware_concurrency();
  4973. }
  4974. llama_model_loader ml(fname_inp, /*use_mmap*/ false);
  4975. llama_model model;
  4976. llm_load_arch(ml, model);
  4977. llm_load_hparams(ml, model);
  4978. if (params->only_copy) {
  4979. ftype = model.ftype;
  4980. }
  4981. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  4982. struct gguf_context * ctx_out = gguf_init_empty();
  4983. // copy the KV pairs from the input file
  4984. gguf_set_kv (ctx_out, ml.ctx_gguf);
  4985. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  4986. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  4987. #ifdef GGML_USE_K_QUANTS
  4988. int n_attention_wv = 0;
  4989. int n_feed_forward_w2 = 0;
  4990. for (int i = 0; i < ml.n_tensors; ++i) {
  4991. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  4992. const std::string name = ggml_get_name(meta);
  4993. // TODO: avoid hardcoded tensor names - use the TN_* constants
  4994. if (name.find("attn_v.weight") != std::string::npos) {
  4995. ++n_attention_wv;
  4996. }
  4997. else if (name.find("ffn_down.weight") != std::string::npos) {
  4998. ++n_feed_forward_w2;
  4999. }
  5000. }
  5001. if (n_attention_wv != n_feed_forward_w2 || (uint32_t)n_attention_wv != model.hparams.n_layer) {
  5002. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  5003. __func__, n_attention_wv, n_feed_forward_w2, model.hparams.n_layer);
  5004. }
  5005. int i_attention_wv = 0;
  5006. int i_feed_forward_w2 = 0;
  5007. #endif
  5008. size_t total_size_org = 0;
  5009. size_t total_size_new = 0;
  5010. std::vector<int64_t> hist_all(1 << 4, 0);
  5011. std::vector<std::thread> workers;
  5012. workers.reserve(nthread);
  5013. std::mutex mutex;
  5014. int idx = 0;
  5015. std::vector<no_init<uint8_t>> read_data;
  5016. std::vector<no_init<uint8_t>> work;
  5017. std::vector<no_init<float>> f32_conv_buf;
  5018. // populate the original tensors so we get an initial meta data
  5019. for (int i = 0; i < ml.n_tensors; ++i) {
  5020. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  5021. gguf_add_tensor(ctx_out, meta);
  5022. }
  5023. std::ofstream fout(fname_out, std::ios::binary);
  5024. const size_t meta_size = gguf_get_meta_size(ctx_out);
  5025. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  5026. // placeholder for the meta data
  5027. ::zeros(fout, meta_size);
  5028. for (int i = 0; i < ml.n_tensors; ++i) {
  5029. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  5030. const std::string name = ggml_get_name(tensor);
  5031. if (read_data.size() < ggml_nbytes(tensor)) {
  5032. read_data.resize(ggml_nbytes(tensor));
  5033. }
  5034. tensor->data = read_data.data();
  5035. ml.load_data_for(tensor);
  5036. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  5037. ++idx, ml.n_tensors,
  5038. ggml_get_name(tensor),
  5039. llama_format_tensor_shape(tensor).c_str(),
  5040. ggml_type_name(tensor->type));
  5041. // This used to be a regex, but <regex> has an extreme cost to compile times.
  5042. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  5043. // quantize only 2D tensors
  5044. quantize &= (tensor->n_dims == 2);
  5045. quantize &= params->quantize_output_tensor || name != "output.weight";
  5046. quantize &= !params->only_copy;
  5047. enum ggml_type new_type;
  5048. void * new_data;
  5049. size_t new_size;
  5050. if (quantize) {
  5051. new_type = quantized_type;
  5052. #ifdef GGML_USE_K_QUANTS
  5053. new_type = get_k_quant_type(
  5054. new_type, tensor, model, ftype, &i_attention_wv, n_attention_wv, &i_feed_forward_w2, n_feed_forward_w2
  5055. );
  5056. #endif
  5057. // If we've decided to quantize to the same type the tensor is already
  5058. // in then there's nothing to do.
  5059. quantize = tensor->type != new_type;
  5060. }
  5061. if (!quantize) {
  5062. new_type = tensor->type;
  5063. new_data = tensor->data;
  5064. new_size = ggml_nbytes(tensor);
  5065. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  5066. } else {
  5067. const size_t nelements = ggml_nelements(tensor);
  5068. float * f32_data;
  5069. if (tensor->type == GGML_TYPE_F32) {
  5070. f32_data = (float *) tensor->data;
  5071. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  5072. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  5073. } else {
  5074. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  5075. f32_data = (float *) f32_conv_buf.data();
  5076. }
  5077. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  5078. fflush(stdout);
  5079. if (work.size() < nelements * 4) {
  5080. work.resize(nelements * 4); // upper bound on size
  5081. }
  5082. new_data = work.data();
  5083. std::array<int64_t, 1 << 4> hist_cur = {};
  5084. static const int chunk_size = 32 * 512;
  5085. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  5086. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  5087. if (nthread_use < 2) {
  5088. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  5089. } else {
  5090. size_t counter = 0;
  5091. new_size = 0;
  5092. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  5093. std::array<int64_t, 1 << 4> local_hist = {};
  5094. size_t local_size = 0;
  5095. while (true) {
  5096. std::unique_lock<std::mutex> lock(mutex);
  5097. size_t first = counter; counter += chunk_size;
  5098. if (first >= nelements) {
  5099. if (local_size > 0) {
  5100. for (int j=0; j<int(local_hist.size()); ++j) {
  5101. hist_cur[j] += local_hist[j];
  5102. }
  5103. new_size += local_size;
  5104. }
  5105. break;
  5106. }
  5107. lock.unlock();
  5108. size_t last = std::min(nelements, first + chunk_size);
  5109. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  5110. }
  5111. };
  5112. for (int it = 0; it < nthread_use - 1; ++it) {
  5113. workers.emplace_back(compute);
  5114. }
  5115. compute();
  5116. for (auto & w : workers) { w.join(); }
  5117. workers.clear();
  5118. }
  5119. LLAMA_LOG_INFO("size = %8.2f MB -> %8.2f MB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  5120. int64_t tot_count = 0;
  5121. for (size_t i = 0; i < hist_cur.size(); i++) {
  5122. hist_all[i] += hist_cur[i];
  5123. tot_count += hist_cur[i];
  5124. }
  5125. if (tot_count > 0) {
  5126. for (size_t i = 0; i < hist_cur.size(); i++) {
  5127. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  5128. }
  5129. }
  5130. LLAMA_LOG_INFO("\n");
  5131. }
  5132. total_size_org += ggml_nbytes(tensor);
  5133. total_size_new += new_size;
  5134. // update the gguf meta data as we go
  5135. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  5136. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  5137. // write tensor data + padding
  5138. fout.write((const char *) new_data, new_size);
  5139. zeros(fout, GGML_PAD(new_size, align) - new_size);
  5140. }
  5141. // go back to beginning of file and write the updated meta data
  5142. {
  5143. fout.seekp(0);
  5144. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  5145. gguf_get_meta_data(ctx_out, data.data());
  5146. fout.write((const char *) data.data(), data.size());
  5147. }
  5148. fout.close();
  5149. gguf_free(ctx_out);
  5150. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  5151. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  5152. // print histogram for all tensors
  5153. {
  5154. int64_t sum_all = 0;
  5155. for (size_t i = 0; i < hist_all.size(); i++) {
  5156. sum_all += hist_all[i];
  5157. }
  5158. if (sum_all > 0) {
  5159. LLAMA_LOG_INFO("%s: hist: ", __func__);
  5160. for (size_t i = 0; i < hist_all.size(); i++) {
  5161. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  5162. }
  5163. LLAMA_LOG_INFO("\n");
  5164. }
  5165. }
  5166. }
  5167. static int llama_apply_lora_from_file_internal(
  5168. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  5169. ) {
  5170. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  5171. const int64_t t_start_lora_us = ggml_time_us();
  5172. auto fin = std::ifstream(path_lora, std::ios::binary);
  5173. if (!fin) {
  5174. LLAMA_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_lora);
  5175. return 1;
  5176. }
  5177. // verify magic and version
  5178. {
  5179. uint32_t magic;
  5180. fin.read((char *) &magic, sizeof(magic));
  5181. uint32_t format_version;
  5182. fin.read((char *) &format_version, sizeof(format_version));
  5183. if (format_version != 1) {
  5184. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  5185. return 1;
  5186. }
  5187. }
  5188. int32_t lora_r;
  5189. int32_t lora_alpha;
  5190. fin.read((char *) &lora_r, sizeof(lora_r));
  5191. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  5192. float scaling = scale * (float)lora_alpha / (float)lora_r;
  5193. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  5194. // create a temporary ggml context to store the lora tensors
  5195. // todo: calculate size from biggest possible tensor
  5196. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  5197. struct ggml_init_params params;
  5198. params.mem_size = lora_buf.size();
  5199. params.mem_buffer = lora_buf.data();
  5200. params.no_alloc = false;
  5201. ggml_context * lora_ctx = ggml_init(params);
  5202. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  5203. // create a name -> tensor map of the model to accelerate lookups
  5204. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  5205. for (const auto & kv : model.tensors_by_name) {
  5206. model_tensors.insert(kv);
  5207. }
  5208. // load base model
  5209. std::unique_ptr<llama_model_loader> ml;
  5210. ggml_context * base_ctx = NULL;
  5211. std::vector<uint8_t> base_buf;
  5212. if (path_base_model) {
  5213. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  5214. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  5215. size_t ctx_size;
  5216. size_t mmapped_size;
  5217. ml->calc_sizes(ctx_size, mmapped_size);
  5218. base_buf.resize(ctx_size);
  5219. ggml_init_params base_params;
  5220. base_params.mem_size = base_buf.size();
  5221. base_params.mem_buffer = base_buf.data();
  5222. base_params.no_alloc = ml->use_mmap;
  5223. base_ctx = ggml_init(base_params);
  5224. // maybe this should in llama_model_loader
  5225. if (ml->use_mmap) {
  5226. ml->mapping.reset(new llama_mmap(&ml->file, /* prefetch */ 0, ggml_is_numa()));
  5227. }
  5228. }
  5229. // read tensors and apply
  5230. bool warned = false;
  5231. int n_tensors = 0;
  5232. std::vector<uint8_t> work_buffer;
  5233. while (true) {
  5234. int32_t n_dims;
  5235. int32_t length;
  5236. int32_t ftype;
  5237. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  5238. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  5239. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  5240. if (fin.eof()) {
  5241. break;
  5242. }
  5243. int32_t ne[2] = { 1, 1 };
  5244. for (int i = 0; i < n_dims; ++i) {
  5245. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  5246. }
  5247. std::string name;
  5248. {
  5249. char buf[1024];
  5250. fin.read(buf, length);
  5251. name = std::string(buf, length);
  5252. }
  5253. // check for lora suffix and get the type of tensor
  5254. const std::string lora_suffix = ".lora";
  5255. size_t pos = name.rfind(lora_suffix);
  5256. if (pos == std::string::npos) {
  5257. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  5258. return 1;
  5259. }
  5260. std::string lora_type = name.substr(pos + lora_suffix.length());
  5261. std::string base_name = name;
  5262. base_name.erase(pos);
  5263. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  5264. if (model_tensors.find(base_name) == model_tensors.end()) {
  5265. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  5266. return 1;
  5267. }
  5268. // create ggml tensor
  5269. ggml_type wtype;
  5270. switch (ftype) {
  5271. case 0: wtype = GGML_TYPE_F32; break;
  5272. case 1: wtype = GGML_TYPE_F16; break;
  5273. default:
  5274. {
  5275. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  5276. __func__, ftype);
  5277. return false;
  5278. }
  5279. }
  5280. ggml_tensor * lora_tensor;
  5281. if (n_dims == 2) {
  5282. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  5283. }
  5284. else {
  5285. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  5286. return 1;
  5287. }
  5288. ggml_set_name(lora_tensor, "lora_tensor");
  5289. // load tensor data
  5290. size_t offset = fin.tellg();
  5291. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  5292. offset = (offset + 31) & -32;
  5293. fin.seekg(offset);
  5294. fin.read((char*)lora_tensor->data, tensor_data_size);
  5295. lora_tensors[name] = lora_tensor;
  5296. // check if we have both A and B tensors and apply
  5297. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  5298. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  5299. ggml_tensor * dest_t = model_tensors[base_name];
  5300. offload_func_t offload_func = llama_nop;
  5301. offload_func_t offload_func_force_inplace = llama_nop;
  5302. #ifdef GGML_USE_CUBLAS
  5303. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  5304. if (dest_t->type != GGML_TYPE_F16) {
  5305. throw std::runtime_error(format(
  5306. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  5307. }
  5308. offload_func = ggml_cuda_assign_buffers;
  5309. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  5310. }
  5311. #endif // GGML_USE_CUBLAS
  5312. ggml_tensor * base_t;
  5313. if (ml) {
  5314. struct gguf_context * ctx_gguf = ml->ctx_gguf;
  5315. // load from base model
  5316. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  5317. // TODO: throw
  5318. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  5319. return 1;
  5320. }
  5321. // TODO: not tested!! maybe not working!
  5322. base_t = ml->create_tensor(base_ctx, base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  5323. ml->load_data_for(base_t);
  5324. } else {
  5325. base_t = dest_t;
  5326. }
  5327. if (ggml_is_quantized(base_t->type)) {
  5328. if (!warned) {
  5329. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  5330. "use a f16 or f32 base model with --lora-base\n", __func__);
  5331. warned = true;
  5332. }
  5333. }
  5334. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  5335. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  5336. ggml_set_name(loraA, "loraA");
  5337. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  5338. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  5339. ggml_set_name(loraB, "loraB");
  5340. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  5341. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  5342. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  5343. return 1;
  5344. }
  5345. // w = w + BA*s
  5346. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  5347. offload_func(BA);
  5348. ggml_set_name(BA, "BA");
  5349. if (scaling != 1.0f) {
  5350. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  5351. ggml_set_name(scale_tensor, "scale_tensor");
  5352. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  5353. offload_func(BA);
  5354. ggml_set_name(BA, "BA_scaled");
  5355. }
  5356. ggml_tensor * r;
  5357. if (base_t == dest_t) {
  5358. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  5359. offload_func_force_inplace(r);
  5360. ggml_set_name(r, "r_add_inplace");
  5361. }
  5362. else {
  5363. r = ggml_add(lora_ctx, base_t, BA);
  5364. offload_func(r);
  5365. ggml_set_name(r, "r_add");
  5366. r = ggml_cpy(lora_ctx, r, dest_t);
  5367. offload_func(r);
  5368. ggml_set_name(r, "r_cpy");
  5369. }
  5370. struct ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  5371. ggml_build_forward_expand(gf, r);
  5372. ggml_graph_compute_helper(work_buffer, gf, n_threads);
  5373. // we won't need these tensors again, reset the context to save memory
  5374. ggml_free(lora_ctx);
  5375. lora_ctx = ggml_init(params);
  5376. lora_tensors.clear();
  5377. n_tensors++;
  5378. if (n_tensors % 4 == 0) {
  5379. LLAMA_LOG_INFO(".");
  5380. }
  5381. }
  5382. }
  5383. // TODO: this should be in a destructor, it will leak on failure
  5384. ggml_free(lora_ctx);
  5385. if (base_ctx) {
  5386. ggml_free(base_ctx);
  5387. }
  5388. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  5389. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  5390. return 0;
  5391. }
  5392. //
  5393. // interface implementation
  5394. //
  5395. struct llama_model_params llama_model_default_params() {
  5396. struct llama_model_params result = {
  5397. /*.n_gpu_layers =*/ 0,
  5398. /*.main_gpu =*/ 0,
  5399. /*.tensor_split =*/ nullptr,
  5400. /*.progress_callback =*/ nullptr,
  5401. /*.progress_callback_user_data =*/ nullptr,
  5402. /*.vocab_only =*/ false,
  5403. /*.use_mmap =*/ true,
  5404. /*.use_mlock =*/ false,
  5405. };
  5406. #ifdef GGML_USE_METAL
  5407. result.n_gpu_layers = 1;
  5408. #endif
  5409. return result;
  5410. }
  5411. struct llama_context_params llama_context_default_params() {
  5412. struct llama_context_params result = {
  5413. /*.seed =*/ LLAMA_DEFAULT_SEED,
  5414. /*.n_ctx =*/ 512,
  5415. /*.n_batch =*/ 512,
  5416. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  5417. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  5418. /*.rope_freq_base =*/ 0.0f,
  5419. /*.rope_freq_scale =*/ 0.0f,
  5420. /*.mul_mat_q =*/ true,
  5421. /*.f16_kv =*/ true,
  5422. /*.logits_all =*/ false,
  5423. /*.embedding =*/ false,
  5424. };
  5425. return result;
  5426. }
  5427. struct llama_model_quantize_params llama_model_quantize_default_params() {
  5428. struct llama_model_quantize_params result = {
  5429. /*.nthread =*/ 0,
  5430. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  5431. /*.allow_requantize =*/ false,
  5432. /*.quantize_output_tensor =*/ true,
  5433. /*.only_copy =*/ false,
  5434. };
  5435. return result;
  5436. }
  5437. int llama_max_devices(void) {
  5438. return LLAMA_MAX_DEVICES;
  5439. }
  5440. bool llama_mmap_supported(void) {
  5441. return llama_mmap::SUPPORTED;
  5442. }
  5443. bool llama_mlock_supported(void) {
  5444. return llama_mlock::SUPPORTED;
  5445. }
  5446. void llama_backend_init(bool numa) {
  5447. ggml_time_init();
  5448. // needed to initialize f16 tables
  5449. {
  5450. struct ggml_init_params params = { 0, NULL, false };
  5451. struct ggml_context * ctx = ggml_init(params);
  5452. ggml_free(ctx);
  5453. }
  5454. if (numa) {
  5455. ggml_numa_init();
  5456. }
  5457. #ifdef GGML_USE_MPI
  5458. ggml_mpi_backend_init();
  5459. #endif
  5460. }
  5461. void llama_backend_free(void) {
  5462. #ifdef GGML_USE_MPI
  5463. ggml_mpi_backend_free();
  5464. #endif
  5465. }
  5466. int64_t llama_time_us(void) {
  5467. return ggml_time_us();
  5468. }
  5469. struct llama_model * llama_load_model_from_file(
  5470. const char * path_model,
  5471. struct llama_model_params params) {
  5472. ggml_time_init();
  5473. llama_model * model = new llama_model;
  5474. unsigned cur_percentage = 0;
  5475. if (params.progress_callback == NULL) {
  5476. params.progress_callback_user_data = &cur_percentage;
  5477. params.progress_callback = [](float progress, void * ctx) {
  5478. unsigned * cur_percentage_p = (unsigned *) ctx;
  5479. unsigned percentage = (unsigned) (100 * progress);
  5480. while (percentage > *cur_percentage_p) {
  5481. *cur_percentage_p = percentage;
  5482. LLAMA_LOG_INFO(".");
  5483. if (percentage >= 100) {
  5484. LLAMA_LOG_INFO("\n");
  5485. }
  5486. }
  5487. };
  5488. }
  5489. if (!llama_model_load(path_model, *model, params.n_gpu_layers,
  5490. params.main_gpu, params.tensor_split,
  5491. params.use_mmap, params.use_mlock, params.vocab_only,
  5492. params.progress_callback, params.progress_callback_user_data)) {
  5493. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  5494. delete model;
  5495. return nullptr;
  5496. }
  5497. return model;
  5498. }
  5499. void llama_free_model(struct llama_model * model) {
  5500. delete model;
  5501. }
  5502. struct llama_context * llama_new_context_with_model(
  5503. struct llama_model * model,
  5504. struct llama_context_params params) {
  5505. if (!model) {
  5506. return nullptr;
  5507. }
  5508. llama_context * ctx = new llama_context(*model);
  5509. const auto & hparams = model->hparams;
  5510. auto & cparams = ctx->cparams;
  5511. cparams.n_batch = params.n_batch;
  5512. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  5513. cparams.rope_freq_base = params.rope_freq_base == 0 ? hparams.rope_freq_base_train : params.rope_freq_base;
  5514. cparams.rope_freq_scale = params.rope_freq_scale == 0 ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  5515. cparams.n_threads = params.n_threads;
  5516. cparams.n_threads_batch = params.n_threads_batch;
  5517. cparams.mul_mat_q = params.mul_mat_q;
  5518. if (params.seed == LLAMA_DEFAULT_SEED) {
  5519. params.seed = time(NULL);
  5520. }
  5521. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  5522. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  5523. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  5524. ctx->rng = std::mt19937(params.seed);
  5525. ctx->logits_all = params.logits_all;
  5526. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  5527. // reserve memory for context buffers
  5528. if (!hparams.vocab_only) {
  5529. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, cparams.n_ctx, model->n_gpu_layers)) {
  5530. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  5531. llama_free(ctx);
  5532. return nullptr;
  5533. }
  5534. {
  5535. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  5536. LLAMA_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  5537. }
  5538. // resized during inference
  5539. if (params.logits_all) {
  5540. ctx->logits.reserve(cparams.n_ctx*hparams.n_vocab);
  5541. } else {
  5542. ctx->logits.reserve(hparams.n_vocab);
  5543. }
  5544. if (params.embedding){
  5545. ctx->embedding.resize(hparams.n_embd);
  5546. }
  5547. {
  5548. static const size_t tensor_alignment = 32;
  5549. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  5550. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  5551. // create measure allocator
  5552. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  5553. // build worst-case graph
  5554. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  5555. int n_past = cparams.n_ctx - n_tokens;
  5556. llama_token token = llama_token_bos(ctx); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  5557. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  5558. #ifdef GGML_USE_METAL
  5559. if (model->n_gpu_layers > 0) {
  5560. ctx->ctx_metal = ggml_metal_init(1);
  5561. if (!ctx->ctx_metal) {
  5562. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  5563. llama_free(ctx);
  5564. return NULL;
  5565. }
  5566. ggml_metal_log_set_callback(llama_log_callback_default, NULL);
  5567. //ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  5568. //ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  5569. }
  5570. #endif
  5571. // measure memory requirements for the graph
  5572. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  5573. LLAMA_LOG_INFO("%s: compute buffer total size = %.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  5574. // recreate allocator with exact memory requirements
  5575. ggml_allocr_free(ctx->alloc);
  5576. ctx->buf_alloc.resize(alloc_size);
  5577. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  5578. #ifdef GGML_USE_METAL
  5579. if (ctx->ctx_metal) {
  5580. //ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  5581. }
  5582. #endif
  5583. #ifdef GGML_USE_CUBLAS
  5584. ggml_cuda_set_scratch_size(alloc_size);
  5585. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
  5586. // calculate total VRAM usage
  5587. auto add_tensor = [](const ggml_tensor * t, size_t & size) {
  5588. if (t->backend == GGML_BACKEND_GPU || t->backend == GGML_BACKEND_GPU_SPLIT) {
  5589. size += ggml_nbytes(t);
  5590. }
  5591. };
  5592. size_t model_vram_size = 0;
  5593. for (const auto & kv : model->tensors_by_name) {
  5594. add_tensor(kv.second, model_vram_size);
  5595. }
  5596. size_t kv_vram_size = 0;
  5597. add_tensor(ctx->kv_self.k, kv_vram_size);
  5598. add_tensor(ctx->kv_self.v, kv_vram_size);
  5599. size_t ctx_vram_size = alloc_size + kv_vram_size;
  5600. size_t total_vram_size = model_vram_size + ctx_vram_size;
  5601. LLAMA_LOG_INFO("%s: total VRAM used: %.2f MB (model: %.2f MB, context: %.2f MB)\n", __func__,
  5602. total_vram_size / 1024.0 / 1024.0,
  5603. model_vram_size / 1024.0 / 1024.0,
  5604. ctx_vram_size / 1024.0 / 1024.0);
  5605. #endif
  5606. }
  5607. #ifdef GGML_USE_METAL
  5608. if (model->n_gpu_layers > 0) {
  5609. // this allocates all Metal resources and memory buffers
  5610. void * data_ptr = NULL;
  5611. size_t data_size = 0;
  5612. if (ctx->model.mapping) {
  5613. data_ptr = ctx->model.mapping->addr;
  5614. data_size = ctx->model.mapping->size;
  5615. } else {
  5616. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  5617. data_size = ggml_get_mem_size (ctx->model.ctx);
  5618. }
  5619. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  5620. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  5621. #define LLAMA_METAL_CHECK_BUF(result) \
  5622. if (!(result)) { \
  5623. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  5624. llama_free(ctx); \
  5625. return NULL; \
  5626. }
  5627. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  5628. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  5629. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  5630. #undef LLAMA_METAL_CHECK_BUF
  5631. }
  5632. #endif
  5633. }
  5634. #ifdef GGML_USE_MPI
  5635. ctx->ctx_mpi = ggml_mpi_init();
  5636. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  5637. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  5638. // TODO: needs fix after #3228
  5639. GGML_ASSERT(false && "not implemented");
  5640. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  5641. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  5642. llama_backend_free();
  5643. exit(1);
  5644. }
  5645. #endif
  5646. return ctx;
  5647. }
  5648. void llama_free(struct llama_context * ctx) {
  5649. delete ctx;
  5650. }
  5651. const llama_model * llama_get_model(const struct llama_context * ctx) {
  5652. return &ctx->model;
  5653. }
  5654. int llama_n_ctx(const struct llama_context * ctx) {
  5655. return ctx->cparams.n_ctx;
  5656. }
  5657. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  5658. return model->vocab.type;
  5659. }
  5660. int llama_n_vocab(const struct llama_model * model) {
  5661. return model->vocab.id_to_token.size();
  5662. }
  5663. int llama_n_ctx_train(const struct llama_model * model) {
  5664. return model->hparams.n_ctx_train;
  5665. }
  5666. int llama_n_embd(const struct llama_model * model) {
  5667. return model->hparams.n_embd;
  5668. }
  5669. int llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  5670. return snprintf(buf, buf_size, "%s %s %s",
  5671. llama_model_arch_name(model->arch).c_str(),
  5672. llama_model_type_name(model->type),
  5673. llama_model_ftype_name(model->ftype).c_str());
  5674. }
  5675. uint64_t llama_model_size(const struct llama_model * model) {
  5676. uint64_t size = 0;
  5677. for (const auto & it : model->tensors_by_name) {
  5678. size += ggml_nbytes(it.second);
  5679. }
  5680. return size;
  5681. }
  5682. uint64_t llama_model_n_params(const struct llama_model * model) {
  5683. uint64_t nparams = 0;
  5684. for (const auto & it : model->tensors_by_name) {
  5685. nparams += ggml_nelements(it.second);
  5686. }
  5687. return nparams;
  5688. }
  5689. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  5690. return ggml_get_tensor(model->ctx, name);
  5691. }
  5692. int llama_model_quantize(
  5693. const char * fname_inp,
  5694. const char * fname_out,
  5695. const llama_model_quantize_params * params) {
  5696. try {
  5697. llama_model_quantize_internal(fname_inp, fname_out, params);
  5698. return 0;
  5699. } catch (const std::exception & err) {
  5700. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  5701. return 1;
  5702. }
  5703. }
  5704. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int n_threads) {
  5705. try {
  5706. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  5707. } catch (const std::exception & err) {
  5708. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  5709. return 1;
  5710. }
  5711. }
  5712. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int n_threads) {
  5713. try {
  5714. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  5715. } catch (const std::exception & err) {
  5716. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  5717. return 1;
  5718. }
  5719. }
  5720. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  5721. return ctx->kv_self.head;
  5722. }
  5723. void llama_kv_cache_tokens_rm(struct llama_context * ctx, int32_t c0, int32_t c1) {
  5724. llama_kv_cache_tokens_rm(ctx->kv_self, c0, c1);
  5725. }
  5726. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  5727. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  5728. }
  5729. void llama_kv_cache_seq_cp(struct llama_context * ctx, llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
  5730. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  5731. }
  5732. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  5733. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  5734. }
  5735. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  5736. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  5737. }
  5738. // Returns the *maximum* size of the state
  5739. size_t llama_get_state_size(const struct llama_context * ctx) {
  5740. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  5741. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  5742. const size_t s_rng_size = sizeof(size_t);
  5743. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  5744. const size_t s_logits_capacity = sizeof(size_t);
  5745. const size_t s_logits_size = sizeof(size_t);
  5746. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  5747. const size_t s_embedding_size = sizeof(size_t);
  5748. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  5749. const size_t s_kv_size = sizeof(size_t);
  5750. const size_t s_kv_ntok = sizeof(int);
  5751. const size_t s_kv = ctx->kv_self.buf.size;
  5752. const size_t s_total = (
  5753. + s_rng_size
  5754. + s_rng
  5755. + s_logits_capacity
  5756. + s_logits_size
  5757. + s_logits
  5758. + s_embedding_size
  5759. + s_embedding
  5760. + s_kv_size
  5761. + s_kv_ntok
  5762. + s_kv
  5763. );
  5764. return s_total;
  5765. }
  5766. // llama_context_data
  5767. struct llama_data_context {
  5768. virtual void write(const void * src, size_t size) = 0;
  5769. virtual size_t get_size_written() = 0;
  5770. virtual ~llama_data_context() = default;
  5771. };
  5772. struct llama_data_buffer_context : llama_data_context {
  5773. uint8_t * ptr;
  5774. size_t size_written = 0;
  5775. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  5776. void write(const void * src, size_t size) override {
  5777. memcpy(ptr, src, size);
  5778. ptr += size;
  5779. size_written += size;
  5780. }
  5781. size_t get_size_written() override {
  5782. return size_written;
  5783. }
  5784. };
  5785. struct llama_data_file_context : llama_data_context {
  5786. llama_file * file;
  5787. size_t size_written = 0;
  5788. llama_data_file_context(llama_file * f) : file(f) {}
  5789. void write(const void * src, size_t size) override {
  5790. file->write_raw(src, size);
  5791. size_written += size;
  5792. }
  5793. size_t get_size_written() override {
  5794. return size_written;
  5795. }
  5796. };
  5797. /** copy state data into either a buffer or file depending on the passed in context
  5798. *
  5799. * file context:
  5800. * llama_file file("/path", "wb");
  5801. * llama_data_file_context data_ctx(&file);
  5802. * llama_copy_state_data(ctx, &data_ctx);
  5803. *
  5804. * buffer context:
  5805. * std::vector<uint8_t> buf(max_size, 0);
  5806. * llama_data_buffer_context data_ctx(&buf.data());
  5807. * llama_copy_state_data(ctx, &data_ctx);
  5808. *
  5809. */
  5810. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  5811. // TODO: does not support multi-sequence states
  5812. {
  5813. const auto & kv_self = ctx->kv_self;
  5814. for (uint32_t i = 0; i < kv_self.head; ++i) {
  5815. GGML_ASSERT(kv_self.cells[i].pos == (int32_t) i);
  5816. GGML_ASSERT(kv_self.cells[i].seq_id.size() == 1);
  5817. GGML_ASSERT(kv_self.cells[i].has_seq_id(0));
  5818. }
  5819. }
  5820. // copy rng
  5821. {
  5822. std::stringstream rng_ss;
  5823. rng_ss << ctx->rng;
  5824. const size_t rng_size = rng_ss.str().size();
  5825. char rng_buf[LLAMA_MAX_RNG_STATE];
  5826. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  5827. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  5828. data_ctx->write(&rng_size, sizeof(rng_size));
  5829. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  5830. }
  5831. // copy logits
  5832. {
  5833. const size_t logits_cap = ctx->logits.capacity();
  5834. const size_t logits_size = ctx->logits.size();
  5835. data_ctx->write(&logits_cap, sizeof(logits_cap));
  5836. data_ctx->write(&logits_size, sizeof(logits_size));
  5837. if (logits_size) {
  5838. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  5839. }
  5840. // If there is a gap between the size and the capacity, write padding
  5841. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  5842. if (padding_size > 0) {
  5843. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  5844. data_ctx->write(padding.data(), padding_size);
  5845. }
  5846. }
  5847. // copy embeddings
  5848. {
  5849. const size_t embedding_size = ctx->embedding.size();
  5850. data_ctx->write(&embedding_size, sizeof(embedding_size));
  5851. if (embedding_size) {
  5852. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  5853. }
  5854. }
  5855. // copy kv cache
  5856. {
  5857. const auto & kv_self = ctx->kv_self;
  5858. const auto & hparams = ctx->model.hparams;
  5859. const auto & cparams = ctx->cparams;
  5860. const int n_layer = hparams.n_layer;
  5861. const int n_embd = hparams.n_embd_gqa();
  5862. const int n_ctx = cparams.n_ctx;
  5863. const size_t kv_size = kv_self.buf.size;
  5864. const int kv_ntok = kv_self.head;
  5865. data_ctx->write(&kv_size, sizeof(kv_size));
  5866. data_ctx->write(&kv_ntok, sizeof(kv_ntok));
  5867. if (kv_size) {
  5868. const size_t elt_size = ggml_element_size(kv_self.k);
  5869. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  5870. ggml_cgraph gf{};
  5871. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  5872. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  5873. kout3d->data = kout3d_data.data();
  5874. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  5875. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  5876. vout3d->data = vout3d_data.data();
  5877. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  5878. n_embd, kv_ntok, n_layer,
  5879. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  5880. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  5881. kv_ntok, n_embd, n_layer,
  5882. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  5883. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  5884. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  5885. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  5886. ggml_free(cpy_ctx);
  5887. // our data is now in the kout3d_data and vout3d_data buffers
  5888. // write them to file
  5889. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  5890. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  5891. }
  5892. }
  5893. }
  5894. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  5895. llama_data_buffer_context data_ctx(dst);
  5896. llama_copy_state_data_internal(ctx, &data_ctx);
  5897. return data_ctx.get_size_written();
  5898. }
  5899. // Sets the state reading from the specified source address
  5900. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  5901. uint8_t * inp = src;
  5902. // set rng
  5903. {
  5904. size_t rng_size;
  5905. char rng_buf[LLAMA_MAX_RNG_STATE];
  5906. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  5907. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  5908. std::stringstream rng_ss;
  5909. rng_ss.str(std::string(&rng_buf[0], rng_size));
  5910. rng_ss >> ctx->rng;
  5911. GGML_ASSERT(!rng_ss.fail());
  5912. }
  5913. // set logits
  5914. {
  5915. size_t logits_cap;
  5916. size_t logits_size;
  5917. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  5918. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  5919. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  5920. if (logits_size) {
  5921. ctx->logits.resize(logits_size);
  5922. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  5923. }
  5924. inp += logits_cap * sizeof(float);
  5925. }
  5926. // set embeddings
  5927. {
  5928. size_t embedding_size;
  5929. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  5930. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  5931. if (embedding_size) {
  5932. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  5933. inp += embedding_size * sizeof(float);
  5934. }
  5935. }
  5936. // set kv cache
  5937. {
  5938. const auto & kv_self = ctx->kv_self;
  5939. const auto & hparams = ctx->model.hparams;
  5940. const auto & cparams = ctx->cparams;
  5941. const int n_layer = hparams.n_layer;
  5942. const int n_embd = hparams.n_embd_gqa();
  5943. const int n_ctx = cparams.n_ctx;
  5944. size_t kv_size;
  5945. int kv_ntok;
  5946. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  5947. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  5948. if (kv_size) {
  5949. GGML_ASSERT(kv_self.buf.size == kv_size);
  5950. const size_t elt_size = ggml_element_size(kv_self.k);
  5951. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  5952. ggml_cgraph gf{};
  5953. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  5954. kin3d->data = (void *) inp;
  5955. inp += ggml_nbytes(kin3d);
  5956. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  5957. vin3d->data = (void *) inp;
  5958. inp += ggml_nbytes(vin3d);
  5959. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  5960. n_embd, kv_ntok, n_layer,
  5961. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  5962. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  5963. kv_ntok, n_embd, n_layer,
  5964. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  5965. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  5966. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  5967. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  5968. ggml_free(cpy_ctx);
  5969. }
  5970. ctx->kv_self.head = kv_ntok;
  5971. ctx->kv_self.size = kv_size;
  5972. }
  5973. const size_t nread = inp - src;
  5974. const size_t max_size = llama_get_state_size(ctx);
  5975. GGML_ASSERT(nread <= max_size);
  5976. return nread;
  5977. }
  5978. static bool llama_load_session_file_internal(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  5979. llama_file file(path_session, "rb");
  5980. // sanity checks
  5981. {
  5982. const uint32_t magic = file.read_u32();
  5983. const uint32_t version = file.read_u32();
  5984. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  5985. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  5986. return false;
  5987. }
  5988. llama_hparams session_hparams;
  5989. file.read_raw(&session_hparams, sizeof(llama_hparams));
  5990. if (session_hparams != ctx->model.hparams) {
  5991. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  5992. return false;
  5993. }
  5994. }
  5995. // load the prompt
  5996. {
  5997. const uint32_t n_token_count = file.read_u32();
  5998. if (n_token_count > n_token_capacity) {
  5999. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  6000. return false;
  6001. }
  6002. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  6003. *n_token_count_out = n_token_count;
  6004. }
  6005. // restore the context state
  6006. {
  6007. const size_t n_state_size_cur = file.size - file.tell();
  6008. const size_t n_state_size_max = llama_get_state_size(ctx);
  6009. if (n_state_size_cur > n_state_size_max) {
  6010. LLAMA_LOG_ERROR("%s : the state size in session file is too big! max %zu, got %zu\n", __func__, n_state_size_max, n_state_size_cur);
  6011. return false;
  6012. }
  6013. std::vector<uint8_t> state_data(n_state_size_max);
  6014. file.read_raw(state_data.data(), n_state_size_cur);
  6015. llama_set_state_data(ctx, state_data.data());
  6016. }
  6017. return true;
  6018. }
  6019. bool llama_load_session_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  6020. try {
  6021. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  6022. } catch (const std::exception & err) {
  6023. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  6024. return false;
  6025. }
  6026. }
  6027. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  6028. llama_file file(path_session, "wb");
  6029. file.write_u32(LLAMA_SESSION_MAGIC);
  6030. file.write_u32(LLAMA_SESSION_VERSION);
  6031. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  6032. // save the prompt
  6033. file.write_u32((uint32_t) n_token_count);
  6034. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  6035. // save the context state using stream saving
  6036. llama_data_file_context data_ctx(&file);
  6037. llama_copy_state_data_internal(ctx, &data_ctx);
  6038. return true;
  6039. }
  6040. int llama_eval(
  6041. struct llama_context * ctx,
  6042. llama_token * tokens,
  6043. int32_t n_tokens,
  6044. int n_past) {
  6045. llama_kv_cache_tokens_rm(ctx->kv_self, n_past, -1);
  6046. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  6047. if (ret < 0) {
  6048. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  6049. }
  6050. return ret;
  6051. }
  6052. int llama_eval_embd(
  6053. struct llama_context * ctx,
  6054. float * embd,
  6055. int32_t n_tokens,
  6056. int n_past) {
  6057. llama_kv_cache_tokens_rm(ctx->kv_self, n_past, -1);
  6058. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, n_past, 1, 0, };
  6059. const int ret = llama_decode_internal(*ctx, batch);
  6060. if (ret < 0) {
  6061. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  6062. }
  6063. return ret;
  6064. }
  6065. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  6066. ctx->cparams.n_threads = n_threads;
  6067. ctx->cparams.n_threads_batch = n_threads_batch;
  6068. }
  6069. struct llama_batch llama_batch_get_one(
  6070. llama_token * tokens,
  6071. int32_t n_tokens,
  6072. llama_pos pos_0,
  6073. llama_seq_id seq_id) {
  6074. return {
  6075. /*n_tokens =*/ n_tokens,
  6076. /*tokens =*/ tokens,
  6077. /*embd =*/ nullptr,
  6078. /*pos =*/ nullptr,
  6079. /*seq_id =*/ nullptr,
  6080. /*logits =*/ nullptr,
  6081. /*all_pos_0 =*/ pos_0,
  6082. /*all_pos_1 =*/ 1,
  6083. /*all_seq_id =*/ seq_id,
  6084. };
  6085. }
  6086. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd) {
  6087. llama_batch batch = { -1, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  6088. if (embd) {
  6089. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  6090. } else {
  6091. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  6092. }
  6093. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  6094. batch.seq_id = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_tokens);
  6095. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  6096. return batch;
  6097. }
  6098. void llama_batch_free(struct llama_batch batch) {
  6099. if (batch.token) free(batch.token);
  6100. if (batch.embd) free(batch.embd);
  6101. if (batch.pos) free(batch.pos);
  6102. if (batch.seq_id) free(batch.seq_id);
  6103. if (batch.logits) free(batch.logits);
  6104. }
  6105. int llama_decode(
  6106. struct llama_context * ctx,
  6107. struct llama_batch batch) {
  6108. const int ret = llama_decode_internal(*ctx, batch);
  6109. if (ret < 0) {
  6110. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  6111. }
  6112. return ret;
  6113. }
  6114. float * llama_get_logits(struct llama_context * ctx) {
  6115. return ctx->logits.data();
  6116. }
  6117. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  6118. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  6119. }
  6120. float * llama_get_embeddings(struct llama_context * ctx) {
  6121. return ctx->embedding.data();
  6122. }
  6123. const char * llama_token_get_text(const struct llama_context * ctx, llama_token token) {
  6124. return ctx->model.vocab.id_to_token[token].text.c_str();
  6125. }
  6126. float llama_token_get_score(const struct llama_context * ctx, llama_token token) {
  6127. return ctx->model.vocab.id_to_token[token].score;
  6128. }
  6129. llama_token_type llama_token_get_type(const struct llama_context * ctx, llama_token token) {
  6130. return ctx->model.vocab.id_to_token[token].type;
  6131. }
  6132. llama_token llama_token_bos(const struct llama_context * ctx) {
  6133. return ctx->model.vocab.special_bos_id;
  6134. }
  6135. llama_token llama_token_eos(const struct llama_context * ctx) {
  6136. return ctx->model.vocab.special_eos_id;
  6137. }
  6138. llama_token llama_token_nl(const struct llama_context * ctx) {
  6139. return ctx->model.vocab.linefeed_id;
  6140. }
  6141. int llama_tokenize(
  6142. const struct llama_model * model,
  6143. const char * text,
  6144. int text_len,
  6145. llama_token * tokens,
  6146. int n_max_tokens,
  6147. bool add_bos) {
  6148. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos);
  6149. if (n_max_tokens < (int) res.size()) {
  6150. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  6151. return -((int) res.size());
  6152. }
  6153. for (size_t i = 0; i < res.size(); i++) {
  6154. tokens[i] = res[i];
  6155. }
  6156. return res.size();
  6157. }
  6158. // does not write null-terminator to buf
  6159. int llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int length) {
  6160. if (0 <= token && token < llama_n_vocab(model)) {
  6161. if (llama_is_normal_token(model->vocab, token)) {
  6162. std::string result = model->vocab.id_to_token[token].text;
  6163. if (llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM) {
  6164. llama_unescape_whitespace(result);
  6165. }
  6166. if (length < (int) result.length()) {
  6167. return -result.length();
  6168. }
  6169. memcpy(buf, result.c_str(), result.length());
  6170. return result.length();
  6171. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  6172. if (length < 3) {
  6173. return -3;
  6174. }
  6175. buf[0] = '\xe2';
  6176. buf[1] = '\x96';
  6177. buf[2] = '\x85';
  6178. return 3;
  6179. } else if (llama_is_control_token(model->vocab, token)) {
  6180. // do nothing
  6181. } else if (llama_is_byte_token(model->vocab, token)) {
  6182. if (length < 1) {
  6183. return -1;
  6184. }
  6185. buf[0] = llama_token_to_byte(model->vocab, token);
  6186. return 1;
  6187. }
  6188. }
  6189. return 0;
  6190. }
  6191. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  6192. struct llama_timings result = {
  6193. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  6194. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  6195. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  6196. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  6197. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  6198. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  6199. /*.n_sample =*/ std::max(1, ctx->n_sample),
  6200. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  6201. /*.n_eval =*/ std::max(1, ctx->n_eval),
  6202. };
  6203. return result;
  6204. }
  6205. void llama_print_timings(struct llama_context * ctx) {
  6206. const llama_timings timings = llama_get_timings(ctx);
  6207. LLAMA_LOG_INFO("\n");
  6208. LLAMA_LOG_INFO("%s: load time = %8.2f ms\n", __func__, timings.t_load_ms);
  6209. LLAMA_LOG_INFO("%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  6210. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  6211. LLAMA_LOG_INFO("%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  6212. __func__, timings.t_p_eval_ms, timings.n_p_eval, timings.t_p_eval_ms / timings.n_p_eval, 1e3 / timings.t_p_eval_ms * timings.n_p_eval);
  6213. LLAMA_LOG_INFO("%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  6214. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  6215. LLAMA_LOG_INFO("%s: total time = %8.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  6216. }
  6217. void llama_reset_timings(struct llama_context * ctx) {
  6218. ctx->t_start_us = ggml_time_us();
  6219. ctx->t_sample_us = ctx->n_sample = 0;
  6220. ctx->t_eval_us = ctx->n_eval = 0;
  6221. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  6222. }
  6223. const char * llama_print_system_info(void) {
  6224. static std::string s;
  6225. s = "";
  6226. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  6227. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  6228. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  6229. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  6230. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  6231. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  6232. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  6233. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  6234. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  6235. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  6236. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  6237. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  6238. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  6239. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  6240. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  6241. return s.c_str();
  6242. }
  6243. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  6244. fprintf(stream, "\n");
  6245. fprintf(stream, "###########\n");
  6246. fprintf(stream, "# Timings #\n");
  6247. fprintf(stream, "###########\n");
  6248. fprintf(stream, "\n");
  6249. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  6250. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  6251. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  6252. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  6253. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  6254. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  6255. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  6256. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  6257. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  6258. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  6259. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  6260. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  6261. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  6262. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  6263. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  6264. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  6265. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  6266. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  6267. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  6268. }
  6269. // For internal test use
  6270. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  6271. struct llama_context * ctx
  6272. ) {
  6273. return ctx->model.tensors_by_name;
  6274. }
  6275. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  6276. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  6277. g_state.log_callback_user_data = user_data;
  6278. }
  6279. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  6280. va_list args_copy;
  6281. va_copy(args_copy, args);
  6282. char buffer[128];
  6283. int len = vsnprintf(buffer, 128, format, args);
  6284. if (len < 128) {
  6285. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  6286. } else {
  6287. char* buffer2 = new char[len+1];
  6288. vsnprintf(buffer2, len+1, format, args_copy);
  6289. buffer2[len] = 0;
  6290. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  6291. delete[] buffer2;
  6292. }
  6293. va_end(args_copy);
  6294. }
  6295. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  6296. va_list args;
  6297. va_start(args, format);
  6298. llama_log_internal_v(level, format, args);
  6299. va_end(args);
  6300. }
  6301. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  6302. (void) level;
  6303. (void) user_data;
  6304. fputs(text, stderr);
  6305. fflush(stderr);
  6306. }