llama.cpp 385 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #ifdef GGML_USE_CUBLAS
  7. # include "ggml-cuda.h"
  8. #elif defined(GGML_USE_CLBLAST)
  9. # include "ggml-opencl.h"
  10. #endif
  11. #ifdef GGML_USE_METAL
  12. # include "ggml-metal.h"
  13. #endif
  14. #ifdef GGML_USE_MPI
  15. # include "ggml-mpi.h"
  16. #endif
  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. #ifdef __has_include
  25. #if __has_include(<unistd.h>)
  26. #include <unistd.h>
  27. #if defined(_POSIX_MAPPED_FILES)
  28. #include <sys/mman.h>
  29. #endif
  30. #if defined(_POSIX_MEMLOCK_RANGE)
  31. #include <sys/resource.h>
  32. #endif
  33. #endif
  34. #endif
  35. #if defined(_WIN32)
  36. #define WIN32_LEAN_AND_MEAN
  37. #ifndef NOMINMAX
  38. #define NOMINMAX
  39. #endif
  40. #include <windows.h>
  41. #include <io.h>
  42. #endif
  43. #include <algorithm>
  44. #include <array>
  45. #include <cassert>
  46. #include <cinttypes>
  47. #include <climits>
  48. #include <cmath>
  49. #include <cstdarg>
  50. #include <cstddef>
  51. #include <cstdint>
  52. #include <cstdio>
  53. #include <cstring>
  54. #include <ctime>
  55. #include <forward_list>
  56. #include <fstream>
  57. #include <functional>
  58. #include <initializer_list>
  59. #include <map>
  60. #include <memory>
  61. #include <mutex>
  62. #include <numeric>
  63. #include <queue>
  64. #include <random>
  65. #include <regex>
  66. #include <set>
  67. #include <sstream>
  68. #include <thread>
  69. #include <type_traits>
  70. #include <unordered_map>
  71. #if defined(_MSC_VER)
  72. #pragma warning(disable: 4244 4267) // possible loss of data
  73. #endif
  74. #ifdef __GNUC__
  75. #ifdef __MINGW32__
  76. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  77. #else
  78. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  79. #endif
  80. #else
  81. #define LLAMA_ATTRIBUTE_FORMAT(...)
  82. #endif
  83. #define LLAMA_MAX_NODES 8192
  84. #define LLAMA_MAX_EXPERTS 8
  85. //
  86. // logging
  87. //
  88. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  89. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  90. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  91. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  92. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  93. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  94. //
  95. // helpers
  96. //
  97. static size_t utf8_len(char src) {
  98. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  99. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  100. return lookup[highbits];
  101. }
  102. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  103. std::string result;
  104. for (size_t pos = 0; ; pos += search.length()) {
  105. auto new_pos = s.find(search, pos);
  106. if (new_pos == std::string::npos) {
  107. result += s.substr(pos, s.size() - pos);
  108. break;
  109. }
  110. result += s.substr(pos, new_pos - pos) + replace;
  111. pos = new_pos;
  112. }
  113. s = std::move(result);
  114. }
  115. static bool is_float_close(float a, float b, float abs_tol) {
  116. // Check for non-negative tolerance
  117. if (abs_tol < 0.0) {
  118. throw std::invalid_argument("Tolerance must be non-negative");
  119. }
  120. // Exact equality check
  121. if (a == b) {
  122. return true;
  123. }
  124. // Check for infinities
  125. if (std::isinf(a) || std::isinf(b)) {
  126. return false;
  127. }
  128. // Regular comparison using the provided absolute tolerance
  129. return std::fabs(b - a) <= abs_tol;
  130. }
  131. #ifdef GGML_USE_CPU_HBM
  132. #include <hbwmalloc.h>
  133. #endif
  134. static void zeros(std::ofstream & file, size_t n) {
  135. char zero = 0;
  136. for (size_t i = 0; i < n; ++i) {
  137. file.write(&zero, 1);
  138. }
  139. }
  140. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  141. static std::string format(const char * fmt, ...) {
  142. va_list ap;
  143. va_list ap2;
  144. va_start(ap, fmt);
  145. va_copy(ap2, ap);
  146. int size = vsnprintf(NULL, 0, fmt, ap);
  147. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  148. std::vector<char> buf(size + 1);
  149. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  150. GGML_ASSERT(size2 == size);
  151. va_end(ap2);
  152. va_end(ap);
  153. return std::string(buf.data(), size);
  154. }
  155. //
  156. // gguf constants (sync with gguf.py)
  157. //
  158. enum llm_arch {
  159. LLM_ARCH_LLAMA,
  160. LLM_ARCH_FALCON,
  161. LLM_ARCH_BAICHUAN,
  162. LLM_ARCH_GPT2,
  163. LLM_ARCH_GPTJ,
  164. LLM_ARCH_GPTNEOX,
  165. LLM_ARCH_MPT,
  166. LLM_ARCH_STARCODER,
  167. LLM_ARCH_PERSIMMON,
  168. LLM_ARCH_REFACT,
  169. LLM_ARCH_BLOOM,
  170. LLM_ARCH_STABLELM,
  171. LLM_ARCH_QWEN,
  172. LLM_ARCH_UNKNOWN,
  173. };
  174. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  175. { LLM_ARCH_LLAMA, "llama" },
  176. { LLM_ARCH_FALCON, "falcon" },
  177. { LLM_ARCH_GPT2, "gpt2" },
  178. { LLM_ARCH_GPTJ, "gptj" },
  179. { LLM_ARCH_GPTNEOX, "gptneox" },
  180. { LLM_ARCH_MPT, "mpt" },
  181. { LLM_ARCH_BAICHUAN, "baichuan" },
  182. { LLM_ARCH_STARCODER, "starcoder" },
  183. { LLM_ARCH_PERSIMMON, "persimmon" },
  184. { LLM_ARCH_REFACT, "refact" },
  185. { LLM_ARCH_BLOOM, "bloom" },
  186. { LLM_ARCH_STABLELM, "stablelm" },
  187. { LLM_ARCH_QWEN, "qwen" },
  188. };
  189. enum llm_kv {
  190. LLM_KV_GENERAL_ARCHITECTURE,
  191. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  192. LLM_KV_GENERAL_ALIGNMENT,
  193. LLM_KV_GENERAL_NAME,
  194. LLM_KV_GENERAL_AUTHOR,
  195. LLM_KV_GENERAL_URL,
  196. LLM_KV_GENERAL_DESCRIPTION,
  197. LLM_KV_GENERAL_LICENSE,
  198. LLM_KV_GENERAL_SOURCE_URL,
  199. LLM_KV_GENERAL_SOURCE_HF_REPO,
  200. LLM_KV_CONTEXT_LENGTH,
  201. LLM_KV_EMBEDDING_LENGTH,
  202. LLM_KV_BLOCK_COUNT,
  203. LLM_KV_FEED_FORWARD_LENGTH,
  204. LLM_KV_USE_PARALLEL_RESIDUAL,
  205. LLM_KV_TENSOR_DATA_LAYOUT,
  206. LLM_KV_EXPERT_COUNT,
  207. LLM_KV_EXPERT_USED_COUNT,
  208. LLM_KV_ATTENTION_HEAD_COUNT,
  209. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  210. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  211. LLM_KV_ATTENTION_CLAMP_KQV,
  212. LLM_KV_ATTENTION_LAYERNORM_EPS,
  213. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  214. LLM_KV_ROPE_DIMENSION_COUNT,
  215. LLM_KV_ROPE_FREQ_BASE,
  216. LLM_KV_ROPE_SCALE_LINEAR,
  217. LLM_KV_ROPE_SCALING_TYPE,
  218. LLM_KV_ROPE_SCALING_FACTOR,
  219. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  220. LLM_KV_ROPE_SCALING_FINETUNED,
  221. LLM_KV_TOKENIZER_MODEL,
  222. LLM_KV_TOKENIZER_LIST,
  223. LLM_KV_TOKENIZER_TOKEN_TYPE,
  224. LLM_KV_TOKENIZER_SCORES,
  225. LLM_KV_TOKENIZER_MERGES,
  226. LLM_KV_TOKENIZER_BOS_ID,
  227. LLM_KV_TOKENIZER_EOS_ID,
  228. LLM_KV_TOKENIZER_UNK_ID,
  229. LLM_KV_TOKENIZER_SEP_ID,
  230. LLM_KV_TOKENIZER_PAD_ID,
  231. LLM_KV_TOKENIZER_ADD_BOS,
  232. LLM_KV_TOKENIZER_ADD_EOS,
  233. LLM_KV_TOKENIZER_HF_JSON,
  234. LLM_KV_TOKENIZER_RWKV,
  235. };
  236. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  237. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  238. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  239. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  240. { LLM_KV_GENERAL_NAME, "general.name" },
  241. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  242. { LLM_KV_GENERAL_URL, "general.url" },
  243. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  244. { LLM_KV_GENERAL_LICENSE, "general.license" },
  245. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  246. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  247. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  248. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  249. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  250. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  251. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  252. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  253. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  254. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  255. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  256. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  257. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  258. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  259. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  260. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  261. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  262. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  263. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  264. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  265. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  266. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  267. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  268. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  269. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  270. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  271. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  272. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  273. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  274. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  275. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  276. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  277. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  278. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  279. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  280. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  281. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  282. };
  283. struct LLM_KV {
  284. LLM_KV(llm_arch arch) : arch(arch) {}
  285. llm_arch arch;
  286. std::string operator()(llm_kv kv) const {
  287. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  288. }
  289. };
  290. enum llm_tensor {
  291. LLM_TENSOR_TOKEN_EMBD,
  292. LLM_TENSOR_TOKEN_EMBD_NORM,
  293. LLM_TENSOR_POS_EMBD,
  294. LLM_TENSOR_OUTPUT,
  295. LLM_TENSOR_OUTPUT_NORM,
  296. LLM_TENSOR_ROPE_FREQS,
  297. LLM_TENSOR_ATTN_Q,
  298. LLM_TENSOR_ATTN_K,
  299. LLM_TENSOR_ATTN_V,
  300. LLM_TENSOR_ATTN_QKV,
  301. LLM_TENSOR_ATTN_OUT,
  302. LLM_TENSOR_ATTN_NORM,
  303. LLM_TENSOR_ATTN_NORM_2,
  304. LLM_TENSOR_ATTN_ROT_EMBD,
  305. LLM_TENSOR_FFN_GATE_INP,
  306. LLM_TENSOR_FFN_NORM,
  307. LLM_TENSOR_FFN_GATE,
  308. LLM_TENSOR_FFN_DOWN,
  309. LLM_TENSOR_FFN_UP,
  310. LLM_TENSOR_FFN_DOWN_EXP,
  311. LLM_TENSOR_FFN_GATE_EXP,
  312. LLM_TENSOR_FFN_UP_EXP,
  313. LLM_TENSOR_ATTN_Q_NORM,
  314. LLM_TENSOR_ATTN_K_NORM,
  315. };
  316. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  317. {
  318. LLM_ARCH_LLAMA,
  319. {
  320. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  321. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  322. { LLM_TENSOR_OUTPUT, "output" },
  323. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  324. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  325. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  326. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  327. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  328. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  329. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  330. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  331. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  332. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  333. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  334. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  335. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  336. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  337. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  338. },
  339. },
  340. {
  341. LLM_ARCH_BAICHUAN,
  342. {
  343. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  344. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  345. { LLM_TENSOR_OUTPUT, "output" },
  346. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  347. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  348. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  349. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  350. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  351. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  352. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  353. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  354. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  355. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  356. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  357. },
  358. },
  359. {
  360. LLM_ARCH_FALCON,
  361. {
  362. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  363. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  364. { LLM_TENSOR_OUTPUT, "output" },
  365. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  366. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  367. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  368. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  369. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  370. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  371. },
  372. },
  373. {
  374. LLM_ARCH_GPT2,
  375. {
  376. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  377. },
  378. },
  379. {
  380. LLM_ARCH_GPTJ,
  381. {
  382. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  383. },
  384. },
  385. {
  386. LLM_ARCH_GPTNEOX,
  387. {
  388. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  389. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  390. { LLM_TENSOR_OUTPUT, "output" },
  391. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  392. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  393. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  394. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  395. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  396. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  397. },
  398. },
  399. {
  400. LLM_ARCH_PERSIMMON,
  401. {
  402. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  403. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  404. { LLM_TENSOR_OUTPUT, "output"},
  405. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  406. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  407. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  408. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  409. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  410. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  411. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  412. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  413. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  414. },
  415. },
  416. {
  417. LLM_ARCH_MPT,
  418. {
  419. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  420. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  421. { LLM_TENSOR_OUTPUT, "output" },
  422. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  423. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  424. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  425. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  426. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  427. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  428. },
  429. },
  430. {
  431. LLM_ARCH_STARCODER,
  432. {
  433. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  434. { LLM_TENSOR_POS_EMBD, "position_embd" },
  435. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  436. { LLM_TENSOR_OUTPUT, "output" },
  437. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  438. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  439. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  440. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  441. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  442. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  443. },
  444. },
  445. {
  446. LLM_ARCH_REFACT,
  447. {
  448. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  449. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  450. { LLM_TENSOR_OUTPUT, "output" },
  451. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  452. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  453. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  454. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  455. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  456. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  457. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  458. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  459. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  460. },
  461. },
  462. {
  463. LLM_ARCH_BLOOM,
  464. {
  465. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  466. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  467. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  468. { LLM_TENSOR_OUTPUT, "output" },
  469. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  470. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  471. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  472. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  473. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  474. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  475. },
  476. },
  477. {
  478. LLM_ARCH_STABLELM,
  479. {
  480. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  481. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  482. { LLM_TENSOR_OUTPUT, "output" },
  483. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  484. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  485. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  486. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  487. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  488. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  489. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  490. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  491. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  492. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  493. },
  494. },
  495. {
  496. LLM_ARCH_QWEN,
  497. {
  498. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  499. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  500. { LLM_TENSOR_OUTPUT, "output" },
  501. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  502. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  503. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  504. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  505. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  506. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  507. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  508. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  509. },
  510. },
  511. {
  512. LLM_ARCH_UNKNOWN,
  513. {
  514. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  515. },
  516. },
  517. };
  518. static llm_arch llm_arch_from_string(const std::string & name) {
  519. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  520. if (kv.second == name) {
  521. return kv.first;
  522. }
  523. }
  524. return LLM_ARCH_UNKNOWN;
  525. }
  526. // helper to handle gguf constants
  527. // usage:
  528. //
  529. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  530. //
  531. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  532. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  533. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  534. //
  535. struct LLM_TN {
  536. LLM_TN(llm_arch arch) : arch(arch) {}
  537. llm_arch arch;
  538. std::string operator()(llm_tensor tensor) const {
  539. return LLM_TENSOR_NAMES[arch].at(tensor);
  540. }
  541. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  542. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  543. }
  544. std::string operator()(llm_tensor tensor, int bid) const {
  545. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  546. }
  547. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  548. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  549. }
  550. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  551. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  552. }
  553. };
  554. //
  555. // gguf helpers
  556. //
  557. static std::map<int8_t, std::string> LLAMA_ROPE_SCALING_TYPES = {
  558. { LLAMA_ROPE_SCALING_NONE, "none" },
  559. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  560. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  561. };
  562. static int8_t llama_rope_scaling_type_from_string(const std::string & name) {
  563. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  564. if (kv.second == name) {
  565. return kv.first;
  566. }
  567. }
  568. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  569. }
  570. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  571. switch (type) {
  572. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  573. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  574. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  575. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  576. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  577. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  578. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  579. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  580. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  581. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  582. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  583. default: return format("unknown type %d", type);
  584. }
  585. }
  586. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  587. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  588. switch (type) {
  589. case GGUF_TYPE_STRING:
  590. return gguf_get_val_str(ctx_gguf, i);
  591. case GGUF_TYPE_ARRAY:
  592. {
  593. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  594. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  595. const void * data = gguf_get_arr_data(ctx_gguf, i);
  596. std::stringstream ss;
  597. ss << "[";
  598. for (int j = 0; j < arr_n; j++) {
  599. if (arr_type == GGUF_TYPE_STRING) {
  600. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  601. // escape quotes
  602. replace_all(val, "\\", "\\\\");
  603. replace_all(val, "\"", "\\\"");
  604. ss << '"' << val << '"';
  605. } else if (arr_type == GGUF_TYPE_ARRAY) {
  606. ss << "???";
  607. } else {
  608. ss << gguf_data_to_str(arr_type, data, j);
  609. }
  610. if (j < arr_n - 1) {
  611. ss << ", ";
  612. }
  613. }
  614. ss << "]";
  615. return ss.str();
  616. }
  617. default:
  618. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  619. }
  620. }
  621. //
  622. // ggml helpers
  623. //
  624. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  625. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  626. if (plan.work_size > 0) {
  627. buf.resize(plan.work_size);
  628. plan.work_data = buf.data();
  629. }
  630. ggml_graph_compute(graph, &plan);
  631. }
  632. //
  633. // llama helpers
  634. //
  635. inline void * llama_host_malloc(size_t n) {
  636. #ifdef GGML_USE_CUBLAS
  637. if (ggml_cublas_loaded()) {
  638. return ggml_cuda_host_malloc(n);
  639. } else {
  640. return malloc(n);
  641. }
  642. #elif GGML_USE_METAL
  643. return ggml_metal_host_malloc(n);
  644. #elif GGML_USE_CPU_HBM
  645. return hbw_malloc(n);
  646. #else
  647. return malloc(n);
  648. #endif
  649. }
  650. inline void llama_host_free(void * ptr) {
  651. #ifdef GGML_USE_CUBLAS
  652. if (ggml_cublas_loaded()) {
  653. return ggml_cuda_host_free(ptr);
  654. } else {
  655. return free(ptr);
  656. }
  657. #elif GGML_USE_METAL
  658. return ggml_metal_host_free(ptr);
  659. #elif GGML_USE_CPU_HBM
  660. return hbw_free(ptr);
  661. #else
  662. return free(ptr);
  663. #endif
  664. }
  665. #if defined(_WIN32)
  666. static std::string llama_format_win_err(DWORD err) {
  667. LPSTR buf;
  668. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  669. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  670. if (!size) {
  671. return "FormatMessageA failed";
  672. }
  673. std::string ret(buf, size);
  674. LocalFree(buf);
  675. return ret;
  676. }
  677. #endif
  678. struct llama_buffer {
  679. void * data = NULL;
  680. size_t size = 0;
  681. // fallback to malloc / free
  682. // useful in cases where CUDA can try to allocate PINNED memory
  683. bool fallback = false;
  684. void resize(size_t n) {
  685. llama_host_free(data);
  686. data = llama_host_malloc(n);
  687. if (!data) {
  688. fallback = true;
  689. data = malloc(n);
  690. } else {
  691. fallback = false;
  692. }
  693. GGML_ASSERT(data);
  694. size = n;
  695. }
  696. ~llama_buffer() {
  697. if (data) {
  698. if (fallback) { // NOLINT
  699. free(data);
  700. } else {
  701. llama_host_free(data);
  702. }
  703. }
  704. data = NULL;
  705. }
  706. };
  707. struct llama_file {
  708. // use FILE * so we don't have to re-open the file to mmap
  709. FILE * fp;
  710. size_t size;
  711. llama_file(const char * fname, const char * mode) {
  712. fp = std::fopen(fname, mode);
  713. if (fp == NULL) {
  714. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  715. }
  716. seek(0, SEEK_END);
  717. size = tell();
  718. seek(0, SEEK_SET);
  719. }
  720. size_t tell() const {
  721. #ifdef _WIN32
  722. __int64 ret = _ftelli64(fp);
  723. #else
  724. long ret = std::ftell(fp);
  725. #endif
  726. GGML_ASSERT(ret != -1); // this really shouldn't fail
  727. return (size_t) ret;
  728. }
  729. void seek(size_t offset, int whence) const {
  730. #ifdef _WIN32
  731. int ret = _fseeki64(fp, (__int64) offset, whence);
  732. #else
  733. int ret = std::fseek(fp, (long) offset, whence);
  734. #endif
  735. GGML_ASSERT(ret == 0); // same
  736. }
  737. void read_raw(void * ptr, size_t len) const {
  738. if (len == 0) {
  739. return;
  740. }
  741. errno = 0;
  742. std::size_t ret = std::fread(ptr, len, 1, fp);
  743. if (ferror(fp)) {
  744. throw std::runtime_error(format("read error: %s", strerror(errno)));
  745. }
  746. if (ret != 1) {
  747. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  748. }
  749. }
  750. uint32_t read_u32() const {
  751. uint32_t ret;
  752. read_raw(&ret, sizeof(ret));
  753. return ret;
  754. }
  755. void write_raw(const void * ptr, size_t len) const {
  756. if (len == 0) {
  757. return;
  758. }
  759. errno = 0;
  760. size_t ret = std::fwrite(ptr, len, 1, fp);
  761. if (ret != 1) {
  762. throw std::runtime_error(format("write error: %s", strerror(errno)));
  763. }
  764. }
  765. void write_u32(std::uint32_t val) const {
  766. write_raw(&val, sizeof(val));
  767. }
  768. ~llama_file() {
  769. if (fp) {
  770. std::fclose(fp);
  771. }
  772. }
  773. };
  774. struct llama_mmap {
  775. void * addr;
  776. size_t size;
  777. llama_mmap(const llama_mmap &) = delete;
  778. #ifdef _POSIX_MAPPED_FILES
  779. static constexpr bool SUPPORTED = true;
  780. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  781. size = file->size;
  782. int fd = fileno(file->fp);
  783. int flags = MAP_SHARED;
  784. // prefetch/readahead impairs performance on NUMA systems
  785. if (numa) { prefetch = 0; }
  786. #ifdef __linux__
  787. if (prefetch) { flags |= MAP_POPULATE; }
  788. #endif
  789. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  790. if (addr == MAP_FAILED) {
  791. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  792. }
  793. if (prefetch > 0) {
  794. // Advise the kernel to preload the mapped memory
  795. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  796. fprintf(stderr, "warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  797. strerror(errno));
  798. }
  799. }
  800. if (numa) {
  801. // advise the kernel not to use readahead
  802. // (because the next page might not belong on the same node)
  803. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  804. fprintf(stderr, "warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  805. strerror(errno));
  806. }
  807. }
  808. }
  809. ~llama_mmap() {
  810. munmap(addr, size);
  811. }
  812. #elif defined(_WIN32)
  813. static constexpr bool SUPPORTED = true;
  814. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  815. (void) numa;
  816. size = file->size;
  817. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  818. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  819. DWORD error = GetLastError();
  820. if (hMapping == NULL) {
  821. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  822. }
  823. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  824. error = GetLastError();
  825. CloseHandle(hMapping);
  826. if (addr == NULL) {
  827. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  828. }
  829. if (prefetch) {
  830. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  831. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  832. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  833. // may fail on pre-Windows 8 systems
  834. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  835. if (pPrefetchVirtualMemory) {
  836. // advise the kernel to preload the mapped memory
  837. WIN32_MEMORY_RANGE_ENTRY range;
  838. range.VirtualAddress = addr;
  839. range.NumberOfBytes = (SIZE_T)size;
  840. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  841. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  842. llama_format_win_err(GetLastError()).c_str());
  843. }
  844. }
  845. }
  846. }
  847. ~llama_mmap() {
  848. if (!UnmapViewOfFile(addr)) {
  849. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  850. llama_format_win_err(GetLastError()).c_str());
  851. }
  852. }
  853. #else
  854. static constexpr bool SUPPORTED = false;
  855. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  856. (void) file;
  857. (void) prefetch;
  858. (void) numa;
  859. throw std::runtime_error(std::string("mmap not supported"));
  860. }
  861. #endif
  862. };
  863. // Represents some region of memory being locked using mlock or VirtualLock;
  864. // will automatically unlock on destruction.
  865. struct llama_mlock {
  866. void * addr = NULL;
  867. size_t size = 0;
  868. bool failed_already = false;
  869. llama_mlock() {}
  870. llama_mlock(const llama_mlock &) = delete;
  871. ~llama_mlock() {
  872. if (size) {
  873. raw_unlock(addr, size);
  874. }
  875. }
  876. void init(void * ptr) {
  877. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  878. addr = ptr;
  879. }
  880. void grow_to(size_t target_size) {
  881. GGML_ASSERT(addr);
  882. if (failed_already) {
  883. return;
  884. }
  885. size_t granularity = lock_granularity();
  886. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  887. if (target_size > size) {
  888. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  889. size = target_size;
  890. } else {
  891. failed_already = true;
  892. }
  893. }
  894. }
  895. #ifdef _POSIX_MEMLOCK_RANGE
  896. static constexpr bool SUPPORTED = true;
  897. static size_t lock_granularity() {
  898. return (size_t) sysconf(_SC_PAGESIZE);
  899. }
  900. #ifdef __APPLE__
  901. #define MLOCK_SUGGESTION \
  902. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  903. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  904. #else
  905. #define MLOCK_SUGGESTION \
  906. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  907. #endif
  908. bool raw_lock(const void * addr, size_t size) const {
  909. if (!mlock(addr, size)) {
  910. return true;
  911. }
  912. char* errmsg = std::strerror(errno);
  913. bool suggest = (errno == ENOMEM);
  914. // Check if the resource limit is fine after all
  915. struct rlimit lock_limit;
  916. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  917. suggest = false;
  918. }
  919. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  920. suggest = false;
  921. }
  922. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  923. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  924. return false;
  925. }
  926. #undef MLOCK_SUGGESTION
  927. static void raw_unlock(void * addr, size_t size) {
  928. if (munlock(addr, size)) {
  929. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  930. }
  931. }
  932. #elif defined(_WIN32)
  933. static constexpr bool SUPPORTED = true;
  934. static size_t lock_granularity() {
  935. SYSTEM_INFO si;
  936. GetSystemInfo(&si);
  937. return (size_t) si.dwPageSize;
  938. }
  939. bool raw_lock(void * ptr, size_t len) const {
  940. for (int tries = 1; ; tries++) {
  941. if (VirtualLock(ptr, len)) {
  942. return true;
  943. }
  944. if (tries == 2) {
  945. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  946. len, size, llama_format_win_err(GetLastError()).c_str());
  947. return false;
  948. }
  949. // It failed but this was only the first try; increase the working
  950. // set size and try again.
  951. SIZE_T min_ws_size, max_ws_size;
  952. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  953. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  954. llama_format_win_err(GetLastError()).c_str());
  955. return false;
  956. }
  957. // Per MSDN: "The maximum number of pages that a process can lock
  958. // is equal to the number of pages in its minimum working set minus
  959. // a small overhead."
  960. // Hopefully a megabyte is enough overhead:
  961. size_t increment = len + 1048576;
  962. // The minimum must be <= the maximum, so we need to increase both:
  963. min_ws_size += increment;
  964. max_ws_size += increment;
  965. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  966. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  967. llama_format_win_err(GetLastError()).c_str());
  968. return false;
  969. }
  970. }
  971. }
  972. static void raw_unlock(void * ptr, size_t len) {
  973. if (!VirtualUnlock(ptr, len)) {
  974. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  975. llama_format_win_err(GetLastError()).c_str());
  976. }
  977. }
  978. #else
  979. static constexpr bool SUPPORTED = false;
  980. static size_t lock_granularity() {
  981. return (size_t) 65536;
  982. }
  983. bool raw_lock(const void * addr, size_t len) const {
  984. fprintf(stderr, "warning: mlock not supported on this system\n");
  985. return false;
  986. }
  987. static void raw_unlock(const void * addr, size_t len) {}
  988. #endif
  989. };
  990. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  991. static void ggml_offload_nop(struct ggml_tensor * tensor) {
  992. (void) tensor;
  993. }
  994. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  995. std::vector<char> result(8, 0);
  996. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  997. if (n_tokens < 0) {
  998. result.resize(-n_tokens);
  999. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1000. GGML_ASSERT(check == -n_tokens);
  1001. }
  1002. else {
  1003. result.resize(n_tokens);
  1004. }
  1005. return std::string(result.data(), result.size());
  1006. }
  1007. //
  1008. // globals
  1009. //
  1010. struct llama_state {
  1011. llama_state() {
  1012. #ifdef GGML_USE_METAL
  1013. ggml_metal_log_set_callback(log_callback, log_callback_user_data);
  1014. #endif
  1015. }
  1016. // We save the log callback globally
  1017. ggml_log_callback log_callback = llama_log_callback_default;
  1018. void * log_callback_user_data = nullptr;
  1019. };
  1020. static llama_state g_state;
  1021. // available llama models
  1022. enum e_model {
  1023. MODEL_UNKNOWN,
  1024. MODEL_1B,
  1025. MODEL_3B,
  1026. MODEL_7B,
  1027. MODEL_8B,
  1028. MODEL_13B,
  1029. MODEL_15B,
  1030. MODEL_30B,
  1031. MODEL_34B,
  1032. MODEL_40B,
  1033. MODEL_65B,
  1034. MODEL_70B,
  1035. };
  1036. static const size_t kiB = 1024;
  1037. static const size_t MiB = 1024*kiB;
  1038. static const size_t GiB = 1024*MiB;
  1039. struct llama_hparams {
  1040. bool vocab_only;
  1041. uint32_t n_vocab;
  1042. uint32_t n_ctx_train; // context size the model was trained on
  1043. uint32_t n_embd;
  1044. uint32_t n_head;
  1045. uint32_t n_head_kv;
  1046. uint32_t n_layer;
  1047. uint32_t n_rot;
  1048. uint32_t n_ff;
  1049. uint32_t n_expert = 0;
  1050. uint32_t n_expert_used = 0;
  1051. float f_norm_eps;
  1052. float f_norm_rms_eps;
  1053. float rope_freq_base_train;
  1054. float rope_freq_scale_train;
  1055. uint32_t n_yarn_orig_ctx;
  1056. int8_t rope_scaling_type_train : 3;
  1057. bool rope_finetuned : 1;
  1058. float f_clamp_kqv;
  1059. float f_max_alibi_bias;
  1060. bool operator!=(const llama_hparams & other) const {
  1061. if (this->vocab_only != other.vocab_only) return true;
  1062. if (this->n_vocab != other.n_vocab) return true;
  1063. if (this->n_ctx_train != other.n_ctx_train) return true;
  1064. if (this->n_embd != other.n_embd) return true;
  1065. if (this->n_head != other.n_head) return true;
  1066. if (this->n_head_kv != other.n_head_kv) return true;
  1067. if (this->n_layer != other.n_layer) return true;
  1068. if (this->n_rot != other.n_rot) return true;
  1069. if (this->n_ff != other.n_ff) return true;
  1070. if (this->n_expert != other.n_expert) return true;
  1071. if (this->n_expert_used != other.n_expert_used) return true;
  1072. if (this->rope_finetuned != other.rope_finetuned) return true;
  1073. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1074. const float EPSILON = 1e-9;
  1075. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1076. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1077. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1078. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1079. return false;
  1080. }
  1081. uint32_t n_gqa() const {
  1082. return n_head/n_head_kv;
  1083. }
  1084. uint32_t n_embd_head() const {
  1085. return n_embd/n_head;
  1086. }
  1087. uint32_t n_embd_gqa() const {
  1088. return n_embd/n_gqa();
  1089. }
  1090. };
  1091. struct llama_cparams {
  1092. uint32_t n_ctx; // context size used during inference
  1093. uint32_t n_batch;
  1094. uint32_t n_threads; // number of threads to use for generation
  1095. uint32_t n_threads_batch; // number of threads to use for batch processing
  1096. float rope_freq_base;
  1097. float rope_freq_scale;
  1098. uint32_t n_yarn_orig_ctx;
  1099. // These hyperparameters are not exposed in GGUF, because all
  1100. // existing YaRN models use the same values for them.
  1101. float yarn_ext_factor;
  1102. float yarn_attn_factor;
  1103. float yarn_beta_fast;
  1104. float yarn_beta_slow;
  1105. bool mul_mat_q;
  1106. bool offload_kqv;
  1107. };
  1108. struct llama_layer {
  1109. // normalization
  1110. struct ggml_tensor * attn_norm;
  1111. struct ggml_tensor * attn_norm_b;
  1112. struct ggml_tensor * attn_norm_2;
  1113. struct ggml_tensor * attn_norm_2_b;
  1114. struct ggml_tensor * attn_q_norm;
  1115. struct ggml_tensor * attn_q_norm_b;
  1116. struct ggml_tensor * attn_k_norm;
  1117. struct ggml_tensor * attn_k_norm_b;
  1118. // attention
  1119. struct ggml_tensor * wq;
  1120. struct ggml_tensor * wk;
  1121. struct ggml_tensor * wv;
  1122. struct ggml_tensor * wo;
  1123. struct ggml_tensor * wqkv;
  1124. // attention bias
  1125. struct ggml_tensor * bq;
  1126. struct ggml_tensor * bk;
  1127. struct ggml_tensor * bv;
  1128. struct ggml_tensor * bo;
  1129. struct ggml_tensor * bqkv;
  1130. // normalization
  1131. struct ggml_tensor * ffn_norm;
  1132. struct ggml_tensor * ffn_norm_b;
  1133. // ff
  1134. struct ggml_tensor * ffn_gate; // w1
  1135. struct ggml_tensor * ffn_down; // w2
  1136. struct ggml_tensor * ffn_up; // w3
  1137. // ff MoE
  1138. struct ggml_tensor * ffn_gate_inp;
  1139. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1140. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1141. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1142. // ff bias
  1143. struct ggml_tensor * ffn_down_b; // b2
  1144. struct ggml_tensor * ffn_up_b; // b3
  1145. };
  1146. struct llama_kv_cell {
  1147. llama_pos pos = -1;
  1148. llama_pos delta = 0;
  1149. std::set<llama_seq_id> seq_id;
  1150. bool has_seq_id(const llama_seq_id & id) const {
  1151. return seq_id.find(id) != seq_id.end();
  1152. }
  1153. };
  1154. // ring-buffer of cached KV data
  1155. struct llama_kv_cache {
  1156. bool has_shift = false;
  1157. // Note: The value of head isn't only used to optimize searching
  1158. // for a free KV slot. llama_decode_internal also uses it, so it
  1159. // cannot be freely changed after a slot has been allocated.
  1160. uint32_t head = 0;
  1161. uint32_t size = 0;
  1162. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1163. // computed before each graph build
  1164. uint32_t n = 0;
  1165. std::vector<llama_kv_cell> cells;
  1166. std::vector<struct ggml_tensor *> k_l; // per layer
  1167. std::vector<struct ggml_tensor *> v_l;
  1168. struct ggml_context * ctx = NULL;
  1169. llama_buffer buf;
  1170. ~llama_kv_cache() {
  1171. if (ctx) {
  1172. ggml_free(ctx);
  1173. }
  1174. #ifdef GGML_USE_CUBLAS
  1175. if (ggml_cublas_loaded()) {
  1176. for (size_t i = 0; i < k_l.size(); ++i) {
  1177. ggml_cuda_free_data(k_l[i]);
  1178. ggml_cuda_free_data(v_l[i]);
  1179. }
  1180. }
  1181. #endif
  1182. }
  1183. };
  1184. struct llama_vocab {
  1185. using id = int32_t;
  1186. using token = std::string;
  1187. using ttype = llama_token_type;
  1188. struct token_data {
  1189. token text;
  1190. float score;
  1191. ttype type;
  1192. };
  1193. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1194. std::unordered_map<token, id> token_to_id;
  1195. std::vector<token_data> id_to_token;
  1196. std::unordered_map<token, id> special_tokens_cache;
  1197. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1198. // default LLaMA special tokens
  1199. id special_bos_id = 1;
  1200. id special_eos_id = 2;
  1201. id special_unk_id = 0;
  1202. id special_sep_id = -1;
  1203. id special_pad_id = -1;
  1204. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1205. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1206. id linefeed_id = 13;
  1207. id special_prefix_id = 32007;
  1208. id special_middle_id = 32009;
  1209. id special_suffix_id = 32008;
  1210. id special_eot_id = 32010;
  1211. int find_bpe_rank(std::string token_left, std::string token_right) const {
  1212. GGML_ASSERT(token_left.find(" ") == std::string::npos);
  1213. GGML_ASSERT(token_left.find("\n") == std::string::npos);
  1214. GGML_ASSERT(token_right.find(" ") == std::string::npos);
  1215. GGML_ASSERT(token_right.find("\n") == std::string::npos);
  1216. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1217. if (it == bpe_ranks.end()) {
  1218. return -1;
  1219. }
  1220. return it->second;
  1221. }
  1222. };
  1223. struct llama_model {
  1224. e_model type = MODEL_UNKNOWN;
  1225. llm_arch arch = LLM_ARCH_UNKNOWN;
  1226. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1227. std::string name = "n/a";
  1228. llama_hparams hparams = {};
  1229. llama_vocab vocab;
  1230. struct ggml_tensor * tok_embd;
  1231. struct ggml_tensor * pos_embd;
  1232. struct ggml_tensor * tok_norm;
  1233. struct ggml_tensor * tok_norm_b;
  1234. struct ggml_tensor * output_norm;
  1235. struct ggml_tensor * output_norm_b;
  1236. struct ggml_tensor * output;
  1237. std::vector<llama_layer> layers;
  1238. int n_gpu_layers;
  1239. // gguf metadata
  1240. std::unordered_map<std::string, std::string> gguf_kv;
  1241. // context
  1242. struct ggml_context * ctx = NULL;
  1243. // the model memory buffer
  1244. llama_buffer buf;
  1245. // model memory mapped file
  1246. std::unique_ptr<llama_mmap> mapping;
  1247. // objects representing data potentially being locked in memory
  1248. llama_mlock mlock_buf;
  1249. llama_mlock mlock_mmap;
  1250. // for quantize-stats only
  1251. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1252. int64_t t_load_us = 0;
  1253. int64_t t_start_us = 0;
  1254. ~llama_model() {
  1255. if (ctx) {
  1256. ggml_free(ctx);
  1257. }
  1258. #ifdef GGML_USE_CUBLAS
  1259. if (ggml_cublas_loaded()) {
  1260. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  1261. ggml_cuda_free_data(tensors_by_name[i].second);
  1262. }
  1263. ggml_cuda_free_scratch();
  1264. }
  1265. #endif
  1266. #if defined(GGML_USE_CLBLAST)
  1267. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  1268. ggml_cl_free_data(tensors_by_name[i].second);
  1269. }
  1270. #endif
  1271. }
  1272. };
  1273. struct llama_context {
  1274. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1275. ~llama_context() {
  1276. #ifdef GGML_USE_METAL
  1277. if (ctx_metal) {
  1278. ggml_metal_free(ctx_metal);
  1279. }
  1280. #endif
  1281. if (alloc) {
  1282. ggml_allocr_free(alloc);
  1283. }
  1284. }
  1285. llama_cparams cparams;
  1286. const llama_model & model;
  1287. // key + value cache for the self attention
  1288. struct llama_kv_cache kv_self;
  1289. std::mt19937 rng;
  1290. bool has_evaluated_once = false;
  1291. int64_t t_start_us;
  1292. int64_t t_load_us;
  1293. int64_t t_sample_us = 0;
  1294. int64_t t_p_eval_us = 0;
  1295. int64_t t_eval_us = 0;
  1296. int32_t n_sample = 0; // number of tokens sampled
  1297. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1298. int32_t n_eval = 0; // number of eval calls
  1299. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1300. std::vector<float> logits;
  1301. #ifndef NDEBUG
  1302. // guard against access to unset logits
  1303. std::vector<bool> logits_valid;
  1304. #endif
  1305. bool logits_all = false;
  1306. // input embedding (1-dimensional array: [n_embd])
  1307. std::vector<float> embedding;
  1308. // reusable buffer for `struct ggml_graph_plan.work_data`
  1309. std::vector<uint8_t> work_buffer;
  1310. // memory buffers used to evaluate the model
  1311. llama_buffer buf_compute;
  1312. llama_buffer buf_alloc;
  1313. ggml_allocr * alloc = NULL;
  1314. #ifdef GGML_USE_METAL
  1315. ggml_metal_context * ctx_metal = NULL;
  1316. #endif
  1317. #ifdef GGML_USE_MPI
  1318. ggml_mpi_context * ctx_mpi = NULL;
  1319. #endif
  1320. };
  1321. //
  1322. // kv cache helpers
  1323. //
  1324. static bool llama_kv_cache_init(
  1325. const struct llama_hparams & hparams,
  1326. struct llama_kv_cache & cache,
  1327. ggml_type ktype,
  1328. ggml_type vtype,
  1329. uint32_t n_ctx,
  1330. int n_gpu_layers,
  1331. bool offload) {
  1332. const uint32_t n_embd = hparams.n_embd_gqa();
  1333. const uint32_t n_layer = hparams.n_layer;
  1334. const int64_t n_mem = n_layer*n_ctx;
  1335. const int64_t n_elements = n_embd*n_mem;
  1336. cache.has_shift = false;
  1337. cache.head = 0;
  1338. cache.size = n_ctx;
  1339. cache.used = 0;
  1340. cache.cells.clear();
  1341. cache.cells.resize(n_ctx);
  1342. cache.buf.resize(ggml_row_size(ktype, n_elements) + ggml_row_size(vtype, n_elements) + 2u*n_layer*ggml_tensor_overhead());
  1343. memset(cache.buf.data, 0, cache.buf.size);
  1344. struct ggml_init_params params;
  1345. params.mem_size = cache.buf.size;
  1346. params.mem_buffer = cache.buf.data;
  1347. params.no_alloc = false;
  1348. cache.ctx = ggml_init(params);
  1349. size_t vram_kv_cache = 0;
  1350. if (!cache.ctx) {
  1351. LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
  1352. return false;
  1353. }
  1354. cache.k_l.reserve(n_layer);
  1355. cache.v_l.reserve(n_layer);
  1356. const int i_gpu_start = (int) n_layer - n_gpu_layers; GGML_UNUSED(i_gpu_start);
  1357. GGML_UNUSED(offload);
  1358. for (int i = 0; i < (int) n_layer; i++) {
  1359. ggml_tensor * k = ggml_new_tensor_1d(cache.ctx, ktype, n_embd*n_ctx);
  1360. ggml_tensor * v = ggml_new_tensor_1d(cache.ctx, vtype, n_embd*n_ctx);
  1361. ggml_format_name(k, "cache_k_l%d", i);
  1362. ggml_format_name(v, "cache_v_l%d", i);
  1363. cache.k_l.push_back(k);
  1364. cache.v_l.push_back(v);
  1365. #ifdef GGML_USE_CUBLAS
  1366. if (i >= i_gpu_start) {
  1367. if (offload) {
  1368. ggml_cuda_assign_buffers_no_scratch(k);
  1369. vram_kv_cache += ggml_nbytes(k);
  1370. ggml_cuda_assign_buffers_no_scratch(v);
  1371. vram_kv_cache += ggml_nbytes(v);
  1372. }
  1373. }
  1374. #endif // GGML_USE_CUBLAS
  1375. }
  1376. if (vram_kv_cache > 0) {
  1377. LLAMA_LOG_INFO("%s: VRAM kv self = %.2f MB\n", __func__, vram_kv_cache / 1024.0 / 1024.0);
  1378. }
  1379. GGML_UNUSED(n_gpu_layers);
  1380. return true;
  1381. }
  1382. // find an empty slot of size "n_tokens" in the cache
  1383. // updates the cache head
  1384. // Note: On success, it's important that cache.head points
  1385. // to the first cell of the slot.
  1386. static bool llama_kv_cache_find_slot(
  1387. struct llama_kv_cache & cache,
  1388. const struct llama_batch & batch) {
  1389. const uint32_t n_ctx = cache.size;
  1390. const uint32_t n_tokens = batch.n_tokens;
  1391. if (n_tokens > n_ctx) {
  1392. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1393. return false;
  1394. }
  1395. uint32_t n_tested = 0;
  1396. while (true) {
  1397. if (cache.head + n_tokens > n_ctx) {
  1398. n_tested += n_ctx - cache.head;
  1399. cache.head = 0;
  1400. continue;
  1401. }
  1402. bool found = true;
  1403. for (uint32_t i = 0; i < n_tokens; i++) {
  1404. if (cache.cells[cache.head + i].pos >= 0) {
  1405. found = false;
  1406. cache.head += i + 1;
  1407. n_tested += i + 1;
  1408. break;
  1409. }
  1410. }
  1411. if (found) {
  1412. break;
  1413. }
  1414. if (n_tested >= n_ctx) {
  1415. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1416. return false;
  1417. }
  1418. }
  1419. for (uint32_t i = 0; i < n_tokens; i++) {
  1420. cache.cells[cache.head + i].pos = batch.pos[i];
  1421. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1422. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1423. }
  1424. }
  1425. cache.used += n_tokens;
  1426. return true;
  1427. }
  1428. // find how many cells are currently in use
  1429. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1430. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1431. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1432. return i + 1;
  1433. }
  1434. }
  1435. return 0;
  1436. }
  1437. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1438. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1439. cache.cells[i].pos = -1;
  1440. cache.cells[i].seq_id.clear();
  1441. }
  1442. cache.head = 0;
  1443. cache.used = 0;
  1444. }
  1445. static void llama_kv_cache_seq_rm(
  1446. struct llama_kv_cache & cache,
  1447. llama_seq_id seq_id,
  1448. llama_pos p0,
  1449. llama_pos p1) {
  1450. uint32_t new_head = cache.size;
  1451. if (p0 < 0) p0 = 0;
  1452. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1453. for (uint32_t i = 0; i < cache.size; ++i) {
  1454. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1455. if (seq_id < 0) {
  1456. cache.cells[i].seq_id.clear();
  1457. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1458. cache.cells[i].seq_id.erase(seq_id);
  1459. } else {
  1460. continue;
  1461. }
  1462. if (cache.cells[i].seq_id.empty()) {
  1463. // keep count of the number of used cells
  1464. if (cache.cells[i].pos >= 0) cache.used--;
  1465. cache.cells[i].pos = -1;
  1466. if (new_head == cache.size) new_head = i;
  1467. }
  1468. }
  1469. }
  1470. // If we freed up a slot, set head to it so searching can start there.
  1471. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1472. }
  1473. static void llama_kv_cache_seq_cp(
  1474. struct llama_kv_cache & cache,
  1475. llama_seq_id seq_id_src,
  1476. llama_seq_id seq_id_dst,
  1477. llama_pos p0,
  1478. llama_pos p1) {
  1479. if (p0 < 0) p0 = 0;
  1480. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1481. cache.head = 0;
  1482. for (uint32_t i = 0; i < cache.size; ++i) {
  1483. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1484. cache.cells[i].seq_id.insert(seq_id_dst);
  1485. }
  1486. }
  1487. }
  1488. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1489. uint32_t new_head = cache.size;
  1490. for (uint32_t i = 0; i < cache.size; ++i) {
  1491. if (!cache.cells[i].has_seq_id(seq_id)) {
  1492. if (cache.cells[i].pos >= 0) cache.used--;
  1493. cache.cells[i].pos = -1;
  1494. cache.cells[i].seq_id.clear();
  1495. if (new_head == cache.size) new_head = i;
  1496. } else {
  1497. cache.cells[i].seq_id.clear();
  1498. cache.cells[i].seq_id.insert(seq_id);
  1499. }
  1500. }
  1501. // If we freed up a slot, set head to it so searching can start there.
  1502. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1503. }
  1504. static void llama_kv_cache_seq_shift(
  1505. struct llama_kv_cache & cache,
  1506. llama_seq_id seq_id,
  1507. llama_pos p0,
  1508. llama_pos p1,
  1509. llama_pos delta) {
  1510. uint32_t new_head = cache.size;
  1511. if (p0 < 0) p0 = 0;
  1512. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1513. for (uint32_t i = 0; i < cache.size; ++i) {
  1514. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1515. cache.has_shift = true;
  1516. cache.cells[i].pos += delta;
  1517. cache.cells[i].delta += delta;
  1518. if (cache.cells[i].pos < 0) {
  1519. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1520. cache.cells[i].pos = -1;
  1521. cache.cells[i].seq_id.clear();
  1522. if (new_head == cache.size) new_head = i;
  1523. }
  1524. }
  1525. }
  1526. // If we freed up a slot, set head to it so searching can start there.
  1527. // Otherwise we just start the next search from the beginning.
  1528. cache.head = new_head != cache.size ? new_head : 0;
  1529. }
  1530. //
  1531. // model loading and saving
  1532. //
  1533. enum llama_fver {
  1534. GGUF_FILE_VERSION_V1 = 1,
  1535. GGUF_FILE_VERSION_V2 = 2,
  1536. GGUF_FILE_VERSION_V3 = 3,
  1537. };
  1538. static const char * llama_file_version_name(llama_fver version) {
  1539. switch (version) {
  1540. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1541. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1542. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1543. }
  1544. return "unknown";
  1545. }
  1546. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1547. char buf[256];
  1548. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1549. for (size_t i = 1; i < ne.size(); i++) {
  1550. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1551. }
  1552. return buf;
  1553. }
  1554. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1555. char buf[256];
  1556. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1557. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1558. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1559. }
  1560. return buf;
  1561. }
  1562. namespace GGUFMeta {
  1563. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1564. struct GKV_Base_Type {
  1565. static constexpr gguf_type gt = gt_;
  1566. static T getter(const gguf_context * ctx, const int kid) {
  1567. return gfun(ctx, kid);
  1568. }
  1569. };
  1570. template<typename T> struct GKV_Base;
  1571. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1572. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1573. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1574. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1575. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1576. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1577. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1578. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1579. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1580. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1581. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1582. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1583. template<> struct GKV_Base<std::string> {
  1584. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1585. static std::string getter(const gguf_context * ctx, const int kid) {
  1586. return gguf_get_val_str(ctx, kid);
  1587. }
  1588. };
  1589. struct ArrayInfo{
  1590. const gguf_type gt;
  1591. const size_t length;
  1592. const void * data;
  1593. };
  1594. template<> struct GKV_Base<ArrayInfo> {
  1595. public:
  1596. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1597. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1598. return ArrayInfo {
  1599. gguf_get_arr_type(ctx, k),
  1600. size_t(gguf_get_arr_n(ctx, k)),
  1601. gguf_get_arr_data(ctx, k),
  1602. };
  1603. }
  1604. };
  1605. template<typename T>
  1606. class GKV: public GKV_Base<T> {
  1607. GKV() = delete;
  1608. public:
  1609. static T get_kv(const gguf_context * ctx, const int k) {
  1610. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1611. if (kt != GKV::gt) {
  1612. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1613. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1614. }
  1615. return GKV::getter(ctx, k);
  1616. }
  1617. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1618. switch (ty) {
  1619. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1620. case LLAMA_KV_OVERRIDE_INT: return "int";
  1621. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1622. }
  1623. return "unknown";
  1624. }
  1625. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1626. if (!override) { return false; }
  1627. if (override->tag == expected_type) {
  1628. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1629. __func__, override_type_to_str(override->tag), override->key);
  1630. switch (override->tag) {
  1631. case LLAMA_KV_OVERRIDE_BOOL: {
  1632. printf("%s\n", override->bool_value ? "true" : "false");
  1633. } break;
  1634. case LLAMA_KV_OVERRIDE_INT: {
  1635. printf("%" PRId64 "\n", override->int_value);
  1636. } break;
  1637. case LLAMA_KV_OVERRIDE_FLOAT: {
  1638. printf("%.6f\n", override->float_value);
  1639. } break;
  1640. default:
  1641. // Shouldn't be possible to end up here, but just in case...
  1642. throw std::runtime_error(
  1643. format("Unsupported attempt to override %s type for metadata key %s\n",
  1644. override_type_to_str(override->tag), override->key));
  1645. }
  1646. return true;
  1647. }
  1648. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1649. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1650. return false;
  1651. }
  1652. template<typename OT>
  1653. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1654. try_override(OT & target, const struct llama_model_kv_override *override) {
  1655. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1656. target = override->bool_value;
  1657. return true;
  1658. }
  1659. return true;
  1660. }
  1661. template<typename OT>
  1662. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1663. try_override(OT & target, const struct llama_model_kv_override *override) {
  1664. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1665. target = override->int_value;
  1666. return true;
  1667. }
  1668. return false;
  1669. }
  1670. template<typename OT>
  1671. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1672. try_override(T & target, const struct llama_model_kv_override *override) {
  1673. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1674. target = override->float_value;
  1675. return true;
  1676. }
  1677. return false;
  1678. }
  1679. template<typename OT>
  1680. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1681. try_override(T & target, const struct llama_model_kv_override *override) {
  1682. (void)target;
  1683. (void)override;
  1684. if (!override) { return false; }
  1685. // Currently, we should never end up here so it would be a bug if we do.
  1686. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1687. override ? override->key : "NULL"));
  1688. }
  1689. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1690. if (try_override<T>(target, override)) {
  1691. return true;
  1692. }
  1693. if (k < 0) { return false; }
  1694. target = get_kv(ctx, k);
  1695. return true;
  1696. }
  1697. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1698. return set(ctx, gguf_find_key(ctx, key), target, override);
  1699. }
  1700. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1701. return set(ctx, key.c_str(), target, override);
  1702. }
  1703. };
  1704. }
  1705. struct llama_model_loader {
  1706. int n_kv = 0;
  1707. int n_tensors = 0;
  1708. int n_created = 0;
  1709. int64_t n_elements = 0;
  1710. size_t n_bytes = 0;
  1711. bool use_mmap = false;
  1712. llama_file file;
  1713. llama_ftype ftype;
  1714. llama_fver fver;
  1715. std::unique_ptr<llama_mmap> mapping;
  1716. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1717. struct gguf_context * ctx_gguf = NULL;
  1718. struct ggml_context * ctx_meta = NULL;
  1719. std::string arch_name;
  1720. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1721. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1722. struct gguf_init_params params = {
  1723. /*.no_alloc = */ true,
  1724. /*.ctx = */ &ctx_meta,
  1725. };
  1726. if (param_overrides_p != nullptr) {
  1727. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1728. kv_overrides.insert({std::string(p->key), *p});
  1729. }
  1730. }
  1731. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1732. if (!ctx_gguf) {
  1733. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1734. }
  1735. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  1736. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  1737. n_kv = gguf_get_n_kv(ctx_gguf);
  1738. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1739. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1740. for (int i = 0; i < n_tensors; i++) {
  1741. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1742. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1743. n_elements += ggml_nelements(t);
  1744. n_bytes += ggml_nbytes(t);
  1745. }
  1746. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1747. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1748. // determine file type based on the number of tensors for each quantization and print meta data
  1749. // TODO: make optional
  1750. {
  1751. std::map<enum ggml_type, uint32_t> n_type;
  1752. uint32_t n_type_max = 0;
  1753. enum ggml_type type_max = GGML_TYPE_F32;
  1754. for (int i = 0; i < n_tensors; i++) {
  1755. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1756. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, name);
  1757. n_type[meta->type]++;
  1758. if (n_type_max < n_type[meta->type]) {
  1759. n_type_max = n_type[meta->type];
  1760. type_max = meta->type;
  1761. }
  1762. 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());
  1763. }
  1764. switch (type_max) {
  1765. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1766. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1767. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1768. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1769. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1770. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1771. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1772. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1773. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1774. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1775. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1776. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1777. default:
  1778. {
  1779. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1780. ftype = LLAMA_FTYPE_ALL_F32;
  1781. } break;
  1782. }
  1783. // this is a way to mark that we have "guessed" the file type
  1784. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1785. {
  1786. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  1787. if (kid >= 0) {
  1788. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  1789. }
  1790. }
  1791. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  1792. for (int i = 0; i < n_kv; i++) {
  1793. const char * name = gguf_get_key(ctx_gguf, i);
  1794. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1795. const std::string type_name =
  1796. type == GGUF_TYPE_ARRAY
  1797. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(ctx_gguf, i)), gguf_get_arr_n(ctx_gguf, i))
  1798. : gguf_type_name(type);
  1799. std::string value = gguf_kv_to_str(ctx_gguf, i);
  1800. const size_t MAX_VALUE_LEN = 40;
  1801. if (value.size() > MAX_VALUE_LEN) {
  1802. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  1803. }
  1804. replace_all(value, "\n", "\\n");
  1805. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  1806. }
  1807. // print type counts
  1808. for (auto & kv : n_type) {
  1809. if (kv.second == 0) {
  1810. continue;
  1811. }
  1812. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  1813. }
  1814. }
  1815. if (!llama_mmap::SUPPORTED) {
  1816. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  1817. use_mmap = false;
  1818. }
  1819. this->use_mmap = use_mmap;
  1820. }
  1821. ~llama_model_loader() {
  1822. if (ctx_gguf) {
  1823. gguf_free(ctx_gguf);
  1824. }
  1825. if (ctx_meta) {
  1826. ggml_free(ctx_meta);
  1827. }
  1828. }
  1829. template<typename T>
  1830. typename std::enable_if<std::is_integral<T>::value, bool>::type
  1831. get_arr_n(const std::string & key, T & result, const bool required = true) {
  1832. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  1833. if (kid < 0) {
  1834. if (required) {
  1835. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  1836. }
  1837. return false;
  1838. }
  1839. struct GGUFMeta::ArrayInfo arr_info =
  1840. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  1841. result = arr_info.length;
  1842. return true;
  1843. }
  1844. template<typename T>
  1845. typename std::enable_if<std::is_integral<T>::value, bool>::type
  1846. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  1847. return get_arr_n(llm_kv(kid), result, required);
  1848. }
  1849. template<typename T>
  1850. bool get_key(const std::string & key, T & result, const bool required = true) {
  1851. auto it = kv_overrides.find(key);
  1852. const struct llama_model_kv_override * override =
  1853. it != kv_overrides.end() ? &it->second : nullptr;
  1854. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  1855. if (required && !found) {
  1856. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  1857. }
  1858. return found;
  1859. }
  1860. template<typename T>
  1861. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  1862. return get_key(llm_kv(kid), result, required);
  1863. }
  1864. std::string get_arch_name() const {
  1865. return arch_name;
  1866. }
  1867. enum llm_arch get_arch() const {
  1868. return llm_kv.arch;
  1869. }
  1870. const char * get_tensor_name(int i) const {
  1871. return gguf_get_tensor_name(ctx_gguf, i);
  1872. }
  1873. struct ggml_tensor * get_tensor_meta(int i) const {
  1874. return ggml_get_tensor(ctx_meta, get_tensor_name(i));
  1875. }
  1876. void calc_sizes(size_t & ctx_size_p, size_t & mmapped_size_p) const {
  1877. ctx_size_p = 0;
  1878. mmapped_size_p = 0;
  1879. for (int i = 0; i < n_tensors; i++) {
  1880. struct ggml_tensor * meta = get_tensor_meta(i);
  1881. ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  1882. (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
  1883. }
  1884. }
  1885. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta, ggml_backend_type backend) {
  1886. if (backend != GGML_BACKEND_CPU) {
  1887. ggml_set_no_alloc(ctx, true);
  1888. }
  1889. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  1890. tensor->backend = backend; // TODO: ggml_set_backend
  1891. ggml_set_name(tensor, ggml_get_name(meta));
  1892. if (backend != GGML_BACKEND_CPU) {
  1893. ggml_set_no_alloc(ctx, use_mmap);
  1894. }
  1895. n_created++;
  1896. return tensor;
  1897. }
  1898. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, ggml_backend_type backend, bool required = true) {
  1899. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  1900. if (cur == NULL) {
  1901. if (!required) {
  1902. return NULL;
  1903. }
  1904. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  1905. }
  1906. if (backend == GGML_BACKEND_GPU_SPLIT) {
  1907. if (ne.size() == 1) {
  1908. throw std::runtime_error(format("%s: 1-dimensional tensor '%s' cannot be split on the GPU", __func__, name.c_str()));
  1909. }
  1910. }
  1911. {
  1912. bool is_ok = true;
  1913. for (size_t i = 0; i < ne.size(); ++i) {
  1914. if (ne[i] != cur->ne[i]) {
  1915. is_ok = false;
  1916. break;
  1917. }
  1918. }
  1919. if (!is_ok) {
  1920. throw std::runtime_error(
  1921. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  1922. __func__, name.c_str(),
  1923. llama_format_tensor_shape(ne).c_str(),
  1924. llama_format_tensor_shape(cur).c_str()));
  1925. }
  1926. }
  1927. return create_tensor_for(ctx, cur, backend);
  1928. }
  1929. void done_getting_tensors() const {
  1930. if (n_created != n_tensors) {
  1931. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  1932. }
  1933. }
  1934. size_t file_offset(const char * name) const {
  1935. const int idx = gguf_find_tensor(ctx_gguf, name);
  1936. if (idx < 0) {
  1937. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  1938. }
  1939. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  1940. }
  1941. void load_data_for(struct ggml_tensor * cur) const {
  1942. const size_t offs = file_offset(ggml_get_name(cur));
  1943. if (use_mmap) {
  1944. cur->data = (uint8_t *) mapping->addr + offs;
  1945. } else {
  1946. file.seek(offs, SEEK_SET);
  1947. file.read_raw(cur->data, ggml_nbytes(cur));
  1948. }
  1949. }
  1950. void load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  1951. size_t size_data = 0;
  1952. size_t size_lock = 0;
  1953. size_t size_pref = 0; // prefetch
  1954. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1955. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1956. size_data += ggml_nbytes(cur);
  1957. if (cur->backend == GGML_BACKEND_CPU) {
  1958. size_pref += ggml_nbytes(cur);
  1959. }
  1960. }
  1961. if (use_mmap) {
  1962. mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
  1963. if (lmlock) {
  1964. lmlock->init(mapping->addr);
  1965. }
  1966. }
  1967. size_t done_size = 0;
  1968. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1969. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1970. GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
  1971. if (progress_callback) {
  1972. progress_callback((float) done_size / size_data, progress_callback_user_data);
  1973. }
  1974. // allocate temp buffer if not using mmap
  1975. if (!use_mmap && cur->data == NULL) {
  1976. GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
  1977. #ifdef GGML_USE_CPU_HBM
  1978. cur->data = (uint8_t*)hbw_malloc(ggml_nbytes(cur));
  1979. #else
  1980. cur->data = (uint8_t*)malloc(ggml_nbytes(cur));
  1981. #endif
  1982. }
  1983. load_data_for(cur);
  1984. switch (cur->backend) {
  1985. case GGML_BACKEND_CPU:
  1986. if (use_mmap && lmlock) {
  1987. size_lock += ggml_nbytes(cur);
  1988. lmlock->grow_to(size_lock);
  1989. }
  1990. break;
  1991. #ifdef GGML_USE_CUBLAS
  1992. case GGML_BACKEND_GPU:
  1993. case GGML_BACKEND_GPU_SPLIT:
  1994. // old code:
  1995. //ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  1996. // TODO: test if this works !!
  1997. ggml_cuda_transform_tensor(cur->data, cur);
  1998. if (!use_mmap) {
  1999. free(cur->data);
  2000. }
  2001. break;
  2002. #elif defined(GGML_USE_CLBLAST)
  2003. case GGML_BACKEND_GPU:
  2004. ggml_cl_transform_tensor(cur->data, cur);
  2005. if (!use_mmap) {
  2006. free(cur->data);
  2007. }
  2008. break;
  2009. #endif
  2010. default:
  2011. continue;
  2012. }
  2013. done_size += ggml_nbytes(cur);
  2014. }
  2015. }
  2016. };
  2017. //
  2018. // load LLaMA models
  2019. //
  2020. static std::string llama_model_arch_name(llm_arch arch) {
  2021. auto it = LLM_ARCH_NAMES.find(arch);
  2022. if (it == LLM_ARCH_NAMES.end()) {
  2023. return "unknown";
  2024. }
  2025. return it->second;
  2026. }
  2027. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2028. if (ftype & LLAMA_FTYPE_GUESSED) {
  2029. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2030. }
  2031. switch (ftype) {
  2032. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2033. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  2034. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  2035. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  2036. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2037. return "mostly Q4_1, some F16";
  2038. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  2039. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  2040. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  2041. // K-quants
  2042. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  2043. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  2044. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  2045. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  2046. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  2047. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  2048. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  2049. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  2050. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  2051. default: return "unknown, may not work";
  2052. }
  2053. }
  2054. static const char * llama_model_type_name(e_model type) {
  2055. switch (type) {
  2056. case MODEL_1B: return "1B";
  2057. case MODEL_3B: return "3B";
  2058. case MODEL_7B: return "7B";
  2059. case MODEL_8B: return "8B";
  2060. case MODEL_13B: return "13B";
  2061. case MODEL_15B: return "15B";
  2062. case MODEL_30B: return "30B";
  2063. case MODEL_34B: return "34B";
  2064. case MODEL_40B: return "40B";
  2065. case MODEL_65B: return "65B";
  2066. case MODEL_70B: return "70B";
  2067. default: return "?B";
  2068. }
  2069. }
  2070. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2071. model.arch = ml.get_arch();
  2072. if (model.arch == LLM_ARCH_UNKNOWN) {
  2073. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2074. }
  2075. }
  2076. static void llm_load_hparams(
  2077. llama_model_loader & ml,
  2078. llama_model & model) {
  2079. auto & hparams = model.hparams;
  2080. const gguf_context * ctx = ml.ctx_gguf;
  2081. // get metadata as string
  2082. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2083. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2084. if (type == GGUF_TYPE_ARRAY) {
  2085. continue;
  2086. }
  2087. const char * name = gguf_get_key(ctx, i);
  2088. const std::string value = gguf_kv_to_str(ctx, i);
  2089. model.gguf_kv.emplace(name, value);
  2090. }
  2091. // get general kv
  2092. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2093. // get hparams kv
  2094. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2095. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2096. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2097. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2098. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2099. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2100. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2101. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2102. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2103. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2104. if (hparams.n_expert > 0) {
  2105. GGML_ASSERT(hparams.n_expert_used > 0);
  2106. } else {
  2107. GGML_ASSERT(hparams.n_expert_used == 0);
  2108. }
  2109. // n_head_kv is optional, default to n_head
  2110. hparams.n_head_kv = hparams.n_head;
  2111. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2112. bool rope_finetuned = false;
  2113. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2114. hparams.rope_finetuned = rope_finetuned;
  2115. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2116. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2117. // rope_freq_base (optional)
  2118. hparams.rope_freq_base_train = 10000.0f;
  2119. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2120. std::string rope_scaling("linear");
  2121. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2122. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2123. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2124. // rope_freq_scale (inverse of the kv) is optional
  2125. float ropescale = 0.0f;
  2126. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2127. // try the old key name
  2128. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2129. }
  2130. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2131. // sanity check for n_rot (optional)
  2132. {
  2133. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2134. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2135. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2136. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2137. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2138. }
  2139. }
  2140. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2141. // gpt-j n_rot = rotary_dim
  2142. }
  2143. // arch-specific KVs
  2144. switch (model.arch) {
  2145. case LLM_ARCH_LLAMA:
  2146. {
  2147. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2148. switch (hparams.n_layer) {
  2149. case 26: model.type = e_model::MODEL_3B; break;
  2150. case 32: model.type = e_model::MODEL_7B; break;
  2151. case 40: model.type = e_model::MODEL_13B; break;
  2152. case 48: model.type = e_model::MODEL_34B; break;
  2153. case 60: model.type = e_model::MODEL_30B; break;
  2154. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2155. default: model.type = e_model::MODEL_UNKNOWN;
  2156. }
  2157. } break;
  2158. case LLM_ARCH_FALCON:
  2159. {
  2160. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2161. switch (hparams.n_layer) {
  2162. case 32: model.type = e_model::MODEL_7B; break;
  2163. case 60: model.type = e_model::MODEL_40B; break;
  2164. default: model.type = e_model::MODEL_UNKNOWN;
  2165. }
  2166. } break;
  2167. case LLM_ARCH_BAICHUAN:
  2168. {
  2169. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2170. switch (hparams.n_layer) {
  2171. case 32: model.type = e_model::MODEL_7B; break;
  2172. case 40: model.type = e_model::MODEL_13B; break;
  2173. default: model.type = e_model::MODEL_UNKNOWN;
  2174. }
  2175. } break;
  2176. case LLM_ARCH_STARCODER:
  2177. {
  2178. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2179. switch (hparams.n_layer) {
  2180. case 24: model.type = e_model::MODEL_1B; break;
  2181. case 36: model.type = e_model::MODEL_3B; break;
  2182. case 42: model.type = e_model::MODEL_7B; break;
  2183. case 40: model.type = e_model::MODEL_15B; break;
  2184. default: model.type = e_model::MODEL_UNKNOWN;
  2185. }
  2186. } break;
  2187. case LLM_ARCH_PERSIMMON:
  2188. {
  2189. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2190. switch (hparams.n_layer) {
  2191. case 36: model.type = e_model::MODEL_8B; break;
  2192. default: model.type = e_model::MODEL_UNKNOWN;
  2193. }
  2194. } break;
  2195. case LLM_ARCH_REFACT:
  2196. {
  2197. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2198. switch (hparams.n_layer) {
  2199. case 32: model.type = e_model::MODEL_1B; break;
  2200. default: model.type = e_model::MODEL_UNKNOWN;
  2201. }
  2202. } break;
  2203. case LLM_ARCH_BLOOM:
  2204. {
  2205. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2206. switch (hparams.n_layer) {
  2207. case 24: model.type = e_model::MODEL_1B; break;
  2208. case 30:
  2209. switch (hparams.n_embd) {
  2210. case 2560: model.type = e_model::MODEL_3B; break;
  2211. case 4096: model.type = e_model::MODEL_7B; break;
  2212. } break;
  2213. }
  2214. } break;
  2215. case LLM_ARCH_MPT:
  2216. {
  2217. hparams.f_clamp_kqv = 0.0f;
  2218. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2219. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2220. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2221. switch (hparams.n_layer) {
  2222. case 32: model.type = e_model::MODEL_7B; break;
  2223. case 48: model.type = e_model::MODEL_30B; break;
  2224. default: model.type = e_model::MODEL_UNKNOWN;
  2225. }
  2226. } break;
  2227. case LLM_ARCH_STABLELM:
  2228. {
  2229. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2230. switch (hparams.n_layer) {
  2231. case 32: model.type = e_model::MODEL_3B; break;
  2232. default: model.type = e_model::MODEL_UNKNOWN;
  2233. }
  2234. } break;
  2235. case LLM_ARCH_QWEN:
  2236. {
  2237. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2238. switch (hparams.n_layer) {
  2239. case 32: model.type = e_model::MODEL_7B; break;
  2240. case 40: model.type = e_model::MODEL_13B; break;
  2241. default: model.type = e_model::MODEL_UNKNOWN;
  2242. }
  2243. } break;
  2244. default: (void)0;
  2245. }
  2246. model.ftype = ml.ftype;
  2247. }
  2248. // TODO: This should probably be in llama.h
  2249. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2250. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2251. static void llm_load_vocab(
  2252. llama_model_loader & ml,
  2253. llama_model & model) {
  2254. auto & vocab = model.vocab;
  2255. struct gguf_context * ctx = ml.ctx_gguf;
  2256. const auto kv = LLM_KV(model.arch);
  2257. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2258. if (token_idx == -1) {
  2259. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2260. }
  2261. const float * scores = nullptr;
  2262. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2263. if (score_idx != -1) {
  2264. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2265. }
  2266. const int * toktypes = nullptr;
  2267. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2268. if (toktype_idx != -1) {
  2269. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2270. }
  2271. // determine vocab type
  2272. {
  2273. std::string tokenizer_name;
  2274. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2275. if (tokenizer_name == "llama") {
  2276. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2277. // default special tokens
  2278. vocab.special_bos_id = 1;
  2279. vocab.special_eos_id = 2;
  2280. vocab.special_unk_id = 0;
  2281. vocab.special_sep_id = -1;
  2282. vocab.special_pad_id = -1;
  2283. } else if (tokenizer_name == "gpt2") {
  2284. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2285. // read bpe merges and populate bpe ranks
  2286. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2287. if (merges_keyidx == -1) {
  2288. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2289. }
  2290. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2291. for (int i = 0; i < n_merges; i++) {
  2292. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2293. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2294. std::string first;
  2295. std::string second;
  2296. const size_t pos = word.find(' ', 1);
  2297. if (pos != std::string::npos) {
  2298. first = word.substr(0, pos);
  2299. second = word.substr(pos + 1);
  2300. }
  2301. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2302. }
  2303. // default special tokens
  2304. vocab.special_bos_id = 11;
  2305. vocab.special_eos_id = 11;
  2306. vocab.special_unk_id = -1;
  2307. vocab.special_sep_id = -1;
  2308. vocab.special_pad_id = -1;
  2309. } else {
  2310. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2311. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2312. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2313. }
  2314. }
  2315. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2316. vocab.id_to_token.resize(n_vocab);
  2317. for (uint32_t i = 0; i < n_vocab; i++) {
  2318. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2319. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2320. vocab.token_to_id[word] = i;
  2321. auto & token_data = vocab.id_to_token[i];
  2322. token_data.text = std::move(word);
  2323. token_data.score = scores ? scores[i] : 0.0f;
  2324. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2325. }
  2326. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2327. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2328. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2329. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2330. } else {
  2331. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2332. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2333. vocab.linefeed_id = ids[0];
  2334. }
  2335. // special tokens
  2336. {
  2337. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2338. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2339. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2340. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2341. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2342. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2343. };
  2344. for (const auto & it : special_token_types) {
  2345. const std::string & key = kv(std::get<0>(it));
  2346. int32_t & id = std::get<1>(it);
  2347. uint32_t new_id;
  2348. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2349. continue;
  2350. }
  2351. if (new_id >= vocab.id_to_token.size()) {
  2352. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2353. __func__, key.c_str(), new_id, id);
  2354. } else {
  2355. id = new_id;
  2356. }
  2357. }
  2358. // Handle add_bos_token and add_eos_token
  2359. {
  2360. bool temp = true;
  2361. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2362. vocab.special_add_bos = int(temp);
  2363. }
  2364. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2365. vocab.special_add_eos = int(temp);
  2366. }
  2367. }
  2368. }
  2369. // build special tokens cache
  2370. {
  2371. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2372. // and will always be correctly labeled in 'added_tokens.json' etc.
  2373. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2374. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2375. // are special tokens.
  2376. // From testing, this appears to correlate 1:1 with special tokens.
  2377. //
  2378. // Counting special tokens and verifying in only one direction
  2379. // is sufficient to detect difference in those two sets.
  2380. //
  2381. uint32_t special_tokens_count_by_type = 0;
  2382. uint32_t special_tokens_count_from_verification = 0;
  2383. bool special_tokens_definition_mismatch = false;
  2384. for (const auto & t : vocab.token_to_id) {
  2385. const auto & token = t.first;
  2386. const auto & id = t.second;
  2387. // Count all non-normal tokens in the vocab while iterating
  2388. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2389. special_tokens_count_by_type++;
  2390. }
  2391. // Skip single character tokens
  2392. if (token.length() > 1) {
  2393. bool is_tokenizable = false;
  2394. // Split token string representation in two, in all possible ways
  2395. // and check if both halves can be matched to a valid token
  2396. for (unsigned i = 1; i < token.length();) {
  2397. const auto left = token.substr(0, i);
  2398. const auto right = token.substr(i);
  2399. // check if we didnt partition in the middle of a utf sequence
  2400. auto utf = utf8_len(left.at(left.length() - 1));
  2401. if (utf == 1) {
  2402. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2403. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2404. is_tokenizable = true;
  2405. break;
  2406. }
  2407. i++;
  2408. } else {
  2409. // skip over the rest of multibyte utf sequence
  2410. i += utf - 1;
  2411. }
  2412. }
  2413. if (!is_tokenizable) {
  2414. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2415. // it's faster to re-filter them here, since there are way less candidates now
  2416. // Calculate a total "utf" length of a token string representation
  2417. size_t utf8_str_len = 0;
  2418. for (unsigned i = 0; i < token.length();) {
  2419. utf8_str_len++;
  2420. i += utf8_len(token.at(i));
  2421. }
  2422. // And skip the ones which are one character
  2423. if (utf8_str_len > 1) {
  2424. // At this point what we have left are special tokens only
  2425. vocab.special_tokens_cache[token] = id;
  2426. // Count manually found special tokens
  2427. special_tokens_count_from_verification++;
  2428. // If this manually found special token is not marked as such, flag a mismatch
  2429. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2430. special_tokens_definition_mismatch = true;
  2431. }
  2432. }
  2433. }
  2434. }
  2435. }
  2436. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2437. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2438. __func__,
  2439. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2440. special_tokens_count_by_type, vocab.id_to_token.size()
  2441. );
  2442. } else {
  2443. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2444. __func__,
  2445. special_tokens_count_from_verification, vocab.id_to_token.size()
  2446. );
  2447. }
  2448. }
  2449. }
  2450. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2451. const auto & hparams = model.hparams;
  2452. const auto & vocab = model.vocab;
  2453. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2454. // hparams
  2455. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2456. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2457. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2458. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2459. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2460. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2461. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2462. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2463. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2464. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2465. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  2466. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2467. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2468. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2469. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2470. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2471. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2472. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2473. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2474. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2475. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2476. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2477. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2478. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2479. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2480. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2481. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2482. if (ml.n_bytes < GiB) {
  2483. 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);
  2484. } else {
  2485. 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);
  2486. }
  2487. // general kv
  2488. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2489. // special tokens
  2490. 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() ); }
  2491. 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() ); }
  2492. 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() ); }
  2493. 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() ); }
  2494. 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() ); }
  2495. 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() ); }
  2496. }
  2497. static void llm_load_tensors(
  2498. llama_model_loader & ml,
  2499. llama_model & model,
  2500. int n_gpu_layers,
  2501. int main_gpu,
  2502. const float * tensor_split,
  2503. bool use_mlock,
  2504. llama_progress_callback progress_callback,
  2505. void * progress_callback_user_data) {
  2506. model.t_start_us = ggml_time_us();
  2507. auto & ctx = model.ctx;
  2508. auto & hparams = model.hparams;
  2509. model.n_gpu_layers = n_gpu_layers;
  2510. size_t ctx_size;
  2511. size_t mmapped_size;
  2512. ml.calc_sizes(ctx_size, mmapped_size);
  2513. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, ctx_size/1024.0/1024.0);
  2514. // create the ggml context
  2515. {
  2516. model.buf.resize(ctx_size);
  2517. if (use_mlock) {
  2518. model.mlock_buf.init (model.buf.data);
  2519. model.mlock_buf.grow_to(model.buf.size);
  2520. }
  2521. struct ggml_init_params params = {
  2522. /*.mem_size =*/ model.buf.size,
  2523. /*.mem_buffer =*/ model.buf.data,
  2524. /*.no_alloc =*/ ml.use_mmap,
  2525. };
  2526. model.ctx = ggml_init(params);
  2527. if (!model.ctx) {
  2528. throw std::runtime_error(format("ggml_init() failed"));
  2529. }
  2530. }
  2531. (void) main_gpu;
  2532. enum ggml_backend_type llama_backend_offload = GGML_BACKEND_CPU;
  2533. enum ggml_backend_type llama_backend_offload_split = GGML_BACKEND_CPU;
  2534. #ifdef GGML_USE_CUBLAS
  2535. if (ggml_cublas_loaded()) {
  2536. LLAMA_LOG_INFO("%s: using " GGML_CUDA_NAME " for GPU acceleration\n", __func__);
  2537. ggml_cuda_set_main_device(main_gpu);
  2538. llama_backend_offload = GGML_BACKEND_GPU;
  2539. llama_backend_offload_split = GGML_BACKEND_GPU_SPLIT;
  2540. }
  2541. #elif defined(GGML_USE_CLBLAST)
  2542. LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
  2543. llama_backend_offload = GGML_BACKEND_GPU;
  2544. llama_backend_offload_split = GGML_BACKEND_GPU;
  2545. #endif
  2546. // prepare memory for the weights
  2547. size_t vram_weights = 0;
  2548. {
  2549. const int64_t n_embd = hparams.n_embd;
  2550. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2551. const int64_t n_layer = hparams.n_layer;
  2552. const int64_t n_vocab = hparams.n_vocab;
  2553. const auto tn = LLM_TN(model.arch);
  2554. switch (model.arch) {
  2555. case LLM_ARCH_LLAMA:
  2556. case LLM_ARCH_REFACT:
  2557. {
  2558. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2559. // output
  2560. {
  2561. ggml_backend_type backend_norm;
  2562. ggml_backend_type backend_output;
  2563. if (n_gpu_layers > int(n_layer)) {
  2564. backend_norm = llama_backend_offload;
  2565. backend_output = llama_backend_offload_split;
  2566. } else {
  2567. backend_norm = GGML_BACKEND_CPU;
  2568. backend_output = GGML_BACKEND_CPU;
  2569. }
  2570. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2571. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2572. if (backend_norm == GGML_BACKEND_GPU) {
  2573. vram_weights += ggml_nbytes(model.output_norm);
  2574. }
  2575. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2576. vram_weights += ggml_nbytes(model.output);
  2577. }
  2578. }
  2579. const uint32_t n_ff = hparams.n_ff;
  2580. const int i_gpu_start = n_layer - n_gpu_layers;
  2581. model.layers.resize(n_layer);
  2582. for (uint32_t i = 0; i < n_layer; ++i) {
  2583. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  2584. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  2585. auto & layer = model.layers[i];
  2586. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2587. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  2588. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2589. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2590. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2591. // optional bias tensors
  2592. layer.bq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, backend, false);
  2593. layer.bk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, backend, false);
  2594. layer.bv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, backend, false);
  2595. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend, false);
  2596. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2597. layer.ffn_gate_inp = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, backend, false);
  2598. if (layer.ffn_gate_inp == nullptr) {
  2599. GGML_ASSERT(hparams.n_expert == 0);
  2600. GGML_ASSERT(hparams.n_expert_used == 0);
  2601. layer.ffn_gate = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  2602. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2603. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2604. } else {
  2605. GGML_ASSERT(hparams.n_expert > 0);
  2606. GGML_ASSERT(hparams.n_expert_used > 0);
  2607. // MoE branch
  2608. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  2609. layer.ffn_gate_exp[x] = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff}, backend_split);
  2610. layer.ffn_down_exp[x] = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd}, backend_split);
  2611. layer.ffn_up_exp[x] = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff}, backend_split);
  2612. }
  2613. }
  2614. if (backend == GGML_BACKEND_GPU) {
  2615. vram_weights +=
  2616. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  2617. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) +
  2618. (layer.bq ? ggml_nbytes(layer.bq) : 0) +
  2619. (layer.bk ? ggml_nbytes(layer.bk) : 0) +
  2620. (layer.bv ? ggml_nbytes(layer.bv) : 0) +
  2621. (layer.bo ? ggml_nbytes(layer.bo) : 0) +
  2622. ggml_nbytes(layer.ffn_norm);
  2623. if (layer.ffn_gate_inp == nullptr) {
  2624. vram_weights +=
  2625. ggml_nbytes(layer.ffn_gate) + ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  2626. } else {
  2627. vram_weights += ggml_nbytes(layer.ffn_gate_inp);
  2628. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  2629. vram_weights +=
  2630. ggml_nbytes(layer.ffn_gate_exp[x]) + ggml_nbytes(layer.ffn_down_exp[x]) + ggml_nbytes(layer.ffn_up_exp[x]);
  2631. }
  2632. }
  2633. }
  2634. }
  2635. } break;
  2636. case LLM_ARCH_BAICHUAN:
  2637. {
  2638. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2639. {
  2640. ggml_backend_type backend_norm;
  2641. ggml_backend_type backend_output;
  2642. if (n_gpu_layers > int(n_layer)) {
  2643. backend_norm = llama_backend_offload;
  2644. backend_output = llama_backend_offload_split;
  2645. } else {
  2646. backend_norm = GGML_BACKEND_CPU;
  2647. backend_output = GGML_BACKEND_CPU;
  2648. }
  2649. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2650. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2651. if (backend_norm == GGML_BACKEND_GPU) {
  2652. vram_weights += ggml_nbytes(model.output_norm);
  2653. }
  2654. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2655. vram_weights += ggml_nbytes(model.output);
  2656. }
  2657. }
  2658. const uint32_t n_ff = hparams.n_ff;
  2659. const int i_gpu_start = n_layer - n_gpu_layers;
  2660. model.layers.resize(n_layer);
  2661. for (uint32_t i = 0; i < n_layer; ++i) {
  2662. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  2663. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  2664. auto & layer = model.layers[i];
  2665. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2666. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  2667. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2668. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2669. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2670. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2671. layer.ffn_gate = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  2672. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2673. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2674. if (backend == GGML_BACKEND_GPU) {
  2675. vram_weights +=
  2676. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  2677. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  2678. ggml_nbytes(layer.ffn_gate) + ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  2679. }
  2680. }
  2681. } break;
  2682. case LLM_ARCH_FALCON:
  2683. {
  2684. // TODO: CPU-only for now
  2685. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2686. // output
  2687. {
  2688. ggml_backend_type backend_norm;
  2689. ggml_backend_type backend_output;
  2690. if (n_gpu_layers > int(n_layer)) {
  2691. backend_norm = llama_backend_offload;
  2692. backend_output = llama_backend_offload_split;
  2693. } else {
  2694. backend_norm = GGML_BACKEND_CPU;
  2695. backend_output = GGML_BACKEND_CPU;
  2696. }
  2697. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2698. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2699. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2700. if (backend_norm == GGML_BACKEND_GPU) {
  2701. vram_weights += ggml_nbytes(model.output_norm);
  2702. vram_weights += ggml_nbytes(model.output_norm_b);
  2703. }
  2704. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2705. vram_weights += ggml_nbytes(model.output);
  2706. }
  2707. }
  2708. const uint32_t n_ff = hparams.n_ff;
  2709. const int i_gpu_start = n_layer - n_gpu_layers;
  2710. model.layers.resize(n_layer);
  2711. for (uint32_t i = 0; i < n_layer; ++i) {
  2712. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  2713. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  2714. auto & layer = model.layers[i];
  2715. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2716. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2717. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  2718. layer.attn_norm_2 = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, backend);
  2719. layer.attn_norm_2_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, backend);
  2720. if (backend == GGML_BACKEND_GPU) {
  2721. vram_weights += ggml_nbytes(layer.attn_norm_2);
  2722. vram_weights += ggml_nbytes(layer.attn_norm_2_b);
  2723. }
  2724. }
  2725. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2726. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2727. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2728. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2729. if (backend == GGML_BACKEND_GPU) {
  2730. vram_weights +=
  2731. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  2732. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.wo) +
  2733. ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  2734. }
  2735. }
  2736. } break;
  2737. case LLM_ARCH_STARCODER:
  2738. {
  2739. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2740. model.pos_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, GGML_BACKEND_CPU);
  2741. // output
  2742. {
  2743. ggml_backend_type backend_norm;
  2744. ggml_backend_type backend_output;
  2745. if (n_gpu_layers > int(n_layer)) {
  2746. backend_norm = llama_backend_offload;
  2747. backend_output = llama_backend_offload_split;
  2748. } else {
  2749. backend_norm = GGML_BACKEND_CPU;
  2750. backend_output = GGML_BACKEND_CPU;
  2751. }
  2752. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2753. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2754. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2755. if (backend_norm == GGML_BACKEND_GPU) {
  2756. vram_weights += ggml_nbytes(model.output_norm);
  2757. vram_weights += ggml_nbytes(model.output_norm_b);
  2758. }
  2759. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2760. vram_weights += ggml_nbytes(model.output);
  2761. }
  2762. }
  2763. const uint32_t n_ff = hparams.n_ff;
  2764. const int i_gpu_start = n_layer - n_gpu_layers;
  2765. model.layers.resize(n_layer);
  2766. for (uint32_t i = 0; i < n_layer; ++i) {
  2767. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  2768. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  2769. auto & layer = model.layers[i];
  2770. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2771. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2772. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2773. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, backend);
  2774. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2775. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend);
  2776. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2777. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2778. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, backend_split);
  2779. layer.ffn_down_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, backend);
  2780. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2781. layer.ffn_up_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, backend);
  2782. if (backend == GGML_BACKEND_GPU) {
  2783. vram_weights +=
  2784. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  2785. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.bqkv) +
  2786. ggml_nbytes(layer.wo) + ggml_nbytes(layer.bo) +
  2787. ggml_nbytes(layer.ffn_norm) + ggml_nbytes(layer.ffn_norm_b) +
  2788. ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_down_b) +
  2789. ggml_nbytes(layer.ffn_up) + ggml_nbytes(layer.ffn_up_b);
  2790. }
  2791. }
  2792. } break;
  2793. case LLM_ARCH_PERSIMMON:
  2794. {
  2795. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2796. {
  2797. ggml_backend_type backend_norm;
  2798. ggml_backend_type backend_output;
  2799. if (n_gpu_layers > int(n_layer)) {
  2800. backend_norm = llama_backend_offload;
  2801. backend_output = llama_backend_offload_split;
  2802. } else {
  2803. backend_norm = GGML_BACKEND_CPU;
  2804. backend_output = GGML_BACKEND_CPU;
  2805. }
  2806. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2807. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2808. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2809. if (backend_norm == GGML_BACKEND_GPU) {
  2810. vram_weights += ggml_nbytes(model.output_norm);
  2811. vram_weights += ggml_nbytes(model.output_norm_b);
  2812. }
  2813. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2814. vram_weights += ggml_nbytes(model.output);
  2815. }
  2816. }
  2817. const uint32_t n_ff = hparams.n_ff;
  2818. const int i_gpu_start = n_layer - n_gpu_layers;
  2819. model.layers.resize(n_layer);
  2820. for (uint32_t i = 0; i < n_layer; ++i) {
  2821. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload;
  2822. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split;
  2823. auto & layer = model.layers[i];
  2824. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2825. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2826. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2827. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, backend);
  2828. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2829. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend);
  2830. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, backend_split);
  2831. layer.ffn_down_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, backend);
  2832. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2833. layer.ffn_up_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, backend);
  2834. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2835. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2836. layer.attn_q_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64}, backend);
  2837. layer.attn_q_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64}, backend);
  2838. layer.attn_k_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64}, backend);
  2839. layer.attn_k_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64}, backend);
  2840. }
  2841. } break;
  2842. case LLM_ARCH_BLOOM:
  2843. {
  2844. // TODO: CPU-only for now
  2845. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2846. model.tok_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, GGML_BACKEND_CPU);
  2847. model.tok_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, GGML_BACKEND_CPU);
  2848. // output
  2849. {
  2850. ggml_backend_type backend_norm;
  2851. ggml_backend_type backend_output;
  2852. if (n_gpu_layers > int(n_layer)) {
  2853. backend_norm = llama_backend_offload;
  2854. backend_output = llama_backend_offload_split;
  2855. } else {
  2856. backend_norm = GGML_BACKEND_CPU;
  2857. backend_output = GGML_BACKEND_CPU;
  2858. }
  2859. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2860. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2861. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2862. if (backend_norm == GGML_BACKEND_GPU) {
  2863. vram_weights += ggml_nbytes(model.output_norm);
  2864. vram_weights += ggml_nbytes(model.output_norm_b);
  2865. }
  2866. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2867. vram_weights += ggml_nbytes(model.output);
  2868. }
  2869. }
  2870. const uint32_t n_ff = hparams.n_ff;
  2871. const int i_gpu_start = n_layer - n_gpu_layers;
  2872. model.layers.resize(n_layer);
  2873. for (uint32_t i = 0; i < n_layer; ++i) {
  2874. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  2875. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  2876. auto & layer = model.layers[i];
  2877. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2878. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2879. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2880. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, backend);
  2881. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2882. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend);
  2883. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2884. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2885. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, backend_split);
  2886. layer.ffn_down_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, backend);
  2887. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2888. layer.ffn_up_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, backend);
  2889. if (backend == GGML_BACKEND_GPU) {
  2890. vram_weights +=
  2891. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  2892. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.bqkv) +
  2893. ggml_nbytes(layer.wo) + ggml_nbytes(layer.bo) +
  2894. ggml_nbytes(layer.ffn_norm) + ggml_nbytes(layer.ffn_norm_b) +
  2895. ggml_nbytes(layer.ffn_up) + ggml_nbytes(layer.ffn_up_b) +
  2896. ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_down_b);
  2897. }
  2898. }
  2899. } break;
  2900. case LLM_ARCH_MPT:
  2901. {
  2902. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2903. // output
  2904. {
  2905. ggml_backend_type backend_norm;
  2906. ggml_backend_type backend_output;
  2907. if (n_gpu_layers > int(n_layer)) {
  2908. backend_norm = llama_backend_offload;
  2909. backend_output = llama_backend_offload_split;
  2910. } else {
  2911. backend_norm = GGML_BACKEND_CPU;
  2912. backend_output = GGML_BACKEND_CPU;
  2913. }
  2914. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2915. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2916. if (backend_norm == GGML_BACKEND_GPU) {
  2917. vram_weights += ggml_nbytes(model.output_norm);
  2918. }
  2919. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2920. vram_weights += ggml_nbytes(model.output);
  2921. }
  2922. }
  2923. const uint32_t n_ff = hparams.n_ff;
  2924. const int i_gpu_start = n_layer - n_gpu_layers;
  2925. model.layers.resize(n_layer);
  2926. for (uint32_t i = 0; i < n_layer; ++i) {
  2927. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  2928. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  2929. auto & layer = model.layers[i];
  2930. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2931. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2932. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2933. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2934. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2935. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2936. if (backend == GGML_BACKEND_GPU) {
  2937. vram_weights +=
  2938. ggml_nbytes(layer.attn_norm) +
  2939. ggml_nbytes(layer.wqkv) +
  2940. ggml_nbytes(layer.wo) +
  2941. ggml_nbytes(layer.ffn_norm) +
  2942. ggml_nbytes(layer.ffn_down) +
  2943. ggml_nbytes(layer.ffn_up);
  2944. }
  2945. }
  2946. } break;
  2947. case LLM_ARCH_STABLELM:
  2948. {
  2949. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2950. // output
  2951. {
  2952. ggml_backend_type backend_norm;
  2953. ggml_backend_type backend_output;
  2954. if (n_gpu_layers > int(n_layer)) {
  2955. backend_norm = llama_backend_offload;
  2956. backend_output = llama_backend_offload_split;
  2957. } else {
  2958. backend_norm = GGML_BACKEND_CPU;
  2959. backend_output = GGML_BACKEND_CPU;
  2960. }
  2961. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2962. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2963. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2964. if (backend_norm == GGML_BACKEND_GPU) {
  2965. vram_weights += ggml_nbytes(model.output_norm);
  2966. }
  2967. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2968. vram_weights += ggml_nbytes(model.output);
  2969. }
  2970. }
  2971. const uint32_t n_ff = hparams.n_ff;
  2972. const int i_gpu_start = n_layer - n_gpu_layers;
  2973. model.layers.resize(n_layer);
  2974. for (uint32_t i = 0; i < n_layer; ++i) {
  2975. /*
  2976. llama_model_loader: - tensor 4: blk.0.attn_output.weight f16 [ 2560, 2560, 1, 1 ]
  2977. */
  2978. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  2979. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  2980. auto & layer = model.layers[i];
  2981. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2982. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2983. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  2984. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2985. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2986. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2987. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2988. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2989. layer.ffn_gate = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  2990. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2991. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2992. if (backend == GGML_BACKEND_GPU) {
  2993. vram_weights +=
  2994. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  2995. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  2996. ggml_nbytes(layer.ffn_gate) + ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  2997. }
  2998. }
  2999. } break;
  3000. case LLM_ARCH_QWEN:
  3001. {
  3002. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  3003. {
  3004. ggml_backend_type backend_norm;
  3005. ggml_backend_type backend_output;
  3006. if (n_gpu_layers > int(n_layer)) {
  3007. backend_norm = llama_backend_offload;
  3008. backend_output = llama_backend_offload_split;
  3009. } else {
  3010. backend_norm = GGML_BACKEND_CPU;
  3011. backend_output = GGML_BACKEND_CPU;
  3012. }
  3013. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  3014. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  3015. if (backend_norm == GGML_BACKEND_GPU) {
  3016. vram_weights += ggml_nbytes(model.output_norm);
  3017. }
  3018. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  3019. vram_weights += ggml_nbytes(model.output);
  3020. }
  3021. }
  3022. const uint32_t n_ff = hparams.n_ff / 2;
  3023. const int i_gpu_start = n_layer - n_gpu_layers;
  3024. model.layers.resize(n_layer);
  3025. for (uint32_t i = 0; i < n_layer; ++i) {
  3026. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload; // NOLINT
  3027. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : llama_backend_offload_split; // NOLINT
  3028. auto & layer = model.layers[i];
  3029. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  3030. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd * 3}, backend_split);
  3031. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd * 3}, backend);
  3032. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  3033. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  3034. layer.ffn_gate = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  3035. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  3036. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  3037. if (backend == GGML_BACKEND_GPU) {
  3038. vram_weights +=
  3039. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.bqkv) +
  3040. ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) + ggml_nbytes(layer.ffn_gate) +
  3041. ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  3042. }
  3043. }
  3044. } break;
  3045. default:
  3046. throw std::runtime_error("unknown architecture");
  3047. }
  3048. }
  3049. ml.done_getting_tensors();
  3050. // print memory requirements
  3051. {
  3052. // this is the total memory required to run the inference
  3053. size_t mem_required =
  3054. ctx_size +
  3055. mmapped_size - vram_weights; // weights in VRAM not in memory
  3056. LLAMA_LOG_INFO("%s: mem required = %7.2f MiB\n", __func__, mem_required / 1024.0 / 1024.0);
  3057. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  3058. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3059. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3060. if (n_gpu_layers > (int) hparams.n_layer) {
  3061. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3062. }
  3063. #ifdef GGML_USE_CUBLAS
  3064. const int max_backend_supported_layers = hparams.n_layer + 1;
  3065. const int max_offloadable_layers = hparams.n_layer + 1;
  3066. #elif GGML_USE_CLBLAST
  3067. const int max_backend_supported_layers = hparams.n_layer + 1;
  3068. const int max_offloadable_layers = hparams.n_layer + 1;
  3069. #endif // GGML_USE_CUBLAS
  3070. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3071. LLAMA_LOG_INFO("%s: VRAM used: %.2f MiB\n", __func__, vram_weights / 1024.0 / 1024.0);
  3072. #else
  3073. (void) n_gpu_layers;
  3074. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  3075. }
  3076. // populate `tensors_by_name`
  3077. for (int i = 0; i < ml.n_tensors; ++i) {
  3078. struct ggml_tensor * cur = ggml_get_tensor(ctx, ml.get_tensor_name(i));
  3079. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3080. }
  3081. (void) tensor_split;
  3082. #ifdef GGML_USE_CUBLAS
  3083. {
  3084. ggml_cuda_set_tensor_split(tensor_split);
  3085. }
  3086. #endif
  3087. ml.load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  3088. if (progress_callback) {
  3089. progress_callback(1.0f, progress_callback_user_data);
  3090. }
  3091. model.mapping = std::move(ml.mapping);
  3092. // loading time will be recalculate after the first eval, so
  3093. // we take page faults deferred by mmap() into consideration
  3094. model.t_load_us = ggml_time_us() - model.t_start_us;
  3095. }
  3096. static bool llama_model_load(const std::string & fname, llama_model & model, const llama_model_params & params) {
  3097. try {
  3098. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3099. model.hparams.vocab_only = params.vocab_only;
  3100. llm_load_arch (ml, model);
  3101. llm_load_hparams(ml, model);
  3102. llm_load_vocab (ml, model);
  3103. llm_load_print_meta(ml, model);
  3104. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3105. throw std::runtime_error("vocab size mismatch");
  3106. }
  3107. if (params.vocab_only) {
  3108. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3109. return true;
  3110. }
  3111. llm_load_tensors(
  3112. ml, model, params.n_gpu_layers, params.main_gpu, params.tensor_split, params.use_mlock,
  3113. params.progress_callback, params.progress_callback_user_data
  3114. );
  3115. } catch (const std::exception & err) {
  3116. LLAMA_LOG_ERROR("error loading model: %s\n", err.what());
  3117. return false;
  3118. }
  3119. return true;
  3120. }
  3121. //
  3122. // llm_build
  3123. //
  3124. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3125. enum llm_rope_type {
  3126. LLM_ROPE,
  3127. LLM_ROPE_NEOX,
  3128. LLM_ROPE_GLM,
  3129. };
  3130. enum llm_ffn_op_type {
  3131. LLM_FFN_SILU,
  3132. LLM_FFN_GELU,
  3133. LLM_FFN_RELU,
  3134. LLM_FFN_RELU_SQR,
  3135. };
  3136. enum llm_ffn_gate_type {
  3137. LLM_FFN_SEQ,
  3138. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3139. };
  3140. enum llm_norm_type {
  3141. LLM_NORM,
  3142. LLM_NORM_RMS,
  3143. };
  3144. static struct ggml_tensor * llm_build_inp_embd(
  3145. struct ggml_context * ctx,
  3146. const llama_hparams & hparams,
  3147. const llama_batch & batch,
  3148. struct ggml_tensor * tok_embd,
  3149. const llm_build_cb & cb) {
  3150. const int64_t n_embd = hparams.n_embd;
  3151. struct ggml_tensor * inpL;
  3152. if (batch.token) {
  3153. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  3154. cb(inp_tokens, "inp_tokens", -1);
  3155. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens);
  3156. } else {
  3157. #ifdef GGML_USE_MPI
  3158. GGML_ASSERT(false && "not implemented");
  3159. #endif
  3160. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  3161. }
  3162. return inpL;
  3163. }
  3164. // Persimmon: n_rot = n_embd_head/2
  3165. // Other: n_rot = n_embd_head
  3166. static void llm_build_k_shift(
  3167. struct ggml_context * ctx,
  3168. const llama_hparams & hparams,
  3169. const llama_cparams & cparams,
  3170. const llama_kv_cache & kv,
  3171. struct ggml_cgraph * graph,
  3172. llm_rope_type type,
  3173. int64_t n_ctx,
  3174. int n_rot,
  3175. float freq_base,
  3176. float freq_scale,
  3177. const llm_build_cb & cb) {
  3178. const int64_t n_layer = hparams.n_layer;
  3179. const int64_t n_head_kv = hparams.n_head_kv;
  3180. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3181. const int64_t n_embd_head = hparams.n_embd_head();
  3182. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3183. const float ext_factor = cparams.yarn_ext_factor;
  3184. const float attn_factor = cparams.yarn_attn_factor;
  3185. const float beta_fast = cparams.yarn_beta_fast;
  3186. const float beta_slow = cparams.yarn_beta_slow;
  3187. GGML_ASSERT(n_embd_head % n_rot == 0);
  3188. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_ctx);
  3189. cb(K_shift, "K_shift", -1);
  3190. int rope_type = 0;
  3191. switch (type) {
  3192. case LLM_ROPE: rope_type = 0; break;
  3193. case LLM_ROPE_NEOX: rope_type = 2; break;
  3194. case LLM_ROPE_GLM: rope_type = 4; break;
  3195. }
  3196. for (int il = 0; il < n_layer; ++il) {
  3197. struct ggml_tensor * tmp =
  3198. // we rotate only the first n_rot dimensions
  3199. ggml_rope_custom_inplace(ctx,
  3200. ggml_view_3d(ctx, kv.k_l[il],
  3201. n_embd_head, n_head_kv, n_ctx,
  3202. ggml_row_size(kv.k_l[il]->type, n_embd_head),
  3203. ggml_row_size(kv.k_l[il]->type, n_embd_gqa),
  3204. 0),
  3205. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3206. ext_factor, attn_factor, beta_fast, beta_slow);
  3207. cb(tmp, "K_shifted", il);
  3208. ggml_build_forward_expand(graph, tmp);
  3209. }
  3210. }
  3211. static void llm_build_kv_store(
  3212. struct ggml_context * ctx,
  3213. const llama_hparams & hparams,
  3214. const llama_kv_cache & kv,
  3215. struct ggml_cgraph * graph,
  3216. struct ggml_tensor * k_cur,
  3217. struct ggml_tensor * v_cur,
  3218. int64_t n_ctx,
  3219. int32_t n_tokens,
  3220. int32_t kv_head,
  3221. const llm_build_cb & cb,
  3222. int64_t il) {
  3223. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3224. // compute the transposed [n_tokens, n_embd] V matrix
  3225. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_gqa, n_tokens));
  3226. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3227. cb(v_cur_t, "v_cur_t", il);
  3228. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_gqa,
  3229. (ggml_row_size(kv.k_l[il]->type, n_embd_gqa))*kv_head);
  3230. cb(k_cache_view, "k_cache_view", il);
  3231. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_gqa,
  3232. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3233. (kv_head)*ggml_element_size(kv.v_l[il]));
  3234. cb(v_cache_view, "v_cache_view", il);
  3235. // important: storing RoPE-ed version of K in the KV cache!
  3236. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3237. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3238. }
  3239. static struct ggml_tensor * llm_build_norm(
  3240. struct ggml_context * ctx,
  3241. struct ggml_tensor * cur,
  3242. const llama_hparams & hparams,
  3243. struct ggml_tensor * mw,
  3244. struct ggml_tensor * mb,
  3245. llm_norm_type type,
  3246. const llm_build_cb & cb,
  3247. int il) {
  3248. switch (type) {
  3249. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3250. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3251. }
  3252. if (mw || mb) {
  3253. cb(cur, "norm", il);
  3254. }
  3255. if (mw) {
  3256. cur = ggml_mul(ctx, cur, mw);
  3257. if (mb) {
  3258. cb(cur, "norm_w", il);
  3259. }
  3260. }
  3261. if (mb) {
  3262. cur = ggml_add(ctx, cur, mb);
  3263. }
  3264. return cur;
  3265. }
  3266. static struct ggml_tensor * llm_build_ffn(
  3267. struct ggml_context * ctx,
  3268. struct ggml_tensor * cur,
  3269. struct ggml_tensor * up,
  3270. struct ggml_tensor * up_b,
  3271. struct ggml_tensor * gate,
  3272. struct ggml_tensor * gate_b,
  3273. struct ggml_tensor * down,
  3274. struct ggml_tensor * down_b,
  3275. llm_ffn_op_type type_op,
  3276. llm_ffn_gate_type type_gate,
  3277. const llm_build_cb & cb,
  3278. int il) {
  3279. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3280. cb(tmp, "ffn_up", il);
  3281. if (up_b) {
  3282. tmp = ggml_add(ctx, tmp, up_b);
  3283. cb(tmp, "ffn_up_b", il);
  3284. }
  3285. if (gate) {
  3286. switch (type_gate) {
  3287. case LLM_FFN_SEQ:
  3288. {
  3289. cur = ggml_mul_mat(ctx, gate, tmp);
  3290. cb(cur, "ffn_gate", il);
  3291. } break;
  3292. case LLM_FFN_PAR:
  3293. {
  3294. cur = ggml_mul_mat(ctx, gate, cur);
  3295. cb(cur, "ffn_gate", il);
  3296. } break;
  3297. }
  3298. if (gate_b) {
  3299. cur = ggml_add(ctx, cur, gate_b);
  3300. cb(cur, "ffn_gate_b", il);
  3301. }
  3302. } else {
  3303. cur = tmp;
  3304. }
  3305. switch (type_op) {
  3306. case LLM_FFN_SILU:
  3307. {
  3308. cur = ggml_silu(ctx, cur);
  3309. cb(cur, "ffn_silu", il);
  3310. } break;
  3311. case LLM_FFN_GELU:
  3312. {
  3313. cur = ggml_gelu(ctx, cur);
  3314. cb(cur, "ffn_gelu", il);
  3315. } break;
  3316. case LLM_FFN_RELU:
  3317. {
  3318. cur = ggml_relu(ctx, cur);
  3319. cb(cur, "ffn_relu", il);
  3320. } break;
  3321. case LLM_FFN_RELU_SQR:
  3322. {
  3323. cur = ggml_relu(ctx, cur);
  3324. cb(cur, "ffn_relu", il);
  3325. cur = ggml_sqr(ctx, cur);
  3326. cb(cur, "ffn_sqr(relu)", il);
  3327. } break;
  3328. }
  3329. if (type_gate == LLM_FFN_PAR) {
  3330. cur = ggml_mul(ctx, cur, tmp);
  3331. cb(cur, "ffn_gate_par", il);
  3332. }
  3333. cur = ggml_mul_mat(ctx, down, cur);
  3334. if (down_b) {
  3335. cb(cur, "ffn_down", il);
  3336. }
  3337. if (down_b) {
  3338. cur = ggml_add(ctx, cur, down_b);
  3339. }
  3340. return cur;
  3341. }
  3342. // if max_alibi_bias > 0 then apply ALiBi
  3343. static struct ggml_tensor * llm_build_kqv(
  3344. struct ggml_context * ctx,
  3345. const llama_hparams & hparams,
  3346. const llama_kv_cache & kv,
  3347. struct ggml_tensor * wo,
  3348. struct ggml_tensor * wo_b,
  3349. struct ggml_tensor * q_cur,
  3350. struct ggml_tensor * kq_scale,
  3351. struct ggml_tensor * kq_mask,
  3352. int64_t n_ctx,
  3353. int32_t n_tokens,
  3354. int32_t n_kv,
  3355. float max_alibi_bias,
  3356. const llm_build_cb & cb,
  3357. int il) {
  3358. const int64_t n_embd = hparams.n_embd;
  3359. const int64_t n_head = hparams.n_head;
  3360. const int64_t n_head_kv = hparams.n_head_kv;
  3361. const int64_t n_embd_head = hparams.n_embd_head();
  3362. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3363. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3364. cb(q, "q", il);
  3365. struct ggml_tensor * k =
  3366. ggml_view_3d(ctx, kv.k_l[il],
  3367. n_embd_head, n_kv, n_head_kv,
  3368. ggml_row_size(kv.k_l[il]->type, n_embd_gqa),
  3369. ggml_row_size(kv.k_l[il]->type, n_embd_head),
  3370. 0);
  3371. cb(k, "k", il);
  3372. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3373. cb(kq, "kq", il);
  3374. if (max_alibi_bias > 0.0f) {
  3375. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3376. kq = ggml_scale(ctx, kq, kq_scale);
  3377. cb(kq, "kq_scaled", il);
  3378. if (max_alibi_bias > 0.0f) {
  3379. // TODO: n_head or n_head_kv
  3380. // TODO: K-shift is likely not working
  3381. // TODO: change to ggml_add
  3382. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3383. cb(kq, "kq_scaled_alibi", il);
  3384. }
  3385. kq = ggml_add(ctx, kq, kq_mask);
  3386. cb(kq, "kq_masked", il);
  3387. kq = ggml_soft_max(ctx, kq);
  3388. cb(kq, "kq_soft_max", il);
  3389. } else {
  3390. kq = ggml_soft_max_ext(ctx, kq, kq_mask, 1.0f/sqrtf(float(n_embd_head)));
  3391. cb(kq, "kq_soft_max_ext", il);
  3392. }
  3393. // split cached v into n_head heads
  3394. struct ggml_tensor * v =
  3395. ggml_view_3d(ctx, kv.v_l[il],
  3396. n_kv, n_embd_head, n_head_kv,
  3397. ggml_element_size(kv.v_l[il])*n_ctx,
  3398. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head,
  3399. 0);
  3400. cb(v, "v", il);
  3401. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3402. cb(kqv, "kqv", il);
  3403. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3404. cb(kqv_merged, "kqv_merged", il);
  3405. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd, n_tokens);
  3406. cb(cur, "kqv_merged_cont", il);
  3407. cur = ggml_mul_mat(ctx, wo, cur);
  3408. if (wo_b) {
  3409. cb(cur, "kqv_wo", il);
  3410. }
  3411. if (wo_b) {
  3412. cur = ggml_add(ctx, cur, wo_b);
  3413. }
  3414. return cur;
  3415. }
  3416. struct llm_build_context {
  3417. const llama_model & model;
  3418. const llama_hparams & hparams;
  3419. const llama_cparams & cparams;
  3420. const llama_batch & batch;
  3421. const llama_kv_cache & kv_self;
  3422. const int64_t n_embd;
  3423. const int64_t n_layer;
  3424. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3425. const int64_t n_head;
  3426. const int64_t n_head_kv;
  3427. const int64_t n_embd_head;
  3428. const int64_t n_embd_gqa;
  3429. const int64_t n_expert;
  3430. const int64_t n_expert_used;
  3431. const float freq_base;
  3432. const float freq_scale;
  3433. const float ext_factor;
  3434. const float attn_factor;
  3435. const float beta_fast;
  3436. const float beta_slow;
  3437. const float norm_eps;
  3438. const float norm_rms_eps;
  3439. const int32_t n_tokens;
  3440. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3441. const int32_t kv_head; // index of where we store new KV data in the cache
  3442. const int32_t n_orig_ctx;
  3443. const bool do_rope_shift;
  3444. const llm_build_cb & cb;
  3445. llama_buffer & buf_compute;
  3446. struct ggml_context * ctx0 = nullptr;
  3447. // TODO: consider making the entire interface noexcept
  3448. llm_build_context(
  3449. llama_context & lctx,
  3450. const llama_batch & batch,
  3451. const llm_build_cb & cb,
  3452. bool worst_case) :
  3453. model (lctx.model),
  3454. hparams (model.hparams),
  3455. cparams (lctx.cparams),
  3456. batch (batch),
  3457. kv_self (lctx.kv_self),
  3458. n_embd (hparams.n_embd),
  3459. n_layer (hparams.n_layer),
  3460. n_ctx (cparams.n_ctx),
  3461. n_head (hparams.n_head),
  3462. n_head_kv (hparams.n_head_kv),
  3463. n_embd_head (hparams.n_embd_head()),
  3464. n_embd_gqa (hparams.n_embd_gqa()),
  3465. n_expert (hparams.n_expert),
  3466. n_expert_used (hparams.n_expert_used),
  3467. freq_base (cparams.rope_freq_base),
  3468. freq_scale (cparams.rope_freq_scale),
  3469. ext_factor (cparams.yarn_ext_factor),
  3470. attn_factor (cparams.yarn_attn_factor),
  3471. beta_fast (cparams.yarn_beta_fast),
  3472. beta_slow (cparams.yarn_beta_slow),
  3473. norm_eps (hparams.f_norm_eps),
  3474. norm_rms_eps (hparams.f_norm_rms_eps),
  3475. n_tokens (batch.n_tokens),
  3476. n_kv (worst_case ? n_ctx : kv_self.n),
  3477. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3478. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3479. do_rope_shift (worst_case || kv_self.has_shift),
  3480. cb (cb),
  3481. buf_compute (lctx.buf_compute) {
  3482. GGML_ASSERT(!!kv_self.ctx);
  3483. // all initializations should be done in init()
  3484. }
  3485. void init() {
  3486. struct ggml_init_params params = {
  3487. /*.mem_size =*/ buf_compute.size,
  3488. /*.mem_buffer =*/ buf_compute.data,
  3489. /*.no_alloc =*/ true,
  3490. };
  3491. ctx0 = ggml_init(params);
  3492. }
  3493. void free() {
  3494. if (ctx0) {
  3495. ggml_free(ctx0);
  3496. ctx0 = nullptr;
  3497. }
  3498. }
  3499. struct ggml_cgraph * build_llama() {
  3500. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3501. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3502. struct ggml_tensor * cur;
  3503. struct ggml_tensor * inpL;
  3504. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3505. cb(inpL, "inp_embd", -1);
  3506. // inp_pos - contains the positions
  3507. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3508. cb(inp_pos, "inp_pos", -1);
  3509. // KQ_scale
  3510. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3511. cb(KQ_scale, "KQ_scale", -1);
  3512. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3513. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3514. cb(KQ_mask, "KQ_mask", -1);
  3515. // shift the entire K-cache if needed
  3516. if (do_rope_shift) {
  3517. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, n_embd_head, freq_base, freq_scale, cb);
  3518. }
  3519. for (int il = 0; il < n_layer; ++il) {
  3520. struct ggml_tensor * inpSA = inpL;
  3521. // norm
  3522. cur = llm_build_norm(ctx0, inpL, hparams,
  3523. model.layers[il].attn_norm, NULL,
  3524. LLM_NORM_RMS, cb, il);
  3525. cb(cur, "attn_norm", il);
  3526. // self-attention
  3527. {
  3528. // compute Q and K and RoPE them
  3529. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3530. cb(Qcur, "Qcur", il);
  3531. if (model.layers[il].bq) {
  3532. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3533. cb(Qcur, "Qcur", il);
  3534. }
  3535. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3536. cb(Kcur, "Kcur", il);
  3537. if (model.layers[il].bk) {
  3538. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3539. cb(Kcur, "Kcur", il);
  3540. }
  3541. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3542. cb(Vcur, "Vcur", il);
  3543. if (model.layers[il].bv) {
  3544. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3545. cb(Vcur, "Vcur", il);
  3546. }
  3547. Qcur = ggml_rope_custom(
  3548. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3549. n_embd_head, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3550. ext_factor, attn_factor, beta_fast, beta_slow
  3551. );
  3552. cb(Qcur, "Qcur", il);
  3553. Kcur = ggml_rope_custom(
  3554. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3555. n_embd_head, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3556. ext_factor, attn_factor, beta_fast, beta_slow
  3557. );
  3558. cb(Kcur, "Kcur", il);
  3559. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3560. cur = llm_build_kqv(ctx0, hparams, kv_self,
  3561. model.layers[il].wo, model.layers[il].bo,
  3562. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, cb, il);
  3563. cb(cur, "kqv_out", il);
  3564. }
  3565. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3566. cb(ffn_inp, "ffn_inp", il);
  3567. // feed-forward network
  3568. if (model.layers[il].ffn_gate_inp == nullptr) {
  3569. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3570. model.layers[il].ffn_norm, NULL,
  3571. LLM_NORM_RMS, cb, il);
  3572. cb(cur, "ffn_norm", il);
  3573. cur = llm_build_ffn(ctx0, cur,
  3574. model.layers[il].ffn_up, NULL,
  3575. model.layers[il].ffn_gate, NULL,
  3576. model.layers[il].ffn_down, NULL,
  3577. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3578. cb(cur, "ffn_out", il);
  3579. } else {
  3580. // MoE branch
  3581. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3582. model.layers[il].ffn_norm, NULL,
  3583. LLM_NORM_RMS, cb, il);
  3584. cb(cur, "ffn_norm", il);
  3585. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  3586. cb(logits, "ffn_moe_logits", il);
  3587. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  3588. cb(probs, "ffn_moe_probs", il);
  3589. // select experts
  3590. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  3591. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  3592. ggml_tensor * weights = ggml_get_rows(ctx0,
  3593. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  3594. cb(weights, "ffn_moe_weights", il);
  3595. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  3596. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  3597. cb(weights_sum, "ffn_moe_weights_sum", il);
  3598. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  3599. cb(weights, "ffn_moe_weights_norm", il);
  3600. // compute expert outputs
  3601. ggml_tensor * moe_out = nullptr;
  3602. for (int i = 0; i < n_expert_used; ++i) {
  3603. ggml_tensor * cur_expert;
  3604. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  3605. cb(cur_up, "ffn_moe_up", il);
  3606. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  3607. cb(cur_gate, "ffn_moe_gate", il);
  3608. cur_gate = ggml_silu(ctx0, cur_gate);
  3609. cb(cur_gate, "ffn_moe_silu", il);
  3610. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  3611. cb(cur_expert, "ffn_moe_gate_par", il);
  3612. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  3613. cb(cur_expert, "ffn_moe_down", il);
  3614. cur_expert = ggml_mul(ctx0, cur_expert,
  3615. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  3616. cb(cur_expert, "ffn_moe_weighted", il);
  3617. if (i == 0) {
  3618. moe_out = cur_expert;
  3619. } else {
  3620. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  3621. cb(moe_out, "ffn_moe_out", il);
  3622. }
  3623. }
  3624. cur = moe_out;
  3625. }
  3626. cur = ggml_add(ctx0, cur, ffn_inp);
  3627. cb(cur, "l_out", il);
  3628. // input for next layer
  3629. inpL = cur;
  3630. }
  3631. cur = inpL;
  3632. cur = llm_build_norm(ctx0, cur, hparams,
  3633. model.output_norm, NULL,
  3634. LLM_NORM_RMS, cb, -1);
  3635. cb(cur, "result_norm", -1);
  3636. // lm_head
  3637. cur = ggml_mul_mat(ctx0, model.output, cur);
  3638. cb(cur, "result_output", -1);
  3639. ggml_build_forward_expand(gf, cur);
  3640. return gf;
  3641. }
  3642. struct ggml_cgraph * build_baichuan() {
  3643. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3644. struct ggml_tensor * cur;
  3645. struct ggml_tensor * inpL;
  3646. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3647. cb(inpL, "inp_embd", -1);
  3648. // inp_pos - contains the positions
  3649. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3650. cb(inp_pos, "inp_pos", -1);
  3651. // KQ_scale
  3652. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3653. cb(KQ_scale, "KQ_scale", -1);
  3654. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3655. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3656. cb(KQ_mask, "KQ_mask", -1);
  3657. // shift the entire K-cache if needed
  3658. if (do_rope_shift) {
  3659. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, n_embd_head, freq_base, freq_scale, cb);
  3660. }
  3661. for (int il = 0; il < n_layer; ++il) {
  3662. struct ggml_tensor * inpSA = inpL;
  3663. cur = llm_build_norm(ctx0, inpL, hparams,
  3664. model.layers[il].attn_norm, NULL,
  3665. LLM_NORM_RMS, cb, il);
  3666. cb(cur, "attn_norm", il);
  3667. // self-attention
  3668. {
  3669. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3670. cb(Qcur, "Qcur", il);
  3671. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3672. cb(Kcur, "Kcur", il);
  3673. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3674. cb(Vcur, "Vcur", il);
  3675. switch (model.type) {
  3676. case MODEL_7B:
  3677. Qcur = ggml_rope_custom(
  3678. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3679. n_embd_head, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3680. ext_factor, attn_factor, beta_fast, beta_slow
  3681. );
  3682. Kcur = ggml_rope_custom(
  3683. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3684. n_embd_head, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3685. ext_factor, attn_factor, beta_fast, beta_slow
  3686. );
  3687. break;
  3688. case MODEL_13B:
  3689. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  3690. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  3691. break;
  3692. default:
  3693. GGML_ASSERT(false);
  3694. }
  3695. cb(Qcur, "Qcur", il);
  3696. cb(Kcur, "Kcur", il);
  3697. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3698. // apply ALiBi for 13B model
  3699. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  3700. cur = llm_build_kqv(ctx0, hparams, kv_self,
  3701. model.layers[il].wo, NULL,
  3702. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, cb, il);
  3703. cb(cur, "kqv_out", il);
  3704. }
  3705. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3706. cb(ffn_inp, "ffn_inp", il);
  3707. // feed-forward network
  3708. {
  3709. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3710. model.layers[il].ffn_norm, NULL,
  3711. LLM_NORM_RMS, cb, il);
  3712. cb(cur, "ffn_norm", il);
  3713. cur = llm_build_ffn(ctx0, cur,
  3714. model.layers[il].ffn_up, NULL,
  3715. model.layers[il].ffn_gate, NULL,
  3716. model.layers[il].ffn_down, NULL,
  3717. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3718. cb(cur, "ffn_out", il);
  3719. }
  3720. cur = ggml_add(ctx0, cur, ffn_inp);
  3721. cb(cur, "l_out", il);
  3722. // input for next layer
  3723. inpL = cur;
  3724. }
  3725. cur = inpL;
  3726. cur = llm_build_norm(ctx0, cur, hparams,
  3727. model.output_norm, NULL,
  3728. LLM_NORM_RMS, cb, -1);
  3729. cb(cur, "result_norm", -1);
  3730. // lm_head
  3731. cur = ggml_mul_mat(ctx0, model.output, cur);
  3732. cb(cur, "result_output", -1);
  3733. ggml_build_forward_expand(gf, cur);
  3734. return gf;
  3735. }
  3736. struct ggml_cgraph * build_falcon() {
  3737. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3738. struct ggml_tensor * cur;
  3739. struct ggml_tensor * inpL;
  3740. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3741. cb(inpL, "inp_embd", -1);
  3742. // inp_pos - contains the positions
  3743. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3744. cb(inp_pos, "inp_pos", -1);
  3745. // KQ_scale
  3746. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3747. cb(KQ_scale, "KQ_scale", -1);
  3748. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3749. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3750. cb(KQ_mask, "KQ_mask", -1);
  3751. // shift the entire K-cache if needed
  3752. if (do_rope_shift) {
  3753. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, n_embd_head, freq_base, freq_scale, cb);
  3754. }
  3755. for (int il = 0; il < n_layer; ++il) {
  3756. struct ggml_tensor * attn_norm;
  3757. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  3758. model.layers[il].attn_norm,
  3759. model.layers[il].attn_norm_b,
  3760. LLM_NORM, cb, il);
  3761. cb(attn_norm, "attn_norm", il);
  3762. // self-attention
  3763. {
  3764. if (model.layers[il].attn_norm_2) {
  3765. // Falcon-40B
  3766. cur = llm_build_norm(ctx0, inpL, hparams,
  3767. model.layers[il].attn_norm_2,
  3768. model.layers[il].attn_norm_2_b,
  3769. LLM_NORM, cb, il);
  3770. cb(cur, "attn_norm_2", il);
  3771. } else {
  3772. cur = attn_norm;
  3773. }
  3774. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3775. cb(cur, "wqkv", il);
  3776. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3777. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  3778. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  3779. cb(Qcur, "Qcur", il);
  3780. cb(Kcur, "Kcur", il);
  3781. cb(Vcur, "Vcur", il);
  3782. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3783. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  3784. // using mode = 2 for neox mode
  3785. Qcur = ggml_rope_custom(
  3786. ctx0, Qcur, inp_pos, n_embd_head, 2, 0, n_orig_ctx,
  3787. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3788. );
  3789. cb(Qcur, "Qcur", il);
  3790. Kcur = ggml_rope_custom(
  3791. ctx0, Kcur, inp_pos, n_embd_head, 2, 0, n_orig_ctx,
  3792. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3793. );
  3794. cb(Kcur, "Kcur", il);
  3795. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3796. cur = llm_build_kqv(ctx0, hparams, kv_self,
  3797. model.layers[il].wo, NULL,
  3798. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, cb, il);
  3799. cb(cur, "kqv_out", il);
  3800. }
  3801. struct ggml_tensor * ffn_inp = cur;
  3802. // feed forward
  3803. {
  3804. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  3805. model.layers[il].ffn_up, NULL,
  3806. NULL, NULL,
  3807. model.layers[il].ffn_down, NULL,
  3808. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3809. cb(cur, "ffn_out", il);
  3810. }
  3811. cur = ggml_add(ctx0, cur, ffn_inp);
  3812. cb(cur, "l_out", il);
  3813. cur = ggml_add(ctx0, cur, inpL);
  3814. cb(cur, "l_out", il);
  3815. // input for next layer
  3816. inpL = cur;
  3817. }
  3818. cur = inpL;
  3819. // norm
  3820. cur = llm_build_norm(ctx0, cur, hparams,
  3821. model.output_norm,
  3822. model.output_norm_b,
  3823. LLM_NORM, cb, -1);
  3824. cb(cur, "result_norm", -1);
  3825. cur = ggml_mul_mat(ctx0, model.output, cur);
  3826. cb(cur, "result_output", -1);
  3827. ggml_build_forward_expand(gf, cur);
  3828. return gf;
  3829. }
  3830. struct ggml_cgraph * build_starcoder() {
  3831. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3832. struct ggml_tensor * cur;
  3833. struct ggml_tensor * pos;
  3834. struct ggml_tensor * inpL;
  3835. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3836. cb(inpL, "inp_embd", -1);
  3837. // inp_pos - contains the positions
  3838. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3839. cb(inp_pos, "inp_pos", -1);
  3840. // KQ_scale
  3841. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3842. cb(KQ_scale, "KQ_scale", -1);
  3843. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3844. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3845. cb(KQ_mask, "KQ_mask", -1);
  3846. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  3847. cb(pos, "pos_embd", -1);
  3848. inpL = ggml_add(ctx0, inpL, pos);
  3849. cb(inpL, "inpL", -1);
  3850. for (int il = 0; il < n_layer; ++il) {
  3851. cur = llm_build_norm(ctx0, inpL, hparams,
  3852. model.layers[il].attn_norm,
  3853. model.layers[il].attn_norm_b,
  3854. LLM_NORM, cb, il);
  3855. cb(cur, "attn_norm", il);
  3856. // self-attention
  3857. {
  3858. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3859. cb(cur, "wqkv", il);
  3860. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3861. cb(cur, "bqkv", il);
  3862. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3863. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  3864. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  3865. cb(Qcur, "Qcur", il);
  3866. cb(Kcur, "Kcur", il);
  3867. cb(Vcur, "Vcur", il);
  3868. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3869. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3870. cur = llm_build_kqv(ctx0, hparams, kv_self,
  3871. model.layers[il].wo, model.layers[il].bo,
  3872. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, cb, il);
  3873. cb(cur, "kqv_out", il);
  3874. }
  3875. // add the input
  3876. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  3877. cb(ffn_inp, "ffn_inp", il);
  3878. // FF
  3879. {
  3880. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3881. model.layers[il].ffn_norm,
  3882. model.layers[il].ffn_norm_b,
  3883. LLM_NORM, cb, il);
  3884. cb(cur, "ffn_norm", il);
  3885. cur = llm_build_ffn(ctx0, cur,
  3886. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  3887. NULL, NULL,
  3888. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  3889. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3890. cb(cur, "ffn_out", il);
  3891. }
  3892. inpL = ggml_add(ctx0, cur, ffn_inp);
  3893. cb(inpL, "l_out", il);
  3894. }
  3895. cur = llm_build_norm(ctx0, inpL, hparams,
  3896. model.output_norm,
  3897. model.output_norm_b,
  3898. LLM_NORM, cb, -1);
  3899. cb(cur, "result_norm", -1);
  3900. cur = ggml_mul_mat(ctx0, model.output, cur);
  3901. cb(cur, "result_output", -1);
  3902. ggml_build_forward_expand(gf, cur);
  3903. return gf;
  3904. }
  3905. struct ggml_cgraph * build_persimmon() {
  3906. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3907. const int64_t n_rot = n_embd_head / 2;
  3908. struct ggml_tensor * cur;
  3909. struct ggml_tensor * inpL;
  3910. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3911. cb(inpL, "imp_embd", -1);
  3912. // inp_pos - contains the positions
  3913. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3914. cb(inp_pos, "inp_pos", -1);
  3915. // KQ_scale
  3916. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3917. cb(KQ_scale, "KQ_scale", -1);
  3918. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3919. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3920. cb(KQ_mask, "KQ_mask", -1);
  3921. if (do_rope_shift) {
  3922. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, n_embd_head, freq_base, freq_scale, cb);
  3923. }
  3924. for (int il = 0; il < n_layer; ++il) {
  3925. struct ggml_tensor * residual = inpL;
  3926. cur = llm_build_norm(ctx0, inpL, hparams,
  3927. model.layers[il].attn_norm,
  3928. model.layers[il].attn_norm_b,
  3929. LLM_NORM, cb, il);
  3930. cb(cur, "attn_norm", il);
  3931. // self attention
  3932. {
  3933. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3934. cb(cur, "wqkv", il);
  3935. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3936. cb(cur, "bqkv", il);
  3937. // split qkv
  3938. GGML_ASSERT(n_head_kv == n_head);
  3939. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  3940. cb(tmpqkv, "tmpqkv", il);
  3941. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  3942. cb(tmpqkv_perm, "tmpqkv", il);
  3943. struct ggml_tensor * tmpq = ggml_view_3d(
  3944. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  3945. ggml_element_size(tmpqkv_perm) * n_embd_head,
  3946. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  3947. 0
  3948. );
  3949. cb(tmpq, "tmpq", il);
  3950. struct ggml_tensor * tmpk = ggml_view_3d(
  3951. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  3952. ggml_element_size(tmpqkv_perm) * n_embd_head,
  3953. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  3954. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  3955. );
  3956. cb(tmpk, "tmpk", il);
  3957. // Q/K Layernorm
  3958. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  3959. model.layers[il].attn_q_norm,
  3960. model.layers[il].attn_q_norm_b,
  3961. LLM_NORM, cb, il);
  3962. cb(tmpq, "tmpq", il);
  3963. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  3964. model.layers[il].attn_k_norm,
  3965. model.layers[il].attn_k_norm_b,
  3966. LLM_NORM, cb, il);
  3967. cb(tmpk, "tmpk", il);
  3968. // RoPE the first n_rot of q/k, pass the other half, and concat.
  3969. struct ggml_tensor * qrot = ggml_view_3d(
  3970. ctx0, tmpq, n_rot, n_head, n_tokens,
  3971. ggml_element_size(tmpq) * n_embd_head,
  3972. ggml_element_size(tmpq) * n_embd_head * n_head,
  3973. 0
  3974. );
  3975. cb(qrot, "qrot", il);
  3976. struct ggml_tensor * krot = ggml_view_3d(
  3977. ctx0, tmpk, n_rot, n_head, n_tokens,
  3978. ggml_element_size(tmpk) * n_embd_head,
  3979. ggml_element_size(tmpk) * n_embd_head * n_head,
  3980. 0
  3981. );
  3982. cb(krot, "krot", il);
  3983. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  3984. struct ggml_tensor * qpass = ggml_view_3d(
  3985. ctx0, tmpq, n_rot, n_head, n_tokens,
  3986. ggml_element_size(tmpq) * n_embd_head,
  3987. ggml_element_size(tmpq) * n_embd_head * n_head,
  3988. ggml_element_size(tmpq) * n_rot
  3989. );
  3990. cb(qpass, "qpass", il);
  3991. struct ggml_tensor * kpass = ggml_view_3d(
  3992. ctx0, tmpk, n_rot, n_head, n_tokens,
  3993. ggml_element_size(tmpk) * n_embd_head,
  3994. ggml_element_size(tmpk) * n_embd_head * n_head,
  3995. ggml_element_size(tmpk) * n_rot
  3996. );
  3997. cb(kpass, "kpass", il);
  3998. struct ggml_tensor * qrotated = ggml_rope_custom(
  3999. ctx0, qrot, inp_pos, n_rot, 2, 0, n_orig_ctx,
  4000. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4001. );
  4002. cb(qrotated, "qrotated", il);
  4003. struct ggml_tensor * krotated = ggml_rope_custom(
  4004. ctx0, krot, inp_pos, n_rot, 2, 0, n_orig_ctx,
  4005. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4006. );
  4007. cb(krotated, "krotated", il);
  4008. // ggml currently only supports concatenation on dim=2
  4009. // so we need to permute qrot, qpass, concat, then permute back.
  4010. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4011. cb(qrotated, "qrotated", il);
  4012. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4013. cb(krotated, "krotated", il);
  4014. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4015. cb(qpass, "qpass", il);
  4016. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4017. cb(kpass, "kpass", il);
  4018. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4019. cb(Qcur, "Qcur", il);
  4020. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4021. cb(Kcur, "Kcur", il);
  4022. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4023. cb(Q, "Q", il);
  4024. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4025. cb(Kcur, "Kcur", il);
  4026. struct ggml_tensor * Vcur = ggml_view_3d(
  4027. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4028. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4029. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4030. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4031. );
  4032. cb(Vcur, "Vcur", il);
  4033. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4034. // TODO: not tested, could be broken
  4035. cur = llm_build_kqv(ctx0, hparams, kv_self,
  4036. model.layers[il].wo, model.layers[il].bo,
  4037. Q, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, cb, il);
  4038. cb(cur, "kqv_out", il);
  4039. }
  4040. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4041. cb(ffn_inp, "ffn_inp", il);
  4042. // feed-forward network
  4043. {
  4044. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4045. model.layers[il].ffn_norm,
  4046. model.layers[il].ffn_norm_b,
  4047. LLM_NORM, cb, il);
  4048. cb(cur, "ffn_norm", il);
  4049. cur = llm_build_ffn(ctx0, cur,
  4050. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4051. NULL, NULL,
  4052. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4053. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4054. cb(cur, "ffn_out", il);
  4055. }
  4056. cur = ggml_add(ctx0, cur, ffn_inp);
  4057. cb(cur, "l_out", il);
  4058. inpL = cur;
  4059. }
  4060. cur = inpL;
  4061. cur = llm_build_norm(ctx0, cur, hparams,
  4062. model.output_norm,
  4063. model.output_norm_b,
  4064. LLM_NORM, cb, -1);
  4065. cb(cur, "result_norm", -1);
  4066. cur = ggml_mul_mat(ctx0, model.output, cur);
  4067. cb(cur, "result_output", -1);
  4068. ggml_build_forward_expand(gf, cur);
  4069. return gf;
  4070. }
  4071. struct ggml_cgraph * build_refact() {
  4072. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4073. struct ggml_tensor * cur;
  4074. struct ggml_tensor * inpL;
  4075. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4076. cb(inpL, "inp_embd", -1);
  4077. // KQ_scale
  4078. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  4079. cb(KQ_scale, "KQ_scale", -1);
  4080. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4081. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4082. cb(KQ_mask, "KQ_mask", -1);
  4083. for (int il = 0; il < n_layer; ++il) {
  4084. struct ggml_tensor * inpSA = inpL;
  4085. cur = llm_build_norm(ctx0, inpL, hparams,
  4086. model.layers[il].attn_norm, NULL,
  4087. LLM_NORM_RMS, cb, il);
  4088. cb(cur, "attn_norm", il);
  4089. // self-attention
  4090. {
  4091. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4092. cb(Qcur, "Qcur", il);
  4093. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4094. cb(Kcur, "Kcur", il);
  4095. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4096. cb(Vcur, "Vcur", il);
  4097. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4098. cb(Kcur, "Kcur", il);
  4099. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4100. cb(Qcur, "Qcur", il);
  4101. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4102. cur = llm_build_kqv(ctx0, hparams, kv_self,
  4103. model.layers[il].wo, NULL,
  4104. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, 8.0f, cb, il);
  4105. cb(cur, "kqv_out", il);
  4106. }
  4107. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4108. cb(ffn_inp, "ffn_inp", il);
  4109. // feed-forward network
  4110. {
  4111. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4112. model.layers[il].ffn_norm, NULL,
  4113. LLM_NORM_RMS, cb, il);
  4114. cb(cur, "ffn_norm", il);
  4115. cur = llm_build_ffn(ctx0, cur,
  4116. model.layers[il].ffn_up, NULL,
  4117. model.layers[il].ffn_gate, NULL,
  4118. model.layers[il].ffn_down, NULL,
  4119. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4120. cb(cur, "ffn_out", il);
  4121. }
  4122. cur = ggml_add(ctx0, cur, ffn_inp);
  4123. cb(cur, "l_out", il);
  4124. // input for next layer
  4125. inpL = cur;
  4126. }
  4127. cur = inpL;
  4128. cur = llm_build_norm(ctx0, cur, hparams,
  4129. model.output_norm, NULL,
  4130. LLM_NORM_RMS, cb, -1);
  4131. cb(cur, "result_norm", -1);
  4132. // lm_head
  4133. cur = ggml_mul_mat(ctx0, model.output, cur);
  4134. cb(cur, "result_output", -1);
  4135. ggml_build_forward_expand(gf, cur);
  4136. return gf;
  4137. }
  4138. struct ggml_cgraph * build_bloom() {
  4139. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4140. struct ggml_tensor * cur;
  4141. struct ggml_tensor * inpL;
  4142. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4143. cb(inpL, "inp_embd", -1);
  4144. // KQ_scale
  4145. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  4146. cb(KQ_scale, "KQ_scale", -1);
  4147. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4148. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4149. cb(KQ_mask, "KQ_mask", -1);
  4150. inpL = llm_build_norm(ctx0, inpL, hparams,
  4151. model.tok_norm,
  4152. model.tok_norm_b,
  4153. LLM_NORM, cb, -1);
  4154. cb(inpL, "inp_norm", -1);
  4155. for (int il = 0; il < n_layer; ++il) {
  4156. cur = llm_build_norm(ctx0, inpL, hparams,
  4157. model.layers[il].attn_norm,
  4158. model.layers[il].attn_norm_b,
  4159. LLM_NORM, cb, il);
  4160. cb(cur, "attn_norm", il);
  4161. // self-attention
  4162. {
  4163. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4164. cb(cur, "wqkv", il);
  4165. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4166. cb(cur, "bqkv", il);
  4167. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4168. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4169. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  4170. cb(Qcur, "Qcur", il);
  4171. cb(Kcur, "Kcur", il);
  4172. cb(Vcur, "Vcur", il);
  4173. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4174. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4175. cur = llm_build_kqv(ctx0, hparams, kv_self,
  4176. model.layers[il].wo, model.layers[il].bo,
  4177. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, 8.0f, cb, il);
  4178. cb(cur, "kqv_out", il);
  4179. }
  4180. // Add the input
  4181. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4182. cb(ffn_inp, "ffn_inp", il);
  4183. // FF
  4184. {
  4185. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4186. model.layers[il].ffn_norm,
  4187. model.layers[il].ffn_norm_b,
  4188. LLM_NORM, cb, il);
  4189. cb(cur, "ffn_norm", il);
  4190. cur = llm_build_ffn(ctx0, cur,
  4191. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4192. NULL, NULL,
  4193. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4194. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4195. cb(cur, "ffn_out", il);
  4196. }
  4197. inpL = ggml_add(ctx0, cur, ffn_inp);
  4198. cb(inpL, "l_out", il);
  4199. }
  4200. cur = llm_build_norm(ctx0, inpL, hparams,
  4201. model.output_norm,
  4202. model.output_norm_b,
  4203. LLM_NORM, cb, -1);
  4204. cb(cur, "result_norm", -1);
  4205. cur = ggml_mul_mat(ctx0, model.output, cur);
  4206. cb(cur, "result_output", -1);
  4207. ggml_build_forward_expand(gf, cur);
  4208. return gf;
  4209. }
  4210. struct ggml_cgraph * build_mpt() {
  4211. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4212. struct ggml_tensor * cur;
  4213. struct ggml_tensor * inpL;
  4214. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4215. cb(inpL, "inp_embd", -1);
  4216. // KQ_scale
  4217. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  4218. cb(KQ_scale, "KQ_scale", -1);
  4219. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4220. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4221. cb(KQ_mask, "KQ_mask", -1);
  4222. for (int il = 0; il < n_layer; ++il) {
  4223. struct ggml_tensor * attn_norm;
  4224. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4225. model.layers[il].attn_norm,
  4226. NULL,
  4227. LLM_NORM, cb, il);
  4228. cb(attn_norm, "attn_norm", il);
  4229. // self-attention
  4230. {
  4231. cur = attn_norm;
  4232. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4233. cb(cur, "wqkv", il);
  4234. if (hparams.f_clamp_kqv > 0.0f) {
  4235. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4236. cb(cur, "wqkv_clamped", il);
  4237. }
  4238. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4239. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4240. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  4241. cb(Qcur, "Qcur", il);
  4242. cb(Kcur, "Kcur", il);
  4243. cb(Vcur, "Vcur", il);
  4244. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4245. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4246. cur = llm_build_kqv(ctx0, hparams, kv_self,
  4247. model.layers[il].wo, NULL,
  4248. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, hparams.f_max_alibi_bias, cb, il);
  4249. cb(cur, "kqv_out", il);
  4250. }
  4251. // Add the input
  4252. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4253. cb(ffn_inp, "ffn_inp", il);
  4254. // feed forward
  4255. {
  4256. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4257. model.layers[il].ffn_norm,
  4258. NULL,
  4259. LLM_NORM, cb, il);
  4260. cb(cur, "ffn_norm", il);
  4261. cur = llm_build_ffn(ctx0, cur,
  4262. model.layers[il].ffn_up, NULL,
  4263. NULL, NULL,
  4264. model.layers[il].ffn_down, NULL,
  4265. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4266. cb(cur, "ffn_out", il);
  4267. }
  4268. cur = ggml_add(ctx0, cur, ffn_inp);
  4269. cb(cur, "l_out", il);
  4270. // input for next layer
  4271. inpL = cur;
  4272. }
  4273. cur = inpL;
  4274. cur = llm_build_norm(ctx0, cur, hparams,
  4275. model.output_norm,
  4276. NULL,
  4277. LLM_NORM, cb, -1);
  4278. cb(cur, "result_norm", -1);
  4279. cur = ggml_mul_mat(ctx0, model.output, cur);
  4280. cb(cur, "result_output", -1);
  4281. ggml_build_forward_expand(gf, cur);
  4282. return gf;
  4283. }
  4284. struct ggml_cgraph * build_stablelm() {
  4285. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4286. struct ggml_tensor * cur;
  4287. struct ggml_tensor * inpL;
  4288. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4289. cb(inpL, "inp_embd", -1);
  4290. // inp_pos - contains the positions
  4291. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4292. cb(inp_pos, "inp_pos", -1);
  4293. // KQ_scale
  4294. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  4295. cb(KQ_scale, "KQ_scale", -1);
  4296. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4297. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4298. cb(KQ_mask, "KQ_mask", -1);
  4299. // shift the entire K-cache if needed
  4300. if (do_rope_shift) {
  4301. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, hparams.n_rot, freq_base, freq_scale, cb);
  4302. }
  4303. for (int il = 0; il < n_layer; ++il) {
  4304. struct ggml_tensor * inpSA = inpL;
  4305. // norm
  4306. cur = llm_build_norm(ctx0, inpL, hparams,
  4307. model.layers[il].attn_norm,
  4308. model.layers[il].attn_norm_b,
  4309. LLM_NORM, cb, il);
  4310. cb(cur, "attn_norm", il);
  4311. // self-attention
  4312. {
  4313. // compute Q and K and RoPE them
  4314. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4315. cb(Qcur, "Qcur", il);
  4316. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4317. cb(Kcur, "Kcur", il);
  4318. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4319. cb(Vcur, "Vcur", il);
  4320. Qcur = ggml_rope_custom(
  4321. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4322. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4323. ext_factor, attn_factor, beta_fast, beta_slow
  4324. );
  4325. cb(Qcur, "Qcur", il);
  4326. Kcur = ggml_rope_custom(
  4327. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4328. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4329. ext_factor, attn_factor, beta_fast, beta_slow
  4330. );
  4331. cb(Kcur, "Kcur", il);
  4332. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4333. cur = llm_build_kqv(ctx0, hparams, kv_self,
  4334. model.layers[il].wo, NULL,
  4335. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, cb, il);
  4336. cb(cur, "kqv_out", il);
  4337. }
  4338. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4339. cb(ffn_inp, "ffn_inp", il);
  4340. // feed-forward network
  4341. {
  4342. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4343. model.layers[il].ffn_norm,
  4344. model.layers[il].ffn_norm_b,
  4345. LLM_NORM, cb, il);
  4346. cb(cur, "ffn_norm", il);
  4347. cur = llm_build_ffn(ctx0, cur,
  4348. model.layers[il].ffn_up, NULL,
  4349. model.layers[il].ffn_gate, NULL,
  4350. model.layers[il].ffn_down, NULL,
  4351. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4352. cb(cur, "ffn_out", il);
  4353. }
  4354. cur = ggml_add(ctx0, cur, ffn_inp);
  4355. cb(cur, "l_out", il);
  4356. // input for next layer
  4357. inpL = cur;
  4358. }
  4359. cur = inpL;
  4360. cur = llm_build_norm(ctx0, cur, hparams,
  4361. model.output_norm,
  4362. model.output_norm_b,
  4363. LLM_NORM, cb, -1);
  4364. cb(cur, "result_norm", -1);
  4365. // lm_head
  4366. cur = ggml_mul_mat(ctx0, model.output, cur);
  4367. cb(cur, "result_output", -1);
  4368. ggml_build_forward_expand(gf, cur);
  4369. return gf;
  4370. }
  4371. struct ggml_cgraph * build_qwen() {
  4372. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4373. struct ggml_tensor * cur;
  4374. struct ggml_tensor * inpL;
  4375. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4376. cb(inpL, "inp_embd", -1);
  4377. // inp_pos - contains the positions
  4378. struct ggml_tensor * inp_pos= ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4379. cb(inp_pos, "inp_pos", -1);
  4380. // KQ_scale
  4381. struct ggml_tensor * KQ_scale= ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  4382. cb(KQ_scale, "KQ_scale", -1);
  4383. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4384. struct ggml_tensor * KQ_mask= ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4385. cb(KQ_mask, "KQ_mask", -1);
  4386. // shift the entire K-cache if needed
  4387. if (do_rope_shift) {
  4388. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, n_embd_head, freq_base, freq_scale, cb);
  4389. }
  4390. for (int il = 0; il < n_layer; ++il) {
  4391. struct ggml_tensor * inpSA = inpL;
  4392. cur = llm_build_norm(ctx0, inpL, hparams,
  4393. model.layers[il].attn_norm, NULL,
  4394. LLM_NORM_RMS, cb, il);
  4395. cb(cur, "attn_norm", il);
  4396. // self-attention
  4397. {
  4398. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4399. cb(cur, "wqkv", il);
  4400. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4401. cb(cur, "bqkv", il);
  4402. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4403. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4404. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4405. cb(Qcur, "Qcur", il);
  4406. cb(Kcur, "Kcur", il);
  4407. cb(Vcur, "Vcur", il);
  4408. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4409. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4410. // using mode = 2 for neox mode
  4411. Qcur = ggml_rope_custom(
  4412. ctx0, Qcur, inp_pos, n_embd_head, 2, 0, n_orig_ctx,
  4413. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4414. );
  4415. cb(Qcur, "Qcur", il);
  4416. Kcur = ggml_rope_custom(
  4417. ctx0, Kcur, inp_pos, n_embd_head, 2, 0, n_orig_ctx,
  4418. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4419. );
  4420. cb(Kcur, "Kcur", il);
  4421. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4422. cur = llm_build_kqv(ctx0, hparams, kv_self,
  4423. model.layers[il].wo, NULL,
  4424. Qcur, KQ_scale, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, cb, il);
  4425. cb(cur, "kqv_out", il);
  4426. }
  4427. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4428. cb(ffn_inp, "ffn_inp", il);
  4429. // feed-forward forward
  4430. {
  4431. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4432. model.layers[il].ffn_norm, NULL,
  4433. LLM_NORM_RMS, cb, il);
  4434. cb(cur, "ffn_norm", il);
  4435. cur = llm_build_ffn(ctx0, cur,
  4436. model.layers[il].ffn_up, NULL,
  4437. model.layers[il].ffn_gate, NULL,
  4438. model.layers[il].ffn_down, NULL,
  4439. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4440. cb(cur, "ffn_out", il);
  4441. }
  4442. cur = ggml_add(ctx0, cur, ffn_inp);
  4443. cb(cur, "l_out", il);
  4444. // input for next layer
  4445. inpL = cur;
  4446. }
  4447. cur = inpL;
  4448. cur = llm_build_norm(ctx0, cur, hparams,
  4449. model.output_norm, NULL,
  4450. LLM_NORM_RMS, cb, -1);
  4451. cb(cur, "result_norm", -1);
  4452. // lm_head
  4453. cur = ggml_mul_mat(ctx0, model.output, cur);
  4454. cb(cur, "result_output", -1);
  4455. ggml_build_forward_expand(gf, cur);
  4456. return gf;
  4457. }
  4458. };
  4459. //
  4460. // tensor offloading helpers
  4461. //
  4462. // TODO: will be removed with backend v2
  4463. enum llm_offload_func_e {
  4464. OFFLOAD_FUNC_NOP,
  4465. OFFLOAD_FUNC,
  4466. OFFLOAD_FUNC_FRC, // force offload
  4467. OFFLOAD_FUNC_KQV,
  4468. OFFLOAD_FUNC_NR,
  4469. OFFLOAD_FUNC_EMB,
  4470. OFFLOAD_FUNC_OUT,
  4471. };
  4472. // TODO: will be removed with backend v2
  4473. struct llm_offload_trie {
  4474. struct node {
  4475. ~node() {
  4476. for (int i = 0; i < 256; ++i) {
  4477. if (children[i]) {
  4478. delete children[i];
  4479. }
  4480. }
  4481. }
  4482. node * children[256] = { nullptr };
  4483. llm_offload_func_e func = OFFLOAD_FUNC_NOP;
  4484. };
  4485. llm_offload_trie() {
  4486. root = new node;
  4487. }
  4488. llm_offload_trie(const std::unordered_map<const char *, llm_offload_func_e> & map) {
  4489. root = new node;
  4490. for (const auto & kv : map) {
  4491. add(kv.first, kv.second);
  4492. }
  4493. }
  4494. ~llm_offload_trie() {
  4495. delete root;
  4496. }
  4497. void add(const char * name, llm_offload_func_e func) {
  4498. node * cur = root;
  4499. for (int i = 0; ; ++i) {
  4500. const uint8_t c = name[i];
  4501. if (!c) {
  4502. break;
  4503. }
  4504. if (!cur->children[c]) {
  4505. cur->children[c] = new node;
  4506. }
  4507. cur = cur->children[c];
  4508. }
  4509. cur->func = func;
  4510. }
  4511. llm_offload_func_e find(const char * name) const {
  4512. const node * cur = root;
  4513. for (int i = 0; ; ++i) {
  4514. const uint8_t c = name[i];
  4515. if (!c) {
  4516. break;
  4517. }
  4518. if (!cur->children[c]) {
  4519. return OFFLOAD_FUNC_NOP;
  4520. }
  4521. cur = cur->children[c];
  4522. }
  4523. return cur->func;
  4524. }
  4525. node * root = nullptr;
  4526. };
  4527. // TODO: will be removed with backend v2
  4528. static const std::unordered_map<const char *, llm_offload_func_e> k_offload_map = {
  4529. //{ "inp_tokens", OFFLOAD_FUNC_NR }, // TODO: missing K-quants get_rows kernel
  4530. //{ "inp_embd", OFFLOAD_FUNC_NR }, // TODO: missing K-quants get_rows kernel
  4531. { "pos_embd", OFFLOAD_FUNC_NR },
  4532. { "inp_pos", OFFLOAD_FUNC_FRC }, // this is often used for KQ ops (e.g. rope)
  4533. { "KQ_scale", OFFLOAD_FUNC_FRC },
  4534. { "KQ_mask", OFFLOAD_FUNC_FRC },
  4535. { "K_shift", OFFLOAD_FUNC_FRC },
  4536. { "K_shifted", OFFLOAD_FUNC },
  4537. { "inp_norm", OFFLOAD_FUNC_NR },
  4538. { "inp_norm_w", OFFLOAD_FUNC_NR },
  4539. { "inp_norm_wb", OFFLOAD_FUNC_NR },
  4540. { "norm", OFFLOAD_FUNC },
  4541. { "norm_w", OFFLOAD_FUNC },
  4542. { "norm_wb", OFFLOAD_FUNC },
  4543. { "attn_norm", OFFLOAD_FUNC },
  4544. { "attn_norm_2", OFFLOAD_FUNC },
  4545. { "wqkv", OFFLOAD_FUNC_KQV },
  4546. { "bqkv", OFFLOAD_FUNC_KQV },
  4547. { "wqkv_clamped", OFFLOAD_FUNC_KQV },
  4548. { "tmpk", OFFLOAD_FUNC_KQV },
  4549. { "tmpq", OFFLOAD_FUNC_KQV },
  4550. { "tmpv", OFFLOAD_FUNC_KQV },
  4551. { "Kcur", OFFLOAD_FUNC_KQV },
  4552. { "Qcur", OFFLOAD_FUNC_KQV },
  4553. { "Vcur", OFFLOAD_FUNC_KQV },
  4554. { "krot", OFFLOAD_FUNC_KQV },
  4555. { "qrot", OFFLOAD_FUNC_KQV },
  4556. { "kpass", OFFLOAD_FUNC_KQV },
  4557. { "qpass", OFFLOAD_FUNC_KQV },
  4558. { "krotated", OFFLOAD_FUNC_KQV },
  4559. { "qrotated", OFFLOAD_FUNC_KQV },
  4560. { "q", OFFLOAD_FUNC_KQV },
  4561. { "k", OFFLOAD_FUNC_KQV },
  4562. { "kq", OFFLOAD_FUNC_KQV },
  4563. { "kq_scaled", OFFLOAD_FUNC_KQV },
  4564. { "kq_scaled_alibi", OFFLOAD_FUNC_KQV },
  4565. { "kq_masked", OFFLOAD_FUNC_KQV },
  4566. { "kq_soft_max", OFFLOAD_FUNC_KQV },
  4567. { "kq_soft_max_ext", OFFLOAD_FUNC_KQV },
  4568. { "v", OFFLOAD_FUNC_KQV },
  4569. { "kqv", OFFLOAD_FUNC_KQV },
  4570. { "kqv_merged", OFFLOAD_FUNC_KQV },
  4571. { "kqv_merged_cont", OFFLOAD_FUNC_KQV },
  4572. { "kqv_wo", OFFLOAD_FUNC_KQV },
  4573. { "kqv_out", OFFLOAD_FUNC_KQV },
  4574. { "ffn_inp", OFFLOAD_FUNC },
  4575. { "ffn_norm", OFFLOAD_FUNC },
  4576. { "ffn_up", OFFLOAD_FUNC },
  4577. { "ffn_up_b", OFFLOAD_FUNC },
  4578. { "ffn_gate", OFFLOAD_FUNC },
  4579. { "ffn_gate_b", OFFLOAD_FUNC },
  4580. { "ffn_gate_par", OFFLOAD_FUNC },
  4581. { "ffn_down", OFFLOAD_FUNC },
  4582. { "ffn_down_b", OFFLOAD_FUNC },
  4583. { "ffn_out", OFFLOAD_FUNC },
  4584. { "ffn_silu", OFFLOAD_FUNC },
  4585. { "ffn_gelu", OFFLOAD_FUNC },
  4586. { "ffn_relu", OFFLOAD_FUNC },
  4587. { "ffn_sqr(relu)", OFFLOAD_FUNC },
  4588. { "ffn_moe_logits", OFFLOAD_FUNC },
  4589. { "ffn_moe_probs", OFFLOAD_FUNC },
  4590. { "ffn_moe_argsort", OFFLOAD_FUNC },
  4591. { "ffn_moe_weights", OFFLOAD_FUNC },
  4592. { "ffn_moe_weights_sum", OFFLOAD_FUNC },
  4593. { "ffn_moe_weights_norm", OFFLOAD_FUNC },
  4594. { "ffn_moe_weighted", OFFLOAD_FUNC },
  4595. { "ffn_moe_up", OFFLOAD_FUNC },
  4596. { "ffn_moe_gate", OFFLOAD_FUNC },
  4597. { "ffn_moe_silu", OFFLOAD_FUNC },
  4598. { "ffn_moe_gate_par", OFFLOAD_FUNC },
  4599. { "ffn_moe_down", OFFLOAD_FUNC },
  4600. { "ffn_moe_out", OFFLOAD_FUNC },
  4601. { "l_out", OFFLOAD_FUNC },
  4602. { "result_norm", OFFLOAD_FUNC_EMB },
  4603. { "result_output", OFFLOAD_FUNC_OUT },
  4604. };
  4605. static llm_offload_trie k_offload_func_trie(k_offload_map);
  4606. static struct ggml_cgraph * llama_build_graph(
  4607. llama_context & lctx,
  4608. const llama_batch & batch) {
  4609. const auto & model = lctx.model;
  4610. // check if we should build the worst-case graph (for memory measurement)
  4611. const bool worst_case = ggml_allocr_is_measure(lctx.alloc);
  4612. // keep track of the input that has already been allocated
  4613. bool alloc_inp_tokens = false;
  4614. bool alloc_inp_embd = false;
  4615. bool alloc_inp_pos = false;
  4616. bool alloc_inp_KQ_scale = false;
  4617. bool alloc_inp_KQ_mask = false;
  4618. bool alloc_inp_K_shift = false;
  4619. #ifdef GGML_USE_CUBLAS
  4620. const bool do_offload = true;
  4621. #else
  4622. const bool do_offload = true; // TODO: set to false after finishing refactoring
  4623. #endif
  4624. int n_non_view = 0; // number of non-view tensors that have been processed by the callback
  4625. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  4626. // TODO: will be removed with backend v2
  4627. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  4628. if (il >= 0) {
  4629. ggml_format_name(cur, "%s-%d", name, il);
  4630. } else {
  4631. ggml_set_name(cur, name);
  4632. }
  4633. //
  4634. // allocate input tensors and set input data
  4635. //
  4636. // TODO: will be removed with backend v2
  4637. if (!alloc_inp_tokens && strcmp(name, "inp_tokens") == 0) {
  4638. ggml_allocr_alloc(lctx.alloc, cur);
  4639. if (!ggml_allocr_is_measure(lctx.alloc) && batch.token) {
  4640. const int64_t n_tokens = cur->ne[0];
  4641. memcpy(cur->data, batch.token, n_tokens*ggml_element_size(cur));
  4642. }
  4643. alloc_inp_tokens = true;
  4644. }
  4645. if (!alloc_inp_embd && strcmp(name, "inp_embd") == 0) {
  4646. ggml_allocr_alloc(lctx.alloc, cur);
  4647. if (!ggml_allocr_is_measure(lctx.alloc) && batch.embd) {
  4648. const int64_t n_embd = cur->ne[0];
  4649. const int64_t n_tokens = cur->ne[1];
  4650. memcpy(cur->data, batch.embd, n_tokens*n_embd*ggml_element_size(cur));
  4651. }
  4652. alloc_inp_embd = true;
  4653. }
  4654. if (!alloc_inp_pos && strcmp(name, "inp_pos") == 0) {
  4655. ggml_allocr_alloc(lctx.alloc, cur);
  4656. if (!ggml_allocr_is_measure(lctx.alloc) && batch.pos) {
  4657. const int64_t n_tokens = cur->ne[0];
  4658. int32_t * data = (int32_t *) cur->data;
  4659. for (int i = 0; i < n_tokens; ++i) {
  4660. data[i] = batch.pos[i];
  4661. }
  4662. }
  4663. alloc_inp_pos = true;
  4664. }
  4665. if (!alloc_inp_KQ_scale && strcmp(name, "KQ_scale") == 0) {
  4666. ggml_allocr_alloc(lctx.alloc, cur);
  4667. if (!ggml_allocr_is_measure(lctx.alloc)) {
  4668. const int64_t n_embd_head = model.hparams.n_embd_head();
  4669. ggml_set_f32(cur, 1.0f/sqrtf(float(n_embd_head)));
  4670. }
  4671. alloc_inp_KQ_scale = true;
  4672. }
  4673. if (!alloc_inp_KQ_mask && strcmp(name, "KQ_mask") == 0) {
  4674. ggml_allocr_alloc(lctx.alloc, cur);
  4675. if (!ggml_allocr_is_measure(lctx.alloc)) {
  4676. const int64_t n_kv = cur->ne[0];
  4677. const int64_t n_tokens = cur->ne[1];
  4678. float * data = (float *) cur->data;
  4679. memset(data, 0, ggml_nbytes(cur));
  4680. for (int h = 0; h < 1; ++h) {
  4681. for (int j = 0; j < n_tokens; ++j) {
  4682. const llama_pos pos = batch.pos[j];
  4683. const llama_seq_id seq_id = batch.seq_id[j][0];
  4684. for (int i = 0; i < n_kv; ++i) {
  4685. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  4686. data[h*(n_kv*n_tokens) + j*n_kv + i] = -INFINITY;
  4687. }
  4688. }
  4689. }
  4690. }
  4691. }
  4692. alloc_inp_KQ_mask = true;
  4693. }
  4694. if (!alloc_inp_K_shift && strcmp(name, "K_shift") == 0) {
  4695. ggml_allocr_alloc(lctx.alloc, cur);
  4696. if (!ggml_allocr_is_measure(lctx.alloc)) {
  4697. const int64_t n_ctx = cur->ne[0];
  4698. int32_t * data = (int32_t *) cur->data;
  4699. for (int i = 0; i < n_ctx; ++i) {
  4700. data[i] = lctx.kv_self.cells[i].delta;
  4701. }
  4702. }
  4703. alloc_inp_K_shift = true;
  4704. }
  4705. // view tensors are not processed further
  4706. if (cur->view_src != nullptr) {
  4707. return;
  4708. }
  4709. if (cur->op != GGML_OP_NONE) {
  4710. n_non_view++;
  4711. }
  4712. //
  4713. // offload layers
  4714. //
  4715. // TODO: will be removed with backend v2
  4716. //#define LLAMA_OFFLOAD_DEBUG
  4717. if (!do_offload) {
  4718. return;
  4719. }
  4720. const int n_layer = model.hparams.n_layer;
  4721. const int n_gpu_layers = model.n_gpu_layers;
  4722. const int i_gpu_start = n_layer - n_gpu_layers;
  4723. // should we offload the final norm? yes if we are not computing embeddings
  4724. const bool offload_emb = lctx.embedding.empty();
  4725. static const std::unordered_map<llm_offload_func_e, std::string, std::hash<int>> k_offload_func_name = {
  4726. { OFFLOAD_FUNC_NOP, "CPU" },
  4727. { OFFLOAD_FUNC_OUT, "CPU" },
  4728. #ifdef GGML_USE_CUBLAS
  4729. { OFFLOAD_FUNC, "GPU (CUDA)" },
  4730. { OFFLOAD_FUNC_FRC, "GPU (CUDA) FRC" },
  4731. { OFFLOAD_FUNC_KQV, "GPU (CUDA) KQV" },
  4732. { OFFLOAD_FUNC_NR, "GPU (CUDA) NR" },
  4733. { OFFLOAD_FUNC_EMB, "GPU (CUDA) EMB" },
  4734. #else
  4735. { OFFLOAD_FUNC, "CPU" },
  4736. { OFFLOAD_FUNC_FRC, "CPU" },
  4737. { OFFLOAD_FUNC_KQV, "CPU" },
  4738. { OFFLOAD_FUNC_NR, "CPU" },
  4739. { OFFLOAD_FUNC_EMB, "CPU" },
  4740. #endif // GGML_USE_CUBLAS
  4741. };
  4742. // check the global map for what offload function to use for this tensor
  4743. llm_offload_func_e func_e = k_offload_func_trie.find(name);
  4744. if (func_e == OFFLOAD_FUNC_NOP) {
  4745. #ifdef LLAMA_OFFLOAD_DEBUG
  4746. // if a tensor hasn't been offloaded, we warn the user
  4747. if (worst_case) {
  4748. LLAMA_LOG_WARN("%s: %32s: not offloaded (ref: %s)\n", __func__,
  4749. cur->name, "https://github.com/ggerganov/llama.cpp/pull/3837");
  4750. }
  4751. #endif
  4752. return;
  4753. }
  4754. // count the number of layers and respect the provided n_gpu_layers
  4755. switch (func_e) {
  4756. case OFFLOAD_FUNC_NOP:
  4757. case OFFLOAD_FUNC_OUT:
  4758. break;
  4759. case OFFLOAD_FUNC:
  4760. if (n_gpu_layers < n_layer) {
  4761. if (il < i_gpu_start) {
  4762. func_e = OFFLOAD_FUNC_NOP;
  4763. }
  4764. }
  4765. break;
  4766. case OFFLOAD_FUNC_FRC:
  4767. if (!lctx.cparams.offload_kqv) {
  4768. func_e = OFFLOAD_FUNC_NOP;
  4769. } break;
  4770. case OFFLOAD_FUNC_KQV:
  4771. if (!lctx.cparams.offload_kqv) {
  4772. func_e = OFFLOAD_FUNC_NOP;
  4773. } else {
  4774. if (n_gpu_layers < n_layer) {
  4775. if (il < i_gpu_start) {
  4776. func_e = OFFLOAD_FUNC_NOP;
  4777. }
  4778. }
  4779. }
  4780. break;
  4781. case OFFLOAD_FUNC_NR:
  4782. if (n_gpu_layers <= n_layer + 0) {
  4783. func_e = OFFLOAD_FUNC_NOP;
  4784. }
  4785. break;
  4786. case OFFLOAD_FUNC_EMB:
  4787. if (!offload_emb || n_gpu_layers < n_layer) {
  4788. func_e = OFFLOAD_FUNC_NOP;
  4789. }
  4790. break;
  4791. default: GGML_ASSERT(false);
  4792. }
  4793. offload_func_t func = ggml_offload_nop;
  4794. // this is needed for compatibility with Metal for example
  4795. #ifdef GGML_USE_CUBLAS
  4796. static offload_func_t ggml_offload_gpu = ggml_cuda_assign_buffers_no_alloc;
  4797. #else
  4798. static offload_func_t ggml_offload_gpu = ggml_offload_nop;
  4799. #endif
  4800. switch (func_e) {
  4801. case OFFLOAD_FUNC_NOP:
  4802. case OFFLOAD_FUNC_OUT: func = ggml_offload_nop; break;
  4803. case OFFLOAD_FUNC:
  4804. case OFFLOAD_FUNC_KQV:
  4805. case OFFLOAD_FUNC_FRC:
  4806. case OFFLOAD_FUNC_NR:
  4807. case OFFLOAD_FUNC_EMB: func = ggml_offload_gpu; break;
  4808. default: GGML_ASSERT(false);
  4809. }
  4810. // apply offload function to the tensor
  4811. func(cur);
  4812. #ifdef LLAMA_OFFLOAD_DEBUG
  4813. if (worst_case) {
  4814. LLAMA_LOG_INFO("%s: %32s: %s\n", __func__, cur->name, k_offload_func_name.at(func_e).c_str());
  4815. }
  4816. #endif
  4817. };
  4818. struct ggml_cgraph * result = NULL;
  4819. struct llm_build_context llm(lctx, batch, cb, worst_case);
  4820. llm.init();
  4821. switch (model.arch) {
  4822. case LLM_ARCH_LLAMA:
  4823. {
  4824. result = llm.build_llama();
  4825. } break;
  4826. case LLM_ARCH_BAICHUAN:
  4827. {
  4828. result = llm.build_baichuan();
  4829. } break;
  4830. case LLM_ARCH_FALCON:
  4831. {
  4832. result = llm.build_falcon();
  4833. } break;
  4834. case LLM_ARCH_STARCODER:
  4835. {
  4836. result = llm.build_starcoder();
  4837. } break;
  4838. case LLM_ARCH_PERSIMMON:
  4839. {
  4840. result = llm.build_persimmon();
  4841. } break;
  4842. case LLM_ARCH_REFACT:
  4843. {
  4844. result = llm.build_refact();
  4845. } break;
  4846. case LLM_ARCH_BLOOM:
  4847. {
  4848. result = llm.build_bloom();
  4849. } break;
  4850. case LLM_ARCH_MPT:
  4851. {
  4852. result = llm.build_mpt();
  4853. } break;
  4854. case LLM_ARCH_STABLELM:
  4855. {
  4856. result = llm.build_stablelm();
  4857. } break;
  4858. case LLM_ARCH_QWEN:
  4859. {
  4860. result = llm.build_qwen();
  4861. } break;
  4862. default:
  4863. GGML_ASSERT(false);
  4864. }
  4865. llm.free();
  4866. if (worst_case) {
  4867. int n_non_view_total = 0;
  4868. for (int i = 0; i < result->n_nodes; ++i) {
  4869. if (result->nodes[i]->view_src == nullptr) {
  4870. n_non_view_total++;
  4871. }
  4872. }
  4873. LLAMA_LOG_INFO("%s: non-view tensors processed: %d/%d\n", __func__, n_non_view, n_non_view_total);
  4874. if (n_non_view != n_non_view_total) {
  4875. LLAMA_LOG_WARN("%s: ****************************************************************\n", __func__);
  4876. LLAMA_LOG_WARN("%s: not all non-view tensors have been processed with a callback\n", __func__);
  4877. LLAMA_LOG_WARN("%s: this can indicate an inefficiency in the graph implementation\n", __func__);
  4878. LLAMA_LOG_WARN("%s: build with LLAMA_OFFLOAD_DEBUG for more info\n", __func__);
  4879. LLAMA_LOG_WARN("%s: ref: https://github.com/ggerganov/llama.cpp/pull/3837\n", __func__);
  4880. LLAMA_LOG_WARN("%s: ****************************************************************\n", __func__);
  4881. }
  4882. }
  4883. return result;
  4884. }
  4885. // decode a batch of tokens by evaluating the transformer
  4886. //
  4887. // - lctx: llama context
  4888. // - batch: batch to evaluate
  4889. //
  4890. // return 0 on success
  4891. // return positive int on warning
  4892. // return negative int on error
  4893. //
  4894. static int llama_decode_internal(
  4895. llama_context & lctx,
  4896. llama_batch batch) {
  4897. const uint32_t n_tokens = batch.n_tokens;
  4898. if (n_tokens == 0) {
  4899. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  4900. return -1;
  4901. }
  4902. const auto & model = lctx.model;
  4903. const auto & hparams = model.hparams;
  4904. const auto & cparams = lctx.cparams;
  4905. const auto n_batch = cparams.n_batch;
  4906. GGML_ASSERT(n_tokens <= n_batch);
  4907. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  4908. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  4909. const int64_t t_start_us = ggml_time_us();
  4910. #ifdef GGML_USE_MPI
  4911. // TODO: needs fix after #3228
  4912. GGML_ASSERT(false && "not implemented");
  4913. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  4914. #endif
  4915. GGML_ASSERT(n_threads > 0);
  4916. auto & kv_self = lctx.kv_self;
  4917. GGML_ASSERT(!!kv_self.ctx);
  4918. const int64_t n_embd = hparams.n_embd;
  4919. const int64_t n_vocab = hparams.n_vocab;
  4920. // helpers for smoother batch API transition
  4921. // after deprecating the llama_eval calls, these will be removed
  4922. std::vector<llama_pos> pos;
  4923. std::vector<int32_t> n_seq_id;
  4924. std::vector<llama_seq_id *> seq_id_arr;
  4925. std::vector<std::vector<llama_seq_id>> seq_id;
  4926. if (batch.pos == nullptr) {
  4927. pos.resize(n_tokens);
  4928. for (uint32_t i = 0; i < n_tokens; i++) {
  4929. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  4930. }
  4931. batch.pos = pos.data();
  4932. }
  4933. if (batch.seq_id == nullptr) {
  4934. n_seq_id.resize(n_tokens);
  4935. seq_id.resize(n_tokens);
  4936. seq_id_arr.resize(n_tokens);
  4937. for (uint32_t i = 0; i < n_tokens; i++) {
  4938. n_seq_id[i] = 1;
  4939. seq_id[i].resize(1);
  4940. seq_id[i][0] = batch.all_seq_id;
  4941. seq_id_arr[i] = seq_id[i].data();
  4942. }
  4943. batch.n_seq_id = n_seq_id.data();
  4944. batch.seq_id = seq_id_arr.data();
  4945. }
  4946. // if we have enough unused cells before the current head ->
  4947. // better to start searching from the beginning of the cache, hoping to fill it
  4948. if (kv_self.head > kv_self.used + 2*n_tokens) {
  4949. kv_self.head = 0;
  4950. }
  4951. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  4952. return 1;
  4953. }
  4954. // a heuristic, to avoid attending the full cache if it is not yet utilized
  4955. // after enough generations, the benefit from this heuristic disappears
  4956. // if we start defragmenting the cache, the benefit from this will be more important
  4957. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  4958. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  4959. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  4960. ggml_allocr_reset(lctx.alloc);
  4961. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  4962. ggml_allocr_alloc_graph(lctx.alloc, gf);
  4963. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  4964. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  4965. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  4966. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  4967. #ifdef GGML_USE_CUBLAS
  4968. for (int i = 0; i < gf->n_leafs; i++) {
  4969. ggml_tensor * node = gf->leafs[i];
  4970. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  4971. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  4972. ggml_cuda_copy_to_device(node);
  4973. }
  4974. }
  4975. for (int i = 0; i < gf->n_nodes; i++) {
  4976. ggml_tensor * node = gf->nodes[i];
  4977. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  4978. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  4979. }
  4980. }
  4981. // HACK: ggml-alloc may change the tensor backend when reusing a parent, so force output to be on the CPU here if needed
  4982. if (!lctx.embedding.empty()) {
  4983. embeddings->backend = GGML_BACKEND_CPU;
  4984. }
  4985. res->backend = GGML_BACKEND_CPU;
  4986. #endif
  4987. // 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);
  4988. // for big prompts, if BLAS is enabled, it is better to use only one thread
  4989. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  4990. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  4991. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  4992. // with the BLAS calls. need a better solution
  4993. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  4994. n_threads = std::min(4, n_threads);
  4995. }
  4996. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 1;
  4997. if (ggml_cpu_has_cublas() && fully_offloaded) {
  4998. n_threads = 1;
  4999. }
  5000. #if GGML_USE_MPI
  5001. const int64_t n_layer = hparams.n_layer;
  5002. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5003. #endif
  5004. #ifdef GGML_USE_METAL
  5005. if (lctx.ctx_metal) {
  5006. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  5007. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  5008. } else {
  5009. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  5010. }
  5011. #else
  5012. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  5013. #endif
  5014. #if GGML_USE_MPI
  5015. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5016. #endif
  5017. // update the kv ring buffer
  5018. {
  5019. if (kv_self.has_shift) {
  5020. kv_self.has_shift = false;
  5021. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5022. kv_self.cells[i].delta = 0;
  5023. }
  5024. }
  5025. kv_self.head += n_tokens;
  5026. // Ensure kv cache head points to a valid index.
  5027. if (kv_self.head >= kv_self.size) {
  5028. kv_self.head = 0;
  5029. }
  5030. }
  5031. #ifdef GGML_PERF
  5032. // print timing information per ggml operation (for debugging purposes)
  5033. // requires GGML_PERF to be defined
  5034. ggml_graph_print(gf);
  5035. #endif
  5036. // plot the computation graph in dot format (for debugging purposes)
  5037. //if (n_past%100 == 0) {
  5038. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5039. //}
  5040. // extract logits
  5041. // TODO: do not compute and extract logits if only embeddings are needed
  5042. // need to update the graphs to skip "result_output"
  5043. {
  5044. auto & logits_out = lctx.logits;
  5045. #ifndef NDEBUG
  5046. auto & logits_valid = lctx.logits_valid;
  5047. logits_valid.clear();
  5048. logits_valid.resize(n_tokens);
  5049. logits_out.clear();
  5050. #endif
  5051. if (batch.logits) {
  5052. logits_out.resize(n_vocab * n_tokens);
  5053. for (uint32_t i = 0; i < n_tokens; i++) {
  5054. if (batch.logits[i] == 0) {
  5055. continue;
  5056. }
  5057. memcpy(logits_out.data() + (n_vocab*i), (float *) ggml_get_data(res) + (n_vocab*i), sizeof(float)*n_vocab);
  5058. #ifndef NDEBUG
  5059. logits_valid[i] = true;
  5060. #endif
  5061. }
  5062. } else if (lctx.logits_all) {
  5063. logits_out.resize(n_vocab * n_tokens);
  5064. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*n_tokens);
  5065. #ifndef NDEBUG
  5066. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5067. #endif
  5068. } else {
  5069. logits_out.resize(n_vocab);
  5070. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(n_tokens - 1)), sizeof(float)*n_vocab);
  5071. #ifndef NDEBUG
  5072. logits_valid[n_tokens - 1] = true;
  5073. #endif
  5074. }
  5075. }
  5076. // extract embeddings
  5077. if (!lctx.embedding.empty()) {
  5078. auto & embedding_out = lctx.embedding;
  5079. embedding_out.resize(n_embd);
  5080. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(n_tokens - 1)), sizeof(float)*n_embd);
  5081. }
  5082. // measure the performance only for the single-token evals
  5083. if (n_tokens == 1) {
  5084. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5085. lctx.n_eval++;
  5086. }
  5087. else if (n_tokens > 1) {
  5088. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5089. lctx.n_p_eval += n_tokens;
  5090. }
  5091. // get a more accurate load time, upon first eval
  5092. // TODO: fix this
  5093. if (!lctx.has_evaluated_once) {
  5094. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5095. lctx.has_evaluated_once = true;
  5096. }
  5097. return 0;
  5098. }
  5099. //
  5100. // tokenizer
  5101. //
  5102. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5103. return vocab.type;
  5104. }
  5105. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5106. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5107. }
  5108. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5109. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5110. }
  5111. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5112. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5113. }
  5114. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5115. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5116. }
  5117. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5118. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5119. }
  5120. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5121. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5122. const auto& token_data = vocab.id_to_token.at(id);
  5123. switch (llama_vocab_get_type(vocab)) {
  5124. case LLAMA_VOCAB_TYPE_SPM: {
  5125. auto buf = token_data.text.substr(3, 2);
  5126. return strtol(buf.c_str(), NULL, 16);
  5127. }
  5128. case LLAMA_VOCAB_TYPE_BPE: {
  5129. GGML_ASSERT(false);
  5130. return unicode_to_bytes_bpe(token_data.text);
  5131. }
  5132. default:
  5133. GGML_ASSERT(false);
  5134. }
  5135. }
  5136. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5137. static const char * hex = "0123456789ABCDEF";
  5138. switch (llama_vocab_get_type(vocab)) {
  5139. case LLAMA_VOCAB_TYPE_SPM: {
  5140. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5141. return vocab.token_to_id.at(buf);
  5142. }
  5143. case LLAMA_VOCAB_TYPE_BPE: {
  5144. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5145. }
  5146. default:
  5147. GGML_ASSERT(false);
  5148. }
  5149. }
  5150. static void llama_escape_whitespace(std::string & text) {
  5151. replace_all(text, " ", "\xe2\x96\x81");
  5152. }
  5153. static void llama_unescape_whitespace(std::string & word) {
  5154. replace_all(word, "\xe2\x96\x81", " ");
  5155. }
  5156. struct llm_symbol {
  5157. using index = int;
  5158. index prev;
  5159. index next;
  5160. const char * text;
  5161. size_t n;
  5162. };
  5163. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5164. // SPM tokenizer
  5165. // original implementation:
  5166. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5167. struct llm_bigram_spm {
  5168. struct comparator {
  5169. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5170. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5171. }
  5172. };
  5173. using queue_storage = std::vector<llm_bigram_spm>;
  5174. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5175. llm_symbol::index left;
  5176. llm_symbol::index right;
  5177. float score;
  5178. size_t size;
  5179. };
  5180. struct llm_tokenizer_spm {
  5181. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5182. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5183. // split string into utf8 chars
  5184. int index = 0;
  5185. size_t offs = 0;
  5186. while (offs < text.size()) {
  5187. llm_symbol sym;
  5188. size_t len = utf8_len(text[offs]);
  5189. sym.text = text.c_str() + offs;
  5190. sym.n = std::min(len, text.size() - offs);
  5191. offs += sym.n;
  5192. sym.prev = index - 1;
  5193. sym.next = offs == text.size() ? -1 : index + 1;
  5194. index++;
  5195. symbols.emplace_back(sym);
  5196. }
  5197. // seed the work queue with all possible 2-character tokens.
  5198. for (size_t i = 1; i < symbols.size(); ++i) {
  5199. try_add_bigram(i - 1, i);
  5200. }
  5201. // keep substituting the highest frequency pairs for as long as we can.
  5202. while (!work_queue.empty()) {
  5203. auto bigram = work_queue.top();
  5204. work_queue.pop();
  5205. auto & left_sym = symbols[bigram.left];
  5206. auto & right_sym = symbols[bigram.right];
  5207. // if one of the symbols already got merged, skip it.
  5208. if (left_sym.n == 0 || right_sym.n == 0 ||
  5209. left_sym.n + right_sym.n != bigram.size) {
  5210. continue;
  5211. }
  5212. // merge the right sym into the left one
  5213. left_sym.n += right_sym.n;
  5214. right_sym.n = 0;
  5215. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5216. // remove the right sym from the chain
  5217. left_sym.next = right_sym.next;
  5218. if (right_sym.next >= 0) {
  5219. symbols[right_sym.next].prev = bigram.left;
  5220. }
  5221. // find more substitutions
  5222. try_add_bigram(left_sym.prev, bigram.left);
  5223. try_add_bigram(bigram.left, left_sym.next);
  5224. }
  5225. for (int i = 0; i != -1; i = symbols[i].next) {
  5226. auto & symbol = symbols[i];
  5227. resegment(symbol, output);
  5228. }
  5229. }
  5230. private:
  5231. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5232. auto text = std::string(symbol.text, symbol.n);
  5233. auto token = vocab.token_to_id.find(text);
  5234. // Do we need to support is_unused?
  5235. if (token != vocab.token_to_id.end()) {
  5236. output.push_back((*token).second);
  5237. return;
  5238. }
  5239. const auto p = rev_merge.find(text);
  5240. if (p == rev_merge.end()) {
  5241. // output any symbols that did not form tokens as bytes.
  5242. for (int j = 0; j < (int)symbol.n; ++j) {
  5243. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5244. output.push_back(token_id);
  5245. }
  5246. return;
  5247. }
  5248. resegment(symbols[p->second.first], output);
  5249. resegment(symbols[p->second.second], output);
  5250. }
  5251. void try_add_bigram(int left, int right) {
  5252. if (left == -1 || right == -1) {
  5253. return;
  5254. }
  5255. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5256. auto token = vocab.token_to_id.find(text);
  5257. if (token == vocab.token_to_id.end()) {
  5258. return;
  5259. }
  5260. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5261. return;
  5262. }
  5263. const auto & tok_data = vocab.id_to_token[(*token).second];
  5264. llm_bigram_spm bigram;
  5265. bigram.left = left;
  5266. bigram.right = right;
  5267. bigram.score = tok_data.score;
  5268. bigram.size = text.size();
  5269. work_queue.push(bigram);
  5270. // Do we need to support is_unused?
  5271. rev_merge[text] = std::make_pair(left, right);
  5272. }
  5273. const llama_vocab & vocab;
  5274. std::vector<llm_symbol> symbols;
  5275. llm_bigram_spm::queue work_queue;
  5276. std::map<std::string, std::pair<int, int>> rev_merge;
  5277. };
  5278. // BPE tokenizer
  5279. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5280. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5281. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5282. struct llm_bigram_bpe {
  5283. struct comparator {
  5284. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5285. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5286. }
  5287. };
  5288. using queue_storage = std::vector<llm_bigram_bpe>;
  5289. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5290. llm_symbol::index left;
  5291. llm_symbol::index right;
  5292. std::string text;
  5293. int rank;
  5294. size_t size;
  5295. };
  5296. struct llm_tokenizer_bpe {
  5297. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5298. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5299. int final_prev_index = -1;
  5300. auto word_collection = bpe_gpt2_preprocess(text);
  5301. symbols_final.clear();
  5302. for (auto & word : word_collection) {
  5303. work_queue = llm_bigram_bpe::queue();
  5304. symbols.clear();
  5305. int index = 0;
  5306. size_t offset = 0;
  5307. while (offset < word.size()) {
  5308. llm_symbol sym;
  5309. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  5310. sym.text = word.c_str() + offset;
  5311. sym.n = char_len;
  5312. offset += sym.n;
  5313. sym.prev = index - 1;
  5314. sym.next = offset == word.size() ? -1 : index + 1;
  5315. index++;
  5316. symbols.emplace_back(sym);
  5317. }
  5318. for (size_t i = 1; i < symbols.size(); ++i) {
  5319. add_new_bigram(i - 1, i);
  5320. }
  5321. // build token(s)
  5322. while (!work_queue.empty()) {
  5323. auto bigram = work_queue.top();
  5324. work_queue.pop();
  5325. auto & left_symbol = symbols[bigram.left];
  5326. auto & right_symbol = symbols[bigram.right];
  5327. if (left_symbol.n == 0 || right_symbol.n == 0) {
  5328. continue;
  5329. }
  5330. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  5331. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  5332. if (left_token + right_token != bigram.text) {
  5333. continue; // Skip this bigram if it's outdated
  5334. }
  5335. // merge the right sym into the left one
  5336. left_symbol.n += right_symbol.n;
  5337. right_symbol.n = 0;
  5338. // remove the right sym from the chain
  5339. left_symbol.next = right_symbol.next;
  5340. if (right_symbol.next >= 0) {
  5341. symbols[right_symbol.next].prev = bigram.left;
  5342. }
  5343. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  5344. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  5345. }
  5346. // add the fnished tokens to the final list keeping correct order for next and prev
  5347. for (auto & sym : symbols) {
  5348. if (sym.n > 0) {
  5349. sym.prev = final_prev_index;
  5350. sym.next = -1;
  5351. if (final_prev_index != -1) {
  5352. symbols_final[final_prev_index].next = symbols_final.size();
  5353. }
  5354. symbols_final.emplace_back(sym);
  5355. final_prev_index = symbols_final.size() - 1;
  5356. }
  5357. }
  5358. }
  5359. symbols = symbols_final;
  5360. if (!symbols.empty()) {
  5361. for (int i = 0; i != -1; i = symbols[i].next) {
  5362. auto & symbol = symbols[i];
  5363. if (symbol.n == 0) {
  5364. continue;
  5365. }
  5366. const std::string str = std::string(symbol.text, symbol.n);
  5367. const auto token = vocab.token_to_id.find(str);
  5368. if (token == vocab.token_to_id.end()) {
  5369. for (auto j = str.begin(); j != str.end(); ++j) {
  5370. std::string byte_str(1, *j);
  5371. auto token_multibyte = vocab.token_to_id.find(byte_str);
  5372. if (token_multibyte == vocab.token_to_id.end()) {
  5373. throw std::runtime_error("ERROR: byte not found in vocab");
  5374. }
  5375. output.push_back((*token_multibyte).second);
  5376. }
  5377. } else {
  5378. output.push_back((*token).second);
  5379. }
  5380. }
  5381. }
  5382. }
  5383. private:
  5384. void add_new_bigram(int left, int right) {
  5385. if (left == -1 || right == -1) {
  5386. return;
  5387. }
  5388. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  5389. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  5390. int rank_found = -1;
  5391. rank_found = vocab.find_bpe_rank(left_token, right_token);
  5392. if (rank_found < 0) {
  5393. return;
  5394. }
  5395. llm_bigram_bpe bigram;
  5396. bigram.left = left;
  5397. bigram.right = right;
  5398. bigram.text = left_token + right_token;
  5399. bigram.size = left_token.size() + right_token.size();
  5400. bigram.rank = rank_found;
  5401. work_queue.push(bigram);
  5402. }
  5403. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  5404. std::vector<std::string> bpe_words;
  5405. std::vector<std::string> bpe_encoded_words;
  5406. std::string token = "";
  5407. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  5408. bool collecting_numeric = false;
  5409. bool collecting_letter = false;
  5410. bool collecting_special = false;
  5411. bool collecting_whitespace_lookahead = false;
  5412. bool collecting = false;
  5413. std::vector<std::string> text_utf;
  5414. text_utf.reserve(text.size());
  5415. bpe_words.reserve(text.size());
  5416. bpe_encoded_words.reserve(text.size());
  5417. auto cps = codepoints_from_utf8(text);
  5418. for (size_t i = 0; i < cps.size(); ++i)
  5419. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  5420. for (int i = 0; i < (int)text_utf.size(); i++) {
  5421. const std::string & utf_char = text_utf[i];
  5422. bool split_condition = false;
  5423. int bytes_remain = text_utf.size() - i;
  5424. // forward backward lookups
  5425. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  5426. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  5427. // handling contractions
  5428. if (!split_condition && bytes_remain >= 2) {
  5429. // 's|'t|'m|'d
  5430. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  5431. split_condition = true;
  5432. }
  5433. if (split_condition) {
  5434. if (token.size()) {
  5435. bpe_words.emplace_back(token); // push previous content as token
  5436. }
  5437. token = utf_char + utf_char_next;
  5438. bpe_words.emplace_back(token);
  5439. token = "";
  5440. i++;
  5441. continue;
  5442. }
  5443. }
  5444. if (!split_condition && bytes_remain >= 3) {
  5445. // 're|'ve|'ll
  5446. if (utf_char == "\'" && (
  5447. (utf_char_next == "r" && utf_char_next_next == "e") ||
  5448. (utf_char_next == "v" && utf_char_next_next == "e") ||
  5449. (utf_char_next == "l" && utf_char_next_next == "l"))
  5450. ) {
  5451. split_condition = true;
  5452. }
  5453. if (split_condition) {
  5454. // current token + next token can be defined
  5455. if (token.size()) {
  5456. bpe_words.emplace_back(token); // push previous content as token
  5457. }
  5458. token = utf_char + utf_char_next + utf_char_next_next;
  5459. bpe_words.emplace_back(token); // the contraction
  5460. token = "";
  5461. i += 2;
  5462. continue;
  5463. }
  5464. }
  5465. if (!split_condition && !collecting) {
  5466. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  5467. collecting_letter = true;
  5468. collecting = true;
  5469. }
  5470. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5471. collecting_numeric = true;
  5472. collecting = true;
  5473. }
  5474. else if (
  5475. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  5476. (!token.size() && utf_char == " " && codepoint_type(utf_char_next) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && codepoint_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  5477. ) {
  5478. collecting_special = true;
  5479. collecting = true;
  5480. }
  5481. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  5482. collecting_whitespace_lookahead = true;
  5483. collecting = true;
  5484. }
  5485. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  5486. split_condition = true;
  5487. }
  5488. }
  5489. else if (!split_condition && collecting) {
  5490. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  5491. split_condition = true;
  5492. }
  5493. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  5494. split_condition = true;
  5495. }
  5496. else if (collecting_special && (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  5497. split_condition = true;
  5498. }
  5499. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5500. split_condition = true;
  5501. }
  5502. }
  5503. if (utf_char_next == "") {
  5504. split_condition = true; // final
  5505. token += utf_char;
  5506. }
  5507. if (split_condition) {
  5508. if (token.size()) {
  5509. bpe_words.emplace_back(token);
  5510. }
  5511. token = utf_char;
  5512. collecting = false;
  5513. collecting_letter = false;
  5514. collecting_numeric = false;
  5515. collecting_special = false;
  5516. collecting_whitespace_lookahead = false;
  5517. }
  5518. else {
  5519. token += utf_char;
  5520. }
  5521. }
  5522. for (std::string & word : bpe_words) {
  5523. std::string encoded_token = "";
  5524. for (char & c : word) {
  5525. encoded_token += bytes_to_unicode_bpe(c);
  5526. }
  5527. bpe_encoded_words.emplace_back(encoded_token);
  5528. }
  5529. return bpe_encoded_words;
  5530. }
  5531. const llama_vocab & vocab;
  5532. std::vector<llm_symbol> symbols;
  5533. std::vector<llm_symbol> symbols_final;
  5534. llm_bigram_bpe::queue work_queue;
  5535. };
  5536. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  5537. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  5538. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  5539. } FRAGMENT_BUFFER_VARIANT_TYPE;
  5540. struct fragment_buffer_variant{
  5541. fragment_buffer_variant(llama_vocab::id _token)
  5542. :
  5543. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  5544. token(_token),
  5545. raw_text(_dummy),
  5546. offset(0),
  5547. length(0){}
  5548. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  5549. :
  5550. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  5551. token((llama_vocab::id)-1),
  5552. raw_text(_raw_text),
  5553. offset(_offset),
  5554. length(_length){
  5555. GGML_ASSERT( _offset >= 0 );
  5556. GGML_ASSERT( _length >= 1 );
  5557. GGML_ASSERT( offset + length <= raw_text.length() );
  5558. }
  5559. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  5560. const llama_vocab::id token;
  5561. const std::string _dummy;
  5562. const std::string & raw_text;
  5563. const uint64_t offset;
  5564. const uint64_t length;
  5565. };
  5566. // #define PRETOKENIZERDEBUG
  5567. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  5568. {
  5569. // for each special token
  5570. for (const auto & st: vocab.special_tokens_cache) {
  5571. const auto & special_token = st.first;
  5572. const auto & special_id = st.second;
  5573. // for each text fragment
  5574. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  5575. while (it != buffer.end()) {
  5576. auto & fragment = (*it);
  5577. // if a fragment is text ( not yet processed )
  5578. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  5579. auto * raw_text = &(fragment.raw_text);
  5580. auto raw_text_base_offset = fragment.offset;
  5581. auto raw_text_base_length = fragment.length;
  5582. // loop over the text
  5583. while (true) {
  5584. // find the first occurrence of a given special token in this fragment
  5585. // passing offset argument only limit the "search area" but match coordinates
  5586. // are still relative to the source full raw_text
  5587. auto match = raw_text->find(special_token, raw_text_base_offset);
  5588. // no occurrences found, stop processing this fragment for a given special token
  5589. if (match == std::string::npos) break;
  5590. // check if match is within bounds of offset <-> length
  5591. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  5592. #ifdef PRETOKENIZERDEBUG
  5593. fprintf(stderr, "FF: (%ld %ld %ld) '%s'\n", raw_text->length(), raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  5594. #endif
  5595. auto source = std::distance(buffer.begin(), it);
  5596. // if match is further than base offset
  5597. // then we have some text to the left of it
  5598. if (match > raw_text_base_offset) {
  5599. // left
  5600. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  5601. const int64_t left_reminder_length = match - raw_text_base_offset;
  5602. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  5603. #ifdef PRETOKENIZERDEBUG
  5604. fprintf(stderr, "FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  5605. #endif
  5606. it++;
  5607. }
  5608. // special token
  5609. buffer.emplace_after(it, special_id);
  5610. it++;
  5611. // right
  5612. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  5613. const int64_t right_reminder_offset = match + special_token.length();
  5614. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  5615. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  5616. #ifdef PRETOKENIZERDEBUG
  5617. fprintf(stderr, "FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  5618. #endif
  5619. it++;
  5620. if (source == 0) {
  5621. buffer.erase_after(buffer.before_begin());
  5622. } else {
  5623. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  5624. }
  5625. // repeat for the right side
  5626. raw_text_base_offset = right_reminder_offset;
  5627. raw_text_base_length = right_reminder_length;
  5628. #ifdef PRETOKENIZERDEBUG
  5629. fprintf(stderr, "RR: (%ld %ld) '%s'\n", raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  5630. #endif
  5631. } else {
  5632. if (source == 0) {
  5633. buffer.erase_after(buffer.before_begin());
  5634. } else {
  5635. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  5636. }
  5637. break;
  5638. }
  5639. }
  5640. }
  5641. it++;
  5642. }
  5643. }
  5644. }
  5645. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  5646. std::vector<llama_vocab::id> output;
  5647. // OG tokenizer behavior:
  5648. //
  5649. // tokenizer.encode('', add_bos=True) returns [1]
  5650. // tokenizer.encode('', add_bos=False) returns []
  5651. if (bos && vocab.special_bos_id != -1) {
  5652. output.push_back(vocab.special_bos_id);
  5653. }
  5654. if (raw_text.empty()) {
  5655. return output;
  5656. }
  5657. std::forward_list<fragment_buffer_variant> fragment_buffer;
  5658. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  5659. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  5660. switch (vocab.type) {
  5661. case LLAMA_VOCAB_TYPE_SPM:
  5662. {
  5663. for (const auto & fragment: fragment_buffer)
  5664. {
  5665. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  5666. {
  5667. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  5668. // TODO: It's likely possible to get rid of this string copy entirely
  5669. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  5670. // and passing 'add space prefix' as bool argument
  5671. //
  5672. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  5673. if (&fragment == &fragment_buffer.front()) {
  5674. raw_text = " " + raw_text; // prefix with space if the first token is not special
  5675. }
  5676. #ifdef PRETOKENIZERDEBUG
  5677. fprintf(stderr,"TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  5678. #endif
  5679. llm_tokenizer_spm tokenizer(vocab);
  5680. llama_escape_whitespace(raw_text);
  5681. tokenizer.tokenize(raw_text, output);
  5682. }
  5683. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  5684. {
  5685. output.push_back(fragment.token);
  5686. }
  5687. }
  5688. } break;
  5689. case LLAMA_VOCAB_TYPE_BPE:
  5690. {
  5691. for (const auto & fragment: fragment_buffer)
  5692. {
  5693. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  5694. {
  5695. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  5696. #ifdef PRETOKENIZERDEBUG
  5697. fprintf(stderr,"TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  5698. #endif
  5699. llm_tokenizer_bpe tokenizer(vocab);
  5700. tokenizer.tokenize(raw_text, output);
  5701. }
  5702. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  5703. {
  5704. output.push_back(fragment.token);
  5705. }
  5706. }
  5707. } break;
  5708. }
  5709. return output;
  5710. }
  5711. //
  5712. // grammar - internal
  5713. //
  5714. struct llama_partial_utf8 {
  5715. uint32_t value; // bit value so far (unshifted)
  5716. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  5717. };
  5718. struct llama_grammar {
  5719. const std::vector<std::vector<llama_grammar_element>> rules;
  5720. std::vector<std::vector<const llama_grammar_element *>> stacks;
  5721. // buffer for partially generated UTF-8 sequence from accepted tokens
  5722. llama_partial_utf8 partial_utf8;
  5723. };
  5724. struct llama_grammar_candidate {
  5725. size_t index;
  5726. const uint32_t * code_points;
  5727. llama_partial_utf8 partial_utf8;
  5728. };
  5729. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  5730. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  5731. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  5732. const std::string & src,
  5733. llama_partial_utf8 partial_start) {
  5734. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  5735. const char * pos = src.c_str();
  5736. std::vector<uint32_t> code_points;
  5737. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  5738. code_points.reserve(src.size() + 1);
  5739. uint32_t value = partial_start.value;
  5740. int n_remain = partial_start.n_remain;
  5741. // continue previous decode, if applicable
  5742. while (*pos != 0 && n_remain > 0) {
  5743. uint8_t next_byte = static_cast<uint8_t>(*pos);
  5744. if ((next_byte >> 6) != 2) {
  5745. // invalid sequence, abort
  5746. code_points.push_back(0);
  5747. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  5748. }
  5749. value = (value << 6) + (next_byte & 0x3F);
  5750. ++pos;
  5751. --n_remain;
  5752. }
  5753. if (partial_start.n_remain > 0 && n_remain == 0) {
  5754. code_points.push_back(value);
  5755. }
  5756. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  5757. while (*pos != 0) {
  5758. uint8_t first_byte = static_cast<uint8_t>(*pos);
  5759. uint8_t highbits = first_byte >> 4;
  5760. n_remain = lookup[highbits] - 1;
  5761. if (n_remain < 0) {
  5762. // invalid sequence, abort
  5763. code_points.clear();
  5764. code_points.push_back(0);
  5765. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  5766. }
  5767. uint8_t mask = (1 << (7 - n_remain)) - 1;
  5768. value = first_byte & mask;
  5769. ++pos;
  5770. while (*pos != 0 && n_remain > 0) {
  5771. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  5772. ++pos;
  5773. --n_remain;
  5774. }
  5775. if (n_remain == 0) {
  5776. code_points.push_back(value);
  5777. }
  5778. }
  5779. code_points.push_back(0);
  5780. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  5781. }
  5782. // returns true iff pos points to the end of one of the definitions of a rule
  5783. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  5784. switch (pos->type) {
  5785. case LLAMA_GRETYPE_END: return true; // NOLINT
  5786. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  5787. default: return false;
  5788. }
  5789. }
  5790. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  5791. // asserts that pos is pointing to a char range element
  5792. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  5793. const llama_grammar_element * pos,
  5794. const uint32_t chr) {
  5795. bool found = false;
  5796. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  5797. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  5798. do {
  5799. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  5800. // inclusive range, e.g. [a-z]
  5801. found = found || (pos->value <= chr && chr <= pos[1].value);
  5802. pos += 2;
  5803. } else {
  5804. // exact char match, e.g. [a] or "a"
  5805. found = found || pos->value == chr;
  5806. pos += 1;
  5807. }
  5808. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  5809. return std::make_pair(found == is_positive_char, pos);
  5810. }
  5811. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  5812. // range at pos (regular or inverse range)
  5813. // asserts that pos is pointing to a char range element
  5814. static bool llama_grammar_match_partial_char(
  5815. const llama_grammar_element * pos,
  5816. const llama_partial_utf8 partial_utf8) {
  5817. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  5818. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  5819. uint32_t partial_value = partial_utf8.value;
  5820. int n_remain = partial_utf8.n_remain;
  5821. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  5822. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  5823. return false;
  5824. }
  5825. // range of possible code points this partial UTF-8 sequence could complete to
  5826. uint32_t low = partial_value << (n_remain * 6);
  5827. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  5828. if (low == 0) {
  5829. if (n_remain == 2) {
  5830. low = 1 << 11;
  5831. } else if (n_remain == 3) {
  5832. low = 1 << 16;
  5833. }
  5834. }
  5835. do {
  5836. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  5837. // inclusive range, e.g. [a-z]
  5838. if (pos->value <= high && low <= pos[1].value) {
  5839. return is_positive_char;
  5840. }
  5841. pos += 2;
  5842. } else {
  5843. // exact char match, e.g. [a] or "a"
  5844. if (low <= pos->value && pos->value <= high) {
  5845. return is_positive_char;
  5846. }
  5847. pos += 1;
  5848. }
  5849. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  5850. return !is_positive_char;
  5851. }
  5852. // transforms a grammar pushdown stack into N possible stacks, all ending
  5853. // at a character range (terminal element)
  5854. static void llama_grammar_advance_stack(
  5855. const std::vector<std::vector<llama_grammar_element>> & rules,
  5856. const std::vector<const llama_grammar_element *> & stack,
  5857. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  5858. if (stack.empty()) {
  5859. new_stacks.emplace_back(stack);
  5860. return;
  5861. }
  5862. const llama_grammar_element * pos = stack.back();
  5863. switch (pos->type) {
  5864. case LLAMA_GRETYPE_RULE_REF: {
  5865. const size_t rule_id = static_cast<size_t>(pos->value);
  5866. const llama_grammar_element * subpos = rules[rule_id].data();
  5867. do {
  5868. // init new stack without the top (pos)
  5869. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  5870. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  5871. // if this rule ref is followed by another element, add that to stack
  5872. new_stack.push_back(pos + 1);
  5873. }
  5874. if (!llama_grammar_is_end_of_sequence(subpos)) {
  5875. // if alternate is nonempty, add to stack
  5876. new_stack.push_back(subpos);
  5877. }
  5878. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  5879. while (!llama_grammar_is_end_of_sequence(subpos)) {
  5880. // scan to end of alternate def
  5881. subpos++;
  5882. }
  5883. if (subpos->type == LLAMA_GRETYPE_ALT) {
  5884. // there's another alternate def of this rule to process
  5885. subpos++;
  5886. } else {
  5887. break;
  5888. }
  5889. } while (true);
  5890. break;
  5891. }
  5892. case LLAMA_GRETYPE_CHAR:
  5893. case LLAMA_GRETYPE_CHAR_NOT:
  5894. new_stacks.emplace_back(stack);
  5895. break;
  5896. default:
  5897. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  5898. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  5899. // those
  5900. GGML_ASSERT(false);
  5901. }
  5902. }
  5903. // takes a set of possible pushdown stacks on a grammar, which are required to
  5904. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  5905. // produces the N possible stacks if the given char is accepted at those
  5906. // positions
  5907. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  5908. const std::vector<std::vector<llama_grammar_element>> & rules,
  5909. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  5910. const uint32_t chr) {
  5911. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  5912. for (const auto & stack : stacks) {
  5913. if (stack.empty()) {
  5914. continue;
  5915. }
  5916. auto match = llama_grammar_match_char(stack.back(), chr);
  5917. if (match.first) {
  5918. const llama_grammar_element * pos = match.second;
  5919. // update top of stack to next element, if any
  5920. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  5921. if (!llama_grammar_is_end_of_sequence(pos)) {
  5922. new_stack.push_back(pos);
  5923. }
  5924. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  5925. }
  5926. }
  5927. return new_stacks;
  5928. }
  5929. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  5930. const std::vector<std::vector<llama_grammar_element>> & rules,
  5931. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  5932. const std::vector<llama_grammar_candidate> & candidates);
  5933. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  5934. const std::vector<std::vector<llama_grammar_element>> & rules,
  5935. const std::vector<const llama_grammar_element *> & stack,
  5936. const std::vector<llama_grammar_candidate> & candidates) {
  5937. std::vector<llama_grammar_candidate> rejects;
  5938. if (stack.empty()) {
  5939. for (const auto & tok : candidates) {
  5940. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  5941. rejects.push_back(tok);
  5942. }
  5943. }
  5944. return rejects;
  5945. }
  5946. const llama_grammar_element * stack_pos = stack.back();
  5947. std::vector<llama_grammar_candidate> next_candidates;
  5948. for (const auto & tok : candidates) {
  5949. if (*tok.code_points == 0) {
  5950. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  5951. // that cannot satisfy this position in grammar
  5952. if (tok.partial_utf8.n_remain != 0 &&
  5953. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  5954. rejects.push_back(tok);
  5955. }
  5956. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  5957. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  5958. } else {
  5959. rejects.push_back(tok);
  5960. }
  5961. }
  5962. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  5963. // update top of stack to next element, if any
  5964. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  5965. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  5966. stack_after.push_back(stack_pos_after);
  5967. }
  5968. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  5969. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  5970. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  5971. for (const auto & tok : next_rejects) {
  5972. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  5973. }
  5974. return rejects;
  5975. }
  5976. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  5977. const std::vector<std::vector<llama_grammar_element>> & rules,
  5978. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  5979. const std::vector<llama_grammar_candidate> & candidates) {
  5980. GGML_ASSERT(!stacks.empty()); // REVIEW
  5981. if (candidates.empty()) {
  5982. return std::vector<llama_grammar_candidate>();
  5983. }
  5984. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  5985. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  5986. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  5987. }
  5988. return rejects;
  5989. }
  5990. //
  5991. // grammar - external
  5992. //
  5993. struct llama_grammar * llama_grammar_init(
  5994. const llama_grammar_element ** rules,
  5995. size_t n_rules,
  5996. size_t start_rule_index) {
  5997. const llama_grammar_element * pos;
  5998. // copy rule definitions into vectors
  5999. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6000. for (size_t i = 0; i < n_rules; i++) {
  6001. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6002. vec_rules[i].push_back(*pos);
  6003. }
  6004. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6005. }
  6006. // loop over alternates of start rule to build initial stacks
  6007. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6008. pos = rules[start_rule_index];
  6009. do {
  6010. std::vector<const llama_grammar_element *> stack;
  6011. if (!llama_grammar_is_end_of_sequence(pos)) {
  6012. // if alternate is nonempty, add to stack
  6013. stack.push_back(pos);
  6014. }
  6015. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6016. while (!llama_grammar_is_end_of_sequence(pos)) {
  6017. // scan to end of alternate def
  6018. pos++;
  6019. }
  6020. if (pos->type == LLAMA_GRETYPE_ALT) {
  6021. // there's another alternate def of this rule to process
  6022. pos++;
  6023. } else {
  6024. break;
  6025. }
  6026. } while (true);
  6027. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6028. }
  6029. void llama_grammar_free(struct llama_grammar * grammar) {
  6030. delete grammar;
  6031. }
  6032. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6033. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6034. // redirect elements in stacks to point to new rules
  6035. for (size_t is = 0; is < result->stacks.size(); is++) {
  6036. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6037. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6038. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6039. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6040. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6041. }
  6042. }
  6043. }
  6044. }
  6045. }
  6046. return result;
  6047. }
  6048. //
  6049. // sampling
  6050. //
  6051. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6052. if (seed == LLAMA_DEFAULT_SEED) {
  6053. seed = time(NULL);
  6054. }
  6055. ctx->rng.seed(seed);
  6056. }
  6057. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6058. GGML_ASSERT(candidates->size > 0);
  6059. const int64_t t_start_sample_us = ggml_time_us();
  6060. // Sort the logits in descending order
  6061. if (!candidates->sorted) {
  6062. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6063. return a.logit > b.logit;
  6064. });
  6065. candidates->sorted = true;
  6066. }
  6067. float max_l = candidates->data[0].logit;
  6068. float cum_sum = 0.0f;
  6069. for (size_t i = 0; i < candidates->size; ++i) {
  6070. float p = expf(candidates->data[i].logit - max_l);
  6071. candidates->data[i].p = p;
  6072. cum_sum += p;
  6073. }
  6074. for (size_t i = 0; i < candidates->size; ++i) {
  6075. candidates->data[i].p /= cum_sum;
  6076. }
  6077. if (ctx) {
  6078. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6079. }
  6080. }
  6081. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  6082. const int64_t t_start_sample_us = ggml_time_us();
  6083. k = std::max(k, (int) min_keep);
  6084. k = std::min(k, (int) candidates->size);
  6085. // Sort scores in descending order
  6086. if (!candidates->sorted) {
  6087. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6088. return a.logit > b.logit;
  6089. };
  6090. if (k == (int) candidates->size) {
  6091. std::sort(candidates->data, candidates->data + candidates->size, comp);
  6092. } else {
  6093. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6094. }
  6095. candidates->sorted = true;
  6096. }
  6097. candidates->size = k;
  6098. if (ctx) {
  6099. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6100. }
  6101. }
  6102. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6103. if (p >= 1.0f) {
  6104. return;
  6105. }
  6106. llama_sample_softmax(ctx, candidates);
  6107. const int64_t t_start_sample_us = ggml_time_us();
  6108. // Compute the cumulative probabilities
  6109. float cum_sum = 0.0f;
  6110. size_t last_idx = candidates->size;
  6111. for (size_t i = 0; i < candidates->size; ++i) {
  6112. cum_sum += candidates->data[i].p;
  6113. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6114. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6115. if (cum_sum >= p && i + 1 >= min_keep) {
  6116. last_idx = i + 1;
  6117. break;
  6118. }
  6119. }
  6120. // Resize the output vector to keep only the top-p tokens
  6121. candidates->size = last_idx;
  6122. if (ctx) {
  6123. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6124. }
  6125. }
  6126. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6127. if (p <= 0.0f || !candidates->size) {
  6128. return;
  6129. }
  6130. llama_sample_softmax(ctx, candidates);
  6131. const int64_t t_start_sample_us = ggml_time_us();
  6132. float scale = candidates->data[0].p; // scale by max prob
  6133. size_t i = 1; // first token always matches
  6134. for (; i < candidates->size; ++i) {
  6135. if (candidates->data[i].p < p * scale && i >= min_keep) {
  6136. break; // prob too small
  6137. }
  6138. }
  6139. // Resize the output vector to keep only the matching tokens
  6140. candidates->size = i;
  6141. if (ctx) {
  6142. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6143. }
  6144. }
  6145. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6146. if (z >= 1.0f || candidates->size <= 2) {
  6147. return;
  6148. }
  6149. llama_sample_softmax(nullptr, candidates);
  6150. const int64_t t_start_sample_us = ggml_time_us();
  6151. // Compute the first and second derivatives
  6152. std::vector<float> first_derivatives(candidates->size - 1);
  6153. std::vector<float> second_derivatives(candidates->size - 2);
  6154. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6155. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6156. }
  6157. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6158. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6159. }
  6160. // Calculate absolute value of second derivatives
  6161. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6162. second_derivatives[i] = std::abs(second_derivatives[i]);
  6163. }
  6164. // Normalize the second derivatives
  6165. {
  6166. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6167. if (second_derivatives_sum > 1e-6f) {
  6168. for (float & value : second_derivatives) {
  6169. value /= second_derivatives_sum;
  6170. }
  6171. } else {
  6172. for (float & value : second_derivatives) {
  6173. value = 1.0f / second_derivatives.size();
  6174. }
  6175. }
  6176. }
  6177. float cum_sum = 0.0f;
  6178. size_t last_idx = candidates->size;
  6179. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6180. cum_sum += second_derivatives[i];
  6181. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6182. if (cum_sum > z && i >= min_keep) {
  6183. last_idx = i;
  6184. break;
  6185. }
  6186. }
  6187. // Resize the output vector to keep only the tokens above the tail location
  6188. candidates->size = last_idx;
  6189. if (ctx) {
  6190. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6191. }
  6192. }
  6193. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6194. // Reference implementation:
  6195. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6196. if (p >= 1.0f) {
  6197. return;
  6198. }
  6199. // Compute the softmax of logits and calculate entropy
  6200. llama_sample_softmax(nullptr, candidates);
  6201. const int64_t t_start_sample_us = ggml_time_us();
  6202. float entropy = 0.0f;
  6203. for (size_t i = 0; i < candidates->size; ++i) {
  6204. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6205. }
  6206. // Compute the absolute difference between negative log probability and entropy for each candidate
  6207. std::vector<float> shifted_scores;
  6208. for (size_t i = 0; i < candidates->size; ++i) {
  6209. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6210. shifted_scores.push_back(shifted_score);
  6211. }
  6212. // Sort tokens based on the shifted_scores and their corresponding indices
  6213. std::vector<size_t> indices(candidates->size);
  6214. std::iota(indices.begin(), indices.end(), 0);
  6215. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6216. return shifted_scores[a] < shifted_scores[b];
  6217. });
  6218. // Compute the cumulative probabilities
  6219. float cum_sum = 0.0f;
  6220. size_t last_idx = indices.size();
  6221. for (size_t i = 0; i < indices.size(); ++i) {
  6222. size_t idx = indices[i];
  6223. cum_sum += candidates->data[idx].p;
  6224. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  6225. if (cum_sum > p && i >= min_keep - 1) {
  6226. last_idx = i + 1;
  6227. break;
  6228. }
  6229. }
  6230. // Resize the output vector to keep only the locally typical tokens
  6231. std::vector<llama_token_data> new_candidates;
  6232. for (size_t i = 0; i < last_idx; ++i) {
  6233. size_t idx = indices[i];
  6234. new_candidates.push_back(candidates->data[idx]);
  6235. }
  6236. // Replace the data in candidates with the new_candidates data
  6237. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  6238. candidates->size = new_candidates.size();
  6239. candidates->sorted = false;
  6240. if (ctx) {
  6241. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6242. }
  6243. }
  6244. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6245. const int64_t t_start_sample_us = ggml_time_us();
  6246. for (size_t i = 0; i < candidates_p->size; ++i) {
  6247. candidates_p->data[i].logit /= temp;
  6248. }
  6249. if (ctx) {
  6250. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6251. }
  6252. }
  6253. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6254. llama_sample_temp(ctx, candidates_p, temp);
  6255. }
  6256. void llama_sample_repetition_penalties(
  6257. struct llama_context * ctx,
  6258. llama_token_data_array * candidates,
  6259. const llama_token * last_tokens,
  6260. size_t penalty_last_n,
  6261. float penalty_repeat,
  6262. float penalty_freq,
  6263. float penalty_present) {
  6264. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  6265. return;
  6266. }
  6267. const int64_t t_start_sample_us = ggml_time_us();
  6268. // Create a frequency map to count occurrences of each token in last_tokens
  6269. std::unordered_map<llama_token, int> token_count;
  6270. for (size_t i = 0; i < penalty_last_n; ++i) {
  6271. token_count[last_tokens[i]]++;
  6272. }
  6273. // Apply frequency and presence penalties to the candidates
  6274. for (size_t i = 0; i < candidates->size; ++i) {
  6275. const auto token_iter = token_count.find(candidates->data[i].id);
  6276. if (token_iter == token_count.end()) {
  6277. continue;
  6278. }
  6279. const int count = token_iter->second;
  6280. // 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.
  6281. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  6282. if (candidates->data[i].logit <= 0) {
  6283. candidates->data[i].logit *= penalty_repeat;
  6284. } else {
  6285. candidates->data[i].logit /= penalty_repeat;
  6286. }
  6287. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  6288. }
  6289. candidates->sorted = false;
  6290. if (ctx) {
  6291. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6292. }
  6293. }
  6294. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  6295. GGML_ASSERT(ctx);
  6296. const int64_t t_start_sample_us = ggml_time_us();
  6297. bool allow_eos = false;
  6298. for (const auto & stack : grammar->stacks) {
  6299. if (stack.empty()) {
  6300. allow_eos = true;
  6301. break;
  6302. }
  6303. }
  6304. const llama_token eos = llama_token_eos(&ctx->model);
  6305. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  6306. candidates_decoded.reserve(candidates->size);
  6307. std::vector<llama_grammar_candidate> candidates_grammar;
  6308. candidates_grammar.reserve(candidates->size);
  6309. for (size_t i = 0; i < candidates->size; ++i) {
  6310. const llama_token id = candidates->data[i].id;
  6311. const std::string piece = llama_token_to_piece(ctx, id);
  6312. if (id == eos) {
  6313. if (!allow_eos) {
  6314. candidates->data[i].logit = -INFINITY;
  6315. }
  6316. } else if (piece.empty() || piece[0] == 0) {
  6317. candidates->data[i].logit = -INFINITY;
  6318. } else {
  6319. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  6320. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  6321. }
  6322. }
  6323. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  6324. for (const auto & reject : rejects) {
  6325. candidates->data[reject.index].logit = -INFINITY;
  6326. }
  6327. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6328. }
  6329. static void llama_log_softmax(float * array, size_t size) {
  6330. float max_l = *std::max_element(array, array + size);
  6331. float sum = 0.f;
  6332. for (size_t i = 0; i < size; ++i) {
  6333. float p = expf(array[i] - max_l);
  6334. sum += p;
  6335. array[i] = p;
  6336. }
  6337. for (size_t i = 0; i < size; ++i) {
  6338. array[i] = logf(array[i] / sum);
  6339. }
  6340. }
  6341. void llama_sample_classifier_free_guidance(
  6342. struct llama_context * ctx,
  6343. llama_token_data_array * candidates,
  6344. struct llama_context * guidance_ctx,
  6345. float scale) {
  6346. int64_t t_start_sample_us = ggml_time_us();
  6347. GGML_ASSERT(ctx);
  6348. auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  6349. GGML_ASSERT(n_vocab == (int)candidates->size);
  6350. GGML_ASSERT(!candidates->sorted);
  6351. std::vector<float> logits_base;
  6352. logits_base.reserve(candidates->size);
  6353. for (size_t i = 0; i < candidates->size; ++i) {
  6354. logits_base.push_back(candidates->data[i].logit);
  6355. }
  6356. llama_log_softmax(logits_base.data(), candidates->size);
  6357. float* logits_guidance = llama_get_logits(guidance_ctx);
  6358. llama_log_softmax(logits_guidance, n_vocab);
  6359. for (int i = 0; i < n_vocab; ++i) {
  6360. float logit_guidance = logits_guidance[i];
  6361. float logit_base = logits_base[i];
  6362. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  6363. }
  6364. if (ctx) {
  6365. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6366. }
  6367. }
  6368. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  6369. GGML_ASSERT(ctx);
  6370. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  6371. int64_t t_start_sample_us;
  6372. t_start_sample_us = ggml_time_us();
  6373. llama_sample_softmax(nullptr, candidates);
  6374. // Estimate s_hat using the most probable m tokens
  6375. float s_hat = 0.0;
  6376. float sum_ti_bi = 0.0;
  6377. float sum_ti_sq = 0.0;
  6378. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  6379. float t_i = logf(float(i + 2) / float(i + 1));
  6380. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  6381. sum_ti_bi += t_i * b_i;
  6382. sum_ti_sq += t_i * t_i;
  6383. }
  6384. s_hat = sum_ti_bi / sum_ti_sq;
  6385. // Compute k from the estimated s_hat and target surprise value
  6386. float epsilon_hat = s_hat - 1;
  6387. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  6388. // Sample the next word X using top-k sampling
  6389. llama_sample_top_k(nullptr, candidates, int(k), 1);
  6390. if (ctx) {
  6391. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6392. }
  6393. llama_token X = llama_sample_token(ctx, candidates);
  6394. t_start_sample_us = ggml_time_us();
  6395. // Compute error as the difference between observed surprise and target surprise value
  6396. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6397. return candidate.id == X;
  6398. }));
  6399. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6400. float e = observed_surprise - tau;
  6401. // Update mu using the learning rate and error
  6402. *mu = *mu - eta * e;
  6403. if (ctx) {
  6404. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6405. }
  6406. return X;
  6407. }
  6408. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  6409. int64_t t_start_sample_us;
  6410. t_start_sample_us = ggml_time_us();
  6411. llama_sample_softmax(ctx, candidates);
  6412. // Truncate the words with surprise values greater than mu
  6413. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6414. return -log2f(candidate.p) > *mu;
  6415. }));
  6416. if (candidates->size == 0) {
  6417. candidates->size = 1;
  6418. }
  6419. if (ctx) {
  6420. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6421. }
  6422. // Normalize the probabilities of the remaining words
  6423. llama_sample_softmax(ctx, candidates);
  6424. // Sample the next word X from the remaining words
  6425. llama_token X = llama_sample_token(ctx, candidates);
  6426. t_start_sample_us = ggml_time_us();
  6427. // Compute error as the difference between observed surprise and target surprise value
  6428. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6429. return candidate.id == X;
  6430. }));
  6431. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6432. float e = observed_surprise - tau;
  6433. // Update mu using the learning rate and error
  6434. *mu = *mu - eta * e;
  6435. if (ctx) {
  6436. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6437. }
  6438. return X;
  6439. }
  6440. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  6441. const int64_t t_start_sample_us = ggml_time_us();
  6442. // Find max element
  6443. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6444. return a.logit < b.logit;
  6445. });
  6446. llama_token result = max_iter->id;
  6447. if (ctx) {
  6448. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6449. ctx->n_sample++;
  6450. }
  6451. return result;
  6452. }
  6453. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  6454. GGML_ASSERT(ctx);
  6455. const int64_t t_start_sample_us = ggml_time_us();
  6456. llama_sample_softmax(nullptr, candidates);
  6457. std::vector<float> probs;
  6458. probs.reserve(candidates->size);
  6459. for (size_t i = 0; i < candidates->size; ++i) {
  6460. probs.push_back(candidates->data[i].p);
  6461. }
  6462. std::discrete_distribution<> dist(probs.begin(), probs.end());
  6463. auto & rng = ctx->rng;
  6464. int idx = dist(rng);
  6465. llama_token result = candidates->data[idx].id;
  6466. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6467. ctx->n_sample++;
  6468. return result;
  6469. }
  6470. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  6471. const int64_t t_start_sample_us = ggml_time_us();
  6472. if (token == llama_token_eos(&ctx->model)) {
  6473. for (const auto & stack : grammar->stacks) {
  6474. if (stack.empty()) {
  6475. return;
  6476. }
  6477. }
  6478. GGML_ASSERT(false);
  6479. }
  6480. const std::string piece = llama_token_to_piece(ctx, token);
  6481. // Note terminating 0 in decoded string
  6482. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  6483. const auto & code_points = decoded.first;
  6484. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  6485. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  6486. }
  6487. grammar->partial_utf8 = decoded.second;
  6488. GGML_ASSERT(!grammar->stacks.empty());
  6489. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6490. }
  6491. //
  6492. // Beam search
  6493. //
  6494. struct llama_beam {
  6495. std::vector<llama_token> tokens;
  6496. float p; // Cumulative beam probability (renormalized relative to all beams)
  6497. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  6498. // Sort beams by probability. In case of ties, prefer beams at eob.
  6499. bool operator<(const llama_beam & rhs) const {
  6500. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  6501. }
  6502. // Shift off first n tokens and discard them.
  6503. void shift_tokens(const size_t n) {
  6504. if (n) {
  6505. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  6506. tokens.resize(tokens.size() - n);
  6507. }
  6508. }
  6509. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  6510. };
  6511. // A struct for calculating logit-related info.
  6512. struct llama_logit_info {
  6513. const float * const logits;
  6514. const int n_vocab;
  6515. const float max_l;
  6516. const float normalizer;
  6517. struct sum_exp {
  6518. float max_l;
  6519. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  6520. };
  6521. llama_logit_info(llama_context * ctx)
  6522. : logits(llama_get_logits(ctx))
  6523. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  6524. , max_l(*std::max_element(logits, logits + n_vocab))
  6525. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  6526. { }
  6527. llama_token_data get_token_data(const llama_token token_id) const {
  6528. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  6529. return {token_id, logits[token_id], p};
  6530. }
  6531. // Return top k token_data by logit.
  6532. std::vector<llama_token_data> top_k(size_t k) {
  6533. std::vector<llama_token_data> min_heap; // min-heap by logit
  6534. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  6535. min_heap.reserve(k_min);
  6536. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  6537. min_heap.push_back(get_token_data(token_id));
  6538. }
  6539. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  6540. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  6541. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  6542. if (min_heap.front().logit < logits[token_id]) {
  6543. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  6544. min_heap.back().id = token_id;
  6545. min_heap.back().logit = logits[token_id];
  6546. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  6547. }
  6548. }
  6549. return min_heap;
  6550. }
  6551. float probability_from_logit(float logit) const {
  6552. return normalizer * std::exp(logit - max_l);
  6553. }
  6554. };
  6555. struct llama_beam_search_data {
  6556. llama_context * ctx;
  6557. size_t n_beams;
  6558. int n_past;
  6559. int n_predict;
  6560. std::vector<llama_beam> beams;
  6561. std::vector<llama_beam> next_beams;
  6562. // Re-calculated on each loop iteration
  6563. size_t common_prefix_length;
  6564. // Used to communicate to/from callback on beams state.
  6565. std::vector<llama_beam_view> beam_views;
  6566. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  6567. : ctx(ctx)
  6568. , n_beams(n_beams)
  6569. , n_past(n_past)
  6570. , n_predict(n_predict)
  6571. , beam_views(n_beams) {
  6572. beams.reserve(n_beams);
  6573. next_beams.reserve(n_beams);
  6574. }
  6575. // Collapse beams to a single beam given by index.
  6576. void collapse_beams(const size_t beam_idx) {
  6577. if (0u < beam_idx) {
  6578. std::swap(beams[0], beams[beam_idx]);
  6579. }
  6580. beams.resize(1);
  6581. }
  6582. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  6583. // The repetitive patterns below reflect the 2 stages of heaps:
  6584. // * Gather elements until the vector is full, then call std::make_heap() on it.
  6585. // * If the heap is full and a new element is found that should be included, pop the
  6586. // least element to the back(), replace it with the new, then push it into the heap.
  6587. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  6588. // Min-heaps use a greater-than comparator.
  6589. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  6590. if (beam.eob) {
  6591. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  6592. if (next_beams.size() < n_beams) {
  6593. next_beams.push_back(std::move(beam));
  6594. if (next_beams.size() == n_beams) {
  6595. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  6596. }
  6597. } else if (next_beams.front().p < beam.p) {
  6598. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  6599. next_beams.back() = std::move(beam);
  6600. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  6601. }
  6602. } else {
  6603. // beam is not at end-of-sentence, so branch with next top_k tokens.
  6604. if (!beam.tokens.empty()) {
  6605. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  6606. }
  6607. llama_logit_info logit_info(ctx);
  6608. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  6609. size_t i=0;
  6610. if (next_beams.size() < n_beams) {
  6611. for (; next_beams.size() < n_beams ; ++i) {
  6612. llama_beam next_beam = beam;
  6613. next_beam.tokens.push_back(next_tokens[i].id);
  6614. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  6615. next_beams.push_back(std::move(next_beam));
  6616. }
  6617. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  6618. } else {
  6619. for (; next_beams.front().p == 0.0f ; ++i) {
  6620. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  6621. next_beams.back() = beam;
  6622. next_beams.back().tokens.push_back(next_tokens[i].id);
  6623. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  6624. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  6625. }
  6626. }
  6627. for (; i < n_beams ; ++i) {
  6628. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  6629. if (next_beams.front().p < next_p) {
  6630. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  6631. next_beams.back() = beam;
  6632. next_beams.back().tokens.push_back(next_tokens[i].id);
  6633. next_beams.back().p = next_p;
  6634. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  6635. }
  6636. }
  6637. }
  6638. }
  6639. // Find common_prefix_length based on beams.
  6640. // Requires beams is not empty.
  6641. size_t find_common_prefix_length() {
  6642. size_t common_prefix_length = beams[0].tokens.size();
  6643. for (size_t i = 1 ; i < beams.size() ; ++i) {
  6644. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  6645. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  6646. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  6647. common_prefix_length = j;
  6648. break;
  6649. }
  6650. }
  6651. }
  6652. return common_prefix_length;
  6653. }
  6654. // Construct beams_state to send back to caller via the callback function.
  6655. // Side effect: set common_prefix_length = find_common_prefix_length();
  6656. llama_beams_state get_beams_state(const bool last_call) {
  6657. for (size_t i = 0 ; i < beams.size() ; ++i) {
  6658. beam_views[i] = beams[i].view();
  6659. }
  6660. common_prefix_length = find_common_prefix_length();
  6661. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  6662. }
  6663. // Loop:
  6664. // * while i < n_predict, AND
  6665. // * any of the beams have not yet reached end-of-beam (eob), AND
  6666. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  6667. // (since all other beam probabilities can only decrease)
  6668. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  6669. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  6670. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  6671. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  6672. !beams[top_beam_index()].eob ; ++i) {
  6673. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  6674. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  6675. if (common_prefix_length) {
  6676. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  6677. n_past += common_prefix_length;
  6678. }
  6679. // Zero-out next_beam probabilities to place them last in following min-heap.
  6680. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  6681. for (llama_beam & beam : beams) {
  6682. beam.shift_tokens(common_prefix_length);
  6683. fill_next_beams_by_top_probabilities(beam);
  6684. }
  6685. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  6686. beams.swap(next_beams);
  6687. renormalize_beam_probabilities(beams);
  6688. }
  6689. collapse_beams(top_beam_index());
  6690. callback(callback_data, get_beams_state(true));
  6691. }
  6692. // As beams grow, the cumulative probabilities decrease.
  6693. // Renormalize them to avoid floating point underflow.
  6694. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  6695. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  6696. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  6697. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  6698. }
  6699. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  6700. size_t top_beam_index() {
  6701. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  6702. }
  6703. // Copy (p,eob) for each beam which may have been changed by the callback.
  6704. void update_beams_from_beam_views() {
  6705. for (size_t i = 0 ; i < beams.size() ; ++i) {
  6706. beams[i].p = beam_views[i].p;
  6707. beams[i].eob = beam_views[i].eob;
  6708. }
  6709. }
  6710. };
  6711. void llama_beam_search(llama_context * ctx,
  6712. llama_beam_search_callback_fn_t callback, void * callback_data,
  6713. size_t n_beams, int n_past, int n_predict) {
  6714. assert(ctx);
  6715. const int64_t t_start_sample_us = ggml_time_us();
  6716. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  6717. beam_search_data.loop(callback, callback_data);
  6718. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6719. ctx->n_sample++;
  6720. }
  6721. //
  6722. // quantization
  6723. //
  6724. template <typename T>
  6725. struct no_init {
  6726. T value;
  6727. no_init() { /* do nothing */ }
  6728. };
  6729. struct quantize_state_internal {
  6730. const llama_model & model;
  6731. const llama_model_quantize_params * params;
  6732. int n_attention_wv = 0;
  6733. int n_feed_forward_w2 = 0;
  6734. int i_attention_wv = 0;
  6735. int i_feed_forward_w2 = 0;
  6736. int n_k_quantized = 0;
  6737. int n_fallback = 0;
  6738. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  6739. : model(model)
  6740. , params(params)
  6741. {}
  6742. };
  6743. static void llama_convert_tensor_internal(
  6744. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  6745. const size_t nelements, const int nthread
  6746. ) {
  6747. if (output.size() < nelements) {
  6748. output.resize(nelements);
  6749. }
  6750. float * f32_output = (float *) output.data();
  6751. ggml_type_traits_t qtype;
  6752. if (ggml_is_quantized(tensor->type)) {
  6753. qtype = ggml_internal_get_type_traits(tensor->type);
  6754. if (qtype.to_float == NULL) {
  6755. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  6756. }
  6757. } else if (tensor->type != GGML_TYPE_F16) {
  6758. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  6759. }
  6760. if (nthread < 2) {
  6761. if (tensor->type == GGML_TYPE_F16) {
  6762. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  6763. } else if (ggml_is_quantized(tensor->type)) {
  6764. qtype.to_float(tensor->data, f32_output, nelements);
  6765. } else {
  6766. GGML_ASSERT(false); // unreachable
  6767. }
  6768. return;
  6769. }
  6770. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  6771. size_t block_size_bytes = ggml_type_size(tensor->type);
  6772. GGML_ASSERT(nelements % block_size == 0);
  6773. size_t nblocks = nelements / block_size;
  6774. size_t blocks_per_thread = nblocks / nthread;
  6775. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  6776. size_t in_buff_offs = 0;
  6777. size_t out_buff_offs = 0;
  6778. for (int tnum = 0; tnum < nthread; tnum++) {
  6779. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  6780. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  6781. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  6782. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  6783. if (typ == GGML_TYPE_F16) {
  6784. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  6785. } else {
  6786. qtype.to_float(inbuf, outbuf, nels);
  6787. }
  6788. };
  6789. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  6790. in_buff_offs += thr_block_bytes;
  6791. out_buff_offs += thr_elems;
  6792. }
  6793. for (auto & w : workers) { w.join(); }
  6794. workers.clear();
  6795. }
  6796. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  6797. const std::string name = ggml_get_name(tensor);
  6798. // TODO: avoid hardcoded tensor names - use the TN_* constants
  6799. const llm_arch arch = qs.model.arch;
  6800. const auto tn = LLM_TN(arch);
  6801. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  6802. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  6803. };
  6804. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  6805. int nx = tensor->ne[0];
  6806. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  6807. new_type = GGML_TYPE_Q8_0;
  6808. }
  6809. else if (new_type != GGML_TYPE_Q8_0) {
  6810. new_type = GGML_TYPE_Q6_K;
  6811. }
  6812. } else if (name.find("attn_v.weight") != std::string::npos) {
  6813. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  6814. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  6815. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  6816. }
  6817. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  6818. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  6819. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  6820. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  6821. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  6822. (qs.i_attention_wv < qs.n_attention_wv/8 || qs.i_attention_wv >= 7*qs.n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  6823. if (qs.model.type == MODEL_70B) {
  6824. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  6825. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  6826. // nearly negligible increase in model size by quantizing this tensor with more bits:
  6827. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  6828. }
  6829. if (qs.model.hparams.n_expert == 8) {
  6830. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  6831. // TODO: explore better strategies
  6832. new_type = GGML_TYPE_Q8_0;
  6833. }
  6834. ++qs.i_attention_wv;
  6835. } else if (name.find("attn_k.weight") != std::string::npos) {
  6836. if (qs.model.hparams.n_expert == 8) {
  6837. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  6838. // TODO: explore better strategies
  6839. new_type = GGML_TYPE_Q8_0;
  6840. }
  6841. } else if (name.find("ffn_down.weight") != std::string::npos) {
  6842. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  6843. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  6844. new_type = qs.i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K
  6845. : arch != LLM_ARCH_FALCON || use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2) ? GGML_TYPE_Q4_K
  6846. : GGML_TYPE_Q3_K;
  6847. }
  6848. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  6849. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  6850. }
  6851. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  6852. if (arch == LLM_ARCH_FALCON) {
  6853. new_type = qs.i_feed_forward_w2 < 2 ? GGML_TYPE_Q6_K :
  6854. use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  6855. } else {
  6856. if (use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  6857. }
  6858. }
  6859. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  6860. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && qs.i_feed_forward_w2 < 4) {
  6861. new_type = GGML_TYPE_Q5_K;
  6862. }
  6863. ++qs.i_feed_forward_w2;
  6864. } else if (name.find("attn_output.weight") != std::string::npos) {
  6865. if (arch != LLM_ARCH_FALCON) {
  6866. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  6867. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  6868. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  6869. } else {
  6870. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  6871. }
  6872. }
  6873. else if (name.find("attn_qkv.weight") != std::string::npos) {
  6874. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  6875. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  6876. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  6877. }
  6878. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  6879. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  6880. }
  6881. // This can be used to reduce the size of the Q5_K_S model.
  6882. // The associated PPL increase is fully in line with the size reduction
  6883. //else {
  6884. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  6885. //}
  6886. bool convert_incompatible_tensor = false;
  6887. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  6888. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  6889. int nx = tensor->ne[0];
  6890. int ny = tensor->ne[1];
  6891. if (nx % QK_K != 0) {
  6892. LLAMA_LOG_WARN("\n\n%s : tensor cols %d x %d are not divisible by %d, required for %s", __func__, nx, ny, QK_K, ggml_type_name(new_type));
  6893. convert_incompatible_tensor = true;
  6894. } else {
  6895. ++qs.n_k_quantized;
  6896. }
  6897. }
  6898. if (convert_incompatible_tensor) {
  6899. switch (new_type) {
  6900. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  6901. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  6902. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  6903. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  6904. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  6905. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  6906. }
  6907. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  6908. ++qs.n_fallback;
  6909. }
  6910. return new_type;
  6911. }
  6912. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  6913. ggml_type quantized_type;
  6914. llama_ftype ftype = params->ftype;
  6915. switch (params->ftype) {
  6916. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  6917. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  6918. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  6919. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  6920. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  6921. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  6922. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  6923. // K-quants
  6924. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  6925. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  6926. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  6927. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  6928. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  6929. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  6930. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  6931. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  6932. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  6933. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  6934. }
  6935. int nthread = params->nthread;
  6936. if (nthread <= 0) {
  6937. nthread = std::thread::hardware_concurrency();
  6938. }
  6939. // mmap consistently increases speed Linux, and also increases speed on Windows with
  6940. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  6941. #if defined(__linux__) || defined(_WIN32)
  6942. constexpr bool use_mmap = true;
  6943. #else
  6944. constexpr bool use_mmap = false;
  6945. #endif
  6946. llama_model_loader ml(fname_inp, use_mmap, NULL);
  6947. if (ml.use_mmap) {
  6948. ml.mapping.reset(new llama_mmap(&ml.file, /* prefetch */ 0, ggml_is_numa()));
  6949. }
  6950. llama_model model;
  6951. llm_load_arch(ml, model);
  6952. llm_load_hparams(ml, model);
  6953. struct quantize_state_internal qs(model, params);
  6954. if (params->only_copy) {
  6955. ftype = model.ftype;
  6956. }
  6957. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  6958. struct gguf_context * ctx_out = gguf_init_empty();
  6959. // copy the KV pairs from the input file
  6960. gguf_set_kv (ctx_out, ml.ctx_gguf);
  6961. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  6962. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  6963. for (int i = 0; i < ml.n_tensors; ++i) {
  6964. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  6965. const std::string name = ggml_get_name(meta);
  6966. // TODO: avoid hardcoded tensor names - use the TN_* constants
  6967. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  6968. ++qs.n_attention_wv;
  6969. }
  6970. else if (name.find("ffn_down.weight") != std::string::npos) {
  6971. ++qs.n_feed_forward_w2;
  6972. }
  6973. }
  6974. if (qs.n_attention_wv != qs.n_feed_forward_w2 || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  6975. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  6976. __func__, qs.n_attention_wv, qs.n_feed_forward_w2, model.hparams.n_layer);
  6977. }
  6978. size_t total_size_org = 0;
  6979. size_t total_size_new = 0;
  6980. std::vector<int64_t> hist_all(1 << 4, 0);
  6981. std::vector<std::thread> workers;
  6982. workers.reserve(nthread);
  6983. std::mutex mutex;
  6984. int idx = 0;
  6985. std::vector<no_init<uint8_t>> read_data;
  6986. std::vector<no_init<uint8_t>> work;
  6987. std::vector<no_init<float>> f32_conv_buf;
  6988. // populate the original tensors so we get an initial meta data
  6989. for (int i = 0; i < ml.n_tensors; ++i) {
  6990. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  6991. gguf_add_tensor(ctx_out, meta);
  6992. }
  6993. std::ofstream fout(fname_out, std::ios::binary);
  6994. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  6995. const size_t meta_size = gguf_get_meta_size(ctx_out);
  6996. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  6997. // placeholder for the meta data
  6998. ::zeros(fout, meta_size);
  6999. for (int i = 0; i < ml.n_tensors; ++i) {
  7000. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7001. const std::string name = ggml_get_name(tensor);
  7002. if (!ml.use_mmap) {
  7003. if (read_data.size() < ggml_nbytes(tensor)) {
  7004. read_data.resize(ggml_nbytes(tensor));
  7005. }
  7006. tensor->data = read_data.data();
  7007. }
  7008. ml.load_data_for(tensor);
  7009. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7010. ++idx, ml.n_tensors,
  7011. ggml_get_name(tensor),
  7012. llama_format_tensor_shape(tensor).c_str(),
  7013. ggml_type_name(tensor->type));
  7014. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7015. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7016. // quantize only 2D tensors
  7017. quantize &= (ggml_n_dims(tensor) == 2);
  7018. quantize &= params->quantize_output_tensor || name != "output.weight";
  7019. quantize &= !params->only_copy;
  7020. // do not quantize expert gating tensors
  7021. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7022. enum ggml_type new_type;
  7023. void * new_data;
  7024. size_t new_size;
  7025. if (quantize) {
  7026. new_type = quantized_type;
  7027. if (!params->pure) {
  7028. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7029. }
  7030. // If we've decided to quantize to the same type the tensor is already
  7031. // in then there's nothing to do.
  7032. quantize = tensor->type != new_type;
  7033. }
  7034. if (!quantize) {
  7035. new_type = tensor->type;
  7036. new_data = tensor->data;
  7037. new_size = ggml_nbytes(tensor);
  7038. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7039. } else {
  7040. const size_t nelements = ggml_nelements(tensor);
  7041. float * f32_data;
  7042. if (tensor->type == GGML_TYPE_F32) {
  7043. f32_data = (float *) tensor->data;
  7044. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  7045. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  7046. } else {
  7047. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  7048. f32_data = (float *) f32_conv_buf.data();
  7049. }
  7050. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  7051. fflush(stdout);
  7052. if (work.size() < nelements * 4) {
  7053. work.resize(nelements * 4); // upper bound on size
  7054. }
  7055. new_data = work.data();
  7056. std::array<int64_t, 1 << 4> hist_cur = {};
  7057. static const int chunk_size = 32 * 512;
  7058. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  7059. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  7060. if (nthread_use < 2) {
  7061. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  7062. } else {
  7063. size_t counter = 0;
  7064. new_size = 0;
  7065. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  7066. std::array<int64_t, 1 << 4> local_hist = {};
  7067. size_t local_size = 0;
  7068. while (true) {
  7069. std::unique_lock<std::mutex> lock(mutex);
  7070. size_t first = counter; counter += chunk_size;
  7071. if (first >= nelements) {
  7072. if (local_size > 0) {
  7073. for (int j=0; j<int(local_hist.size()); ++j) {
  7074. hist_cur[j] += local_hist[j];
  7075. }
  7076. new_size += local_size;
  7077. }
  7078. break;
  7079. }
  7080. lock.unlock();
  7081. size_t last = std::min(nelements, first + chunk_size);
  7082. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  7083. }
  7084. };
  7085. for (int it = 0; it < nthread_use - 1; ++it) {
  7086. workers.emplace_back(compute);
  7087. }
  7088. compute();
  7089. for (auto & w : workers) { w.join(); }
  7090. workers.clear();
  7091. }
  7092. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  7093. int64_t tot_count = 0;
  7094. for (size_t i = 0; i < hist_cur.size(); i++) {
  7095. hist_all[i] += hist_cur[i];
  7096. tot_count += hist_cur[i];
  7097. }
  7098. if (tot_count > 0) {
  7099. for (size_t i = 0; i < hist_cur.size(); i++) {
  7100. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  7101. }
  7102. }
  7103. LLAMA_LOG_INFO("\n");
  7104. }
  7105. total_size_org += ggml_nbytes(tensor);
  7106. total_size_new += new_size;
  7107. // update the gguf meta data as we go
  7108. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  7109. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  7110. // write tensor data + padding
  7111. fout.write((const char *) new_data, new_size);
  7112. zeros(fout, GGML_PAD(new_size, align) - new_size);
  7113. }
  7114. // go back to beginning of file and write the updated meta data
  7115. {
  7116. fout.seekp(0);
  7117. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  7118. gguf_get_meta_data(ctx_out, data.data());
  7119. fout.write((const char *) data.data(), data.size());
  7120. }
  7121. fout.close();
  7122. gguf_free(ctx_out);
  7123. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  7124. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  7125. // print histogram for all tensors
  7126. {
  7127. int64_t sum_all = 0;
  7128. for (size_t i = 0; i < hist_all.size(); i++) {
  7129. sum_all += hist_all[i];
  7130. }
  7131. if (sum_all > 0) {
  7132. LLAMA_LOG_INFO("%s: hist: ", __func__);
  7133. for (size_t i = 0; i < hist_all.size(); i++) {
  7134. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  7135. }
  7136. LLAMA_LOG_INFO("\n");
  7137. }
  7138. }
  7139. if (qs.n_fallback > 0) {
  7140. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  7141. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  7142. }
  7143. }
  7144. static int llama_apply_lora_from_file_internal(
  7145. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  7146. ) {
  7147. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  7148. const int64_t t_start_lora_us = ggml_time_us();
  7149. llama_file fin(path_lora, "rb");
  7150. // verify magic and version
  7151. {
  7152. uint32_t magic = fin.read_u32();
  7153. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  7154. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  7155. return 1;
  7156. }
  7157. uint32_t format_version = fin.read_u32();
  7158. if (format_version != 1) {
  7159. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  7160. return 1;
  7161. }
  7162. }
  7163. int32_t lora_r = fin.read_u32();
  7164. int32_t lora_alpha = fin.read_u32();
  7165. float scaling = scale * (float)lora_alpha / (float)lora_r;
  7166. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  7167. // create a name -> tensor map of the model to accelerate lookups
  7168. // find the max tensor size to estimate the required temporary buffer size
  7169. size_t max_tensor_size = 0;
  7170. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  7171. for (const auto & kv : model.tensors_by_name) {
  7172. model_tensors.insert(kv);
  7173. size_t f32_size = ggml_nelements(kv.second) * sizeof(float);
  7174. max_tensor_size = std::max(max_tensor_size, f32_size);
  7175. }
  7176. // create a temporary ggml context to store the lora tensors
  7177. // TODO: use ggml-alloc
  7178. size_t lora_ctx_size = max_tensor_size * 3;
  7179. LLAMA_LOG_INFO("%s: allocating %.f MB for lora temporary buffer\n", __func__, lora_ctx_size / 1024.0 / 1024.0);
  7180. std::vector<uint8_t> lora_buf(lora_ctx_size);
  7181. struct ggml_init_params params;
  7182. params.mem_size = lora_buf.size();
  7183. params.mem_buffer = lora_buf.data();
  7184. params.no_alloc = false;
  7185. using unique_context = std::unique_ptr<ggml_context, decltype(&ggml_free)>;
  7186. unique_context lora_ctx(nullptr, ggml_free);
  7187. lora_ctx.reset(ggml_init(params));
  7188. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  7189. // load base model
  7190. std::unique_ptr<llama_model_loader> ml;
  7191. unique_context base_ctx(nullptr, ggml_free);
  7192. std::vector<uint8_t> base_buf;
  7193. if (path_base_model) {
  7194. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  7195. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ NULL));
  7196. size_t ctx_size;
  7197. size_t mmapped_size;
  7198. ml->calc_sizes(ctx_size, mmapped_size);
  7199. base_buf.resize(ctx_size);
  7200. ggml_init_params base_params;
  7201. base_params.mem_size = base_buf.size();
  7202. base_params.mem_buffer = base_buf.data();
  7203. base_params.no_alloc = ml->use_mmap;
  7204. base_ctx.reset(ggml_init(base_params));
  7205. // maybe this should be in llama_model_loader
  7206. if (ml->use_mmap) {
  7207. ml->mapping.reset(new llama_mmap(&ml->file, /* prefetch */ 0, ggml_is_numa()));
  7208. }
  7209. }
  7210. // read tensors and apply
  7211. bool warned = false;
  7212. int n_tensors = 0;
  7213. std::vector<uint8_t> work_buffer;
  7214. while (true) {
  7215. if (fin.tell() == fin.size) {
  7216. // eof
  7217. break;
  7218. }
  7219. int32_t n_dims;
  7220. int32_t name_len;
  7221. int32_t ftype;
  7222. fin.read_raw(&n_dims, sizeof(n_dims));
  7223. fin.read_raw(&name_len, sizeof(name_len));
  7224. fin.read_raw(&ftype, sizeof(ftype));
  7225. if (n_dims != 1 && n_dims != 2) {
  7226. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  7227. return 1;
  7228. }
  7229. int32_t ne[2] = { 1, 1 };
  7230. for (int i = 0; i < n_dims; ++i) {
  7231. fin.read_raw(&ne[i], sizeof(ne[i]));
  7232. }
  7233. std::string name;
  7234. {
  7235. GGML_ASSERT(name_len <= 1024);
  7236. char buf[1024];
  7237. fin.read_raw(buf, name_len);
  7238. name = std::string(buf, name_len);
  7239. }
  7240. // check for lora suffix and get the type of tensor
  7241. const std::string lora_suffix = ".lora";
  7242. size_t pos = name.rfind(lora_suffix);
  7243. if (pos == std::string::npos) {
  7244. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  7245. return 1;
  7246. }
  7247. std::string lora_type = name.substr(pos + lora_suffix.length());
  7248. std::string base_name = name;
  7249. base_name.erase(pos);
  7250. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(), base_name.c_str(), lora_type.c_str());
  7251. if (model_tensors.find(base_name) == model_tensors.end()) {
  7252. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  7253. return 1;
  7254. }
  7255. // create ggml tensor
  7256. ggml_type wtype;
  7257. switch (ftype) {
  7258. case 0: wtype = GGML_TYPE_F32; break;
  7259. case 1: wtype = GGML_TYPE_F16; break;
  7260. default:
  7261. {
  7262. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  7263. __func__, ftype);
  7264. return false;
  7265. }
  7266. }
  7267. ggml_tensor * lora_tensor = ggml_new_tensor_2d(lora_ctx.get(), wtype, ne[0], ne[1]);
  7268. ggml_set_name(lora_tensor, name.c_str());
  7269. // load tensor data
  7270. size_t offset = fin.tell();
  7271. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  7272. offset = (offset + 31) & -32;
  7273. fin.seek(offset, SEEK_SET);
  7274. fin.read_raw(lora_tensor->data, tensor_data_size);
  7275. lora_tensors[name] = lora_tensor;
  7276. // check if we have both A and B tensors and apply
  7277. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  7278. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  7279. ggml_tensor * dest_t = model_tensors[base_name];
  7280. offload_func_t offload_func = ggml_offload_nop;
  7281. offload_func_t offload_func_force_inplace = ggml_offload_nop;
  7282. #ifdef GGML_USE_CUBLAS
  7283. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  7284. if (dest_t->type != GGML_TYPE_F16) {
  7285. throw std::runtime_error(format(
  7286. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models. dest_t->type: %d", __func__, dest_t->type));
  7287. }
  7288. offload_func = ggml_cuda_assign_buffers;
  7289. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  7290. }
  7291. #endif // GGML_USE_CUBLAS
  7292. ggml_tensor * base_t;
  7293. if (ml) {
  7294. struct gguf_context * ctx_gguf = ml->ctx_gguf;
  7295. // load from base model
  7296. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  7297. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  7298. return 1;
  7299. }
  7300. base_t = ml->create_tensor(base_ctx.get(), base_name, { dest_t->ne[0], dest_t->ne[1] }, GGML_BACKEND_CPU);
  7301. ml->load_data_for(base_t);
  7302. } else {
  7303. base_t = dest_t;
  7304. }
  7305. if (ggml_is_quantized(base_t->type)) {
  7306. if (!warned) {
  7307. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  7308. "use a f16 or f32 base model with --lora-base\n", __func__);
  7309. warned = true;
  7310. }
  7311. }
  7312. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  7313. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  7314. ggml_set_name(loraA, "loraA");
  7315. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  7316. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  7317. ggml_set_name(loraB, "loraB");
  7318. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  7319. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  7320. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  7321. return 1;
  7322. }
  7323. // w = w + BA*s
  7324. ggml_tensor * BA = ggml_mul_mat(lora_ctx.get(), loraA, loraB);
  7325. offload_func(BA);
  7326. ggml_set_name(BA, "BA");
  7327. if (scaling != 1.0f) {
  7328. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx.get(), scaling);
  7329. ggml_set_name(scale_tensor, "scale_tensor");
  7330. BA = ggml_scale_inplace(lora_ctx.get(), BA, scale_tensor);
  7331. offload_func(BA);
  7332. ggml_set_name(BA, "BA_scaled");
  7333. }
  7334. ggml_tensor * r;
  7335. if (base_t == dest_t) {
  7336. r = ggml_add_inplace(lora_ctx.get(), dest_t, BA);
  7337. offload_func_force_inplace(r);
  7338. ggml_set_name(r, "r_add_inplace");
  7339. }
  7340. else {
  7341. r = ggml_add(lora_ctx.get(), base_t, BA);
  7342. offload_func(r);
  7343. ggml_set_name(r, "r_add");
  7344. r = ggml_cpy(lora_ctx.get(), r, dest_t);
  7345. offload_func(r);
  7346. ggml_set_name(r, "r_cpy");
  7347. }
  7348. struct ggml_cgraph * gf = ggml_new_graph(lora_ctx.get());
  7349. ggml_build_forward_expand(gf, r);
  7350. ggml_graph_compute_helper(work_buffer, gf, n_threads);
  7351. // the tensors in the adapter must be sorted such that loraA and loraB of the same tensor are next to each other
  7352. GGML_ASSERT(lora_tensors.size() == 2);
  7353. // we won't need these tensors again, reset the context to save memory
  7354. lora_ctx.reset(ggml_init(params));
  7355. lora_tensors.clear();
  7356. n_tensors++;
  7357. if (n_tensors % 4 == 0) {
  7358. LLAMA_LOG_INFO(".");
  7359. }
  7360. }
  7361. }
  7362. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  7363. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  7364. return 0;
  7365. }
  7366. //
  7367. // interface implementation
  7368. //
  7369. struct llama_model_params llama_model_default_params() {
  7370. struct llama_model_params result = {
  7371. /*.n_gpu_layers =*/ 0,
  7372. /*.main_gpu =*/ 0,
  7373. /*.tensor_split =*/ nullptr,
  7374. /*.progress_callback =*/ nullptr,
  7375. /*.progress_callback_user_data =*/ nullptr,
  7376. /*.kv_overrides =*/ nullptr,
  7377. /*.vocab_only =*/ false,
  7378. /*.use_mmap =*/ true,
  7379. /*.use_mlock =*/ false,
  7380. };
  7381. #ifdef GGML_USE_METAL
  7382. result.n_gpu_layers = 1;
  7383. #endif
  7384. return result;
  7385. }
  7386. struct llama_context_params llama_context_default_params() {
  7387. struct llama_context_params result = {
  7388. /*.seed =*/ LLAMA_DEFAULT_SEED,
  7389. /*.n_ctx =*/ 512,
  7390. /*.n_batch =*/ 512,
  7391. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  7392. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  7393. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  7394. /*.rope_freq_base =*/ 0.0f,
  7395. /*.rope_freq_scale =*/ 0.0f,
  7396. /*.yarn_ext_factor =*/ -1.0f,
  7397. /*.yarn_attn_factor =*/ 1.0f,
  7398. /*.yarn_beta_fast =*/ 32.0f,
  7399. /*.yarn_beta_slow =*/ 1.0f,
  7400. /*.yarn_orig_ctx =*/ 0,
  7401. /*.type_k =*/ GGML_TYPE_F16,
  7402. /*.type_v =*/ GGML_TYPE_F16,
  7403. /*.mul_mat_q =*/ true,
  7404. /*.logits_all =*/ false,
  7405. /*.embedding =*/ false,
  7406. /*.offload_kqv =*/ true,
  7407. };
  7408. return result;
  7409. }
  7410. struct llama_model_quantize_params llama_model_quantize_default_params() {
  7411. struct llama_model_quantize_params result = {
  7412. /*.nthread =*/ 0,
  7413. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  7414. /*.allow_requantize =*/ false,
  7415. /*.quantize_output_tensor =*/ true,
  7416. /*.only_copy =*/ false,
  7417. /*.pure =*/ false,
  7418. };
  7419. return result;
  7420. }
  7421. int llama_max_devices(void) {
  7422. return LLAMA_MAX_DEVICES;
  7423. }
  7424. bool llama_mmap_supported(void) {
  7425. return llama_mmap::SUPPORTED;
  7426. }
  7427. bool llama_mlock_supported(void) {
  7428. return llama_mlock::SUPPORTED;
  7429. }
  7430. void llama_backend_init(bool numa) {
  7431. ggml_time_init();
  7432. // needed to initialize f16 tables
  7433. {
  7434. struct ggml_init_params params = { 0, NULL, false };
  7435. struct ggml_context * ctx = ggml_init(params);
  7436. ggml_free(ctx);
  7437. }
  7438. if (numa) {
  7439. ggml_numa_init();
  7440. }
  7441. #ifdef GGML_USE_MPI
  7442. ggml_mpi_backend_init();
  7443. #endif
  7444. }
  7445. void llama_backend_free(void) {
  7446. #ifdef GGML_USE_MPI
  7447. ggml_mpi_backend_free();
  7448. #endif
  7449. }
  7450. int64_t llama_time_us(void) {
  7451. return ggml_time_us();
  7452. }
  7453. struct llama_model * llama_load_model_from_file(
  7454. const char * path_model,
  7455. struct llama_model_params params) {
  7456. ggml_time_init();
  7457. llama_model * model = new llama_model;
  7458. unsigned cur_percentage = 0;
  7459. if (params.progress_callback == NULL) {
  7460. params.progress_callback_user_data = &cur_percentage;
  7461. params.progress_callback = [](float progress, void * ctx) {
  7462. unsigned * cur_percentage_p = (unsigned *) ctx;
  7463. unsigned percentage = (unsigned) (100 * progress);
  7464. while (percentage > *cur_percentage_p) {
  7465. *cur_percentage_p = percentage;
  7466. LLAMA_LOG_INFO(".");
  7467. if (percentage >= 100) {
  7468. LLAMA_LOG_INFO("\n");
  7469. }
  7470. }
  7471. };
  7472. }
  7473. if (!llama_model_load(path_model, *model, params)) {
  7474. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  7475. delete model;
  7476. return nullptr;
  7477. }
  7478. return model;
  7479. }
  7480. void llama_free_model(struct llama_model * model) {
  7481. delete model;
  7482. }
  7483. struct llama_context * llama_new_context_with_model(
  7484. struct llama_model * model,
  7485. struct llama_context_params params) {
  7486. if (!model) {
  7487. return nullptr;
  7488. }
  7489. llama_context * ctx = new llama_context(*model);
  7490. const auto & hparams = model->hparams;
  7491. auto & cparams = ctx->cparams;
  7492. cparams.n_batch = params.n_batch;
  7493. cparams.n_threads = params.n_threads;
  7494. cparams.n_threads_batch = params.n_threads_batch;
  7495. cparams.yarn_ext_factor = params.yarn_ext_factor;
  7496. cparams.yarn_attn_factor = params.yarn_attn_factor;
  7497. cparams.yarn_beta_fast = params.yarn_beta_fast;
  7498. cparams.yarn_beta_slow = params.yarn_beta_slow;
  7499. cparams.mul_mat_q = params.mul_mat_q;
  7500. cparams.offload_kqv = params.offload_kqv;
  7501. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  7502. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  7503. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  7504. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  7505. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  7506. hparams.n_ctx_train;
  7507. auto rope_scaling_type = params.rope_scaling_type;
  7508. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  7509. rope_scaling_type = hparams.rope_scaling_type_train;
  7510. }
  7511. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  7512. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  7513. }
  7514. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  7515. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  7516. }
  7517. if (params.seed == LLAMA_DEFAULT_SEED) {
  7518. params.seed = time(NULL);
  7519. }
  7520. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  7521. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  7522. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  7523. ctx->rng = std::mt19937(params.seed);
  7524. ctx->logits_all = params.logits_all;
  7525. const ggml_type type_k = params.type_k;
  7526. const ggml_type type_v = params.type_v;
  7527. GGML_ASSERT(hparams.n_embd_head() % ggml_blck_size(type_k) == 0);
  7528. GGML_ASSERT(hparams.n_embd_head() % ggml_blck_size(type_v) == 0);
  7529. // reserve memory for context buffers
  7530. if (!hparams.vocab_only) {
  7531. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, type_k, type_v, cparams.n_ctx, model->n_gpu_layers, cparams.offload_kqv)) {
  7532. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  7533. llama_free(ctx);
  7534. return nullptr;
  7535. }
  7536. {
  7537. size_t memory_size_k = 0;
  7538. size_t memory_size_v = 0;
  7539. for (auto & k : ctx->kv_self.k_l) {
  7540. memory_size_k += ggml_nbytes(k);
  7541. }
  7542. for (auto & v : ctx->kv_self.v_l) {
  7543. memory_size_v += ggml_nbytes(v);
  7544. }
  7545. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  7546. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  7547. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  7548. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  7549. }
  7550. // resized during inference
  7551. if (params.logits_all) {
  7552. ctx->logits.reserve(cparams.n_ctx*hparams.n_vocab);
  7553. } else {
  7554. ctx->logits.reserve(hparams.n_vocab);
  7555. }
  7556. if (params.embedding){
  7557. ctx->embedding.resize(hparams.n_embd);
  7558. }
  7559. {
  7560. static const size_t tensor_alignment = 32;
  7561. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  7562. ctx->buf_compute.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  7563. // create measure allocator
  7564. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  7565. // build worst-case graph
  7566. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  7567. int n_past = cparams.n_ctx - n_tokens;
  7568. llama_token token = llama_token_bos(&ctx->model); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  7569. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  7570. #ifdef GGML_USE_METAL
  7571. if (model->n_gpu_layers > 0) {
  7572. ctx->ctx_metal = ggml_metal_init(1);
  7573. if (!ctx->ctx_metal) {
  7574. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  7575. llama_free(ctx);
  7576. return NULL;
  7577. }
  7578. //ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  7579. //ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  7580. }
  7581. #endif
  7582. // measure memory requirements for the graph
  7583. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  7584. LLAMA_LOG_INFO("%s: compute buffer total size = %.2f MiB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  7585. // recreate allocator with exact memory requirements
  7586. ggml_allocr_free(ctx->alloc);
  7587. ctx->buf_alloc.resize(alloc_size);
  7588. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  7589. #ifdef GGML_USE_METAL
  7590. if (ctx->ctx_metal) {
  7591. //ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  7592. }
  7593. #endif
  7594. #ifdef GGML_USE_CUBLAS
  7595. ggml_cuda_set_scratch_size(alloc_size);
  7596. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MiB\n", __func__, alloc_size / 1024.0 / 1024.0);
  7597. // calculate total VRAM usage
  7598. auto add_tensor = [](const ggml_tensor * t, size_t & size) {
  7599. if (t->backend == GGML_BACKEND_GPU || t->backend == GGML_BACKEND_GPU_SPLIT) {
  7600. size += ggml_nbytes(t);
  7601. }
  7602. };
  7603. size_t model_vram_size = 0;
  7604. for (const auto & kv : model->tensors_by_name) {
  7605. add_tensor(kv.second, model_vram_size);
  7606. }
  7607. size_t kv_vram_size = 0;
  7608. for (auto & k : ctx->kv_self.k_l) {
  7609. add_tensor(k, kv_vram_size);
  7610. }
  7611. for (auto & v : ctx->kv_self.v_l) {
  7612. add_tensor(v, kv_vram_size);
  7613. }
  7614. size_t ctx_vram_size = alloc_size + kv_vram_size;
  7615. size_t total_vram_size = model_vram_size + ctx_vram_size;
  7616. LLAMA_LOG_INFO("%s: total VRAM used: %.2f MiB (model: %.2f MiB, context: %.2f MiB)\n", __func__,
  7617. total_vram_size / 1024.0 / 1024.0,
  7618. model_vram_size / 1024.0 / 1024.0,
  7619. ctx_vram_size / 1024.0 / 1024.0);
  7620. #endif
  7621. }
  7622. #ifdef GGML_USE_METAL
  7623. if (model->n_gpu_layers > 0) {
  7624. // this allocates all Metal resources and memory buffers
  7625. void * data_ptr = NULL;
  7626. size_t data_size = 0;
  7627. if (ctx->model.mapping) {
  7628. data_ptr = ctx->model.mapping->addr;
  7629. data_size = ctx->model.mapping->size;
  7630. } else {
  7631. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  7632. data_size = ggml_get_mem_size (ctx->model.ctx);
  7633. }
  7634. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  7635. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MiB\n", __func__, max_size/1024.0/1024.0);
  7636. #define LLAMA_METAL_CHECK_BUF(result) \
  7637. if (!(result)) { \
  7638. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  7639. llama_free(ctx); \
  7640. return NULL; \
  7641. }
  7642. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  7643. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  7644. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  7645. #undef LLAMA_METAL_CHECK_BUF
  7646. }
  7647. #endif
  7648. }
  7649. #ifdef GGML_USE_MPI
  7650. ctx->ctx_mpi = ggml_mpi_init();
  7651. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  7652. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  7653. // TODO: needs fix after #3228
  7654. GGML_ASSERT(false && "not implemented");
  7655. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  7656. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  7657. llama_backend_free();
  7658. exit(1);
  7659. }
  7660. #endif
  7661. return ctx;
  7662. }
  7663. void llama_free(struct llama_context * ctx) {
  7664. delete ctx;
  7665. }
  7666. const llama_model * llama_get_model(const struct llama_context * ctx) {
  7667. return &ctx->model;
  7668. }
  7669. int llama_n_ctx(const struct llama_context * ctx) {
  7670. return ctx->cparams.n_ctx;
  7671. }
  7672. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  7673. return model->vocab.type;
  7674. }
  7675. int llama_n_vocab(const struct llama_model * model) {
  7676. return model->vocab.id_to_token.size();
  7677. }
  7678. int llama_n_ctx_train(const struct llama_model * model) {
  7679. return model->hparams.n_ctx_train;
  7680. }
  7681. int llama_n_embd(const struct llama_model * model) {
  7682. return model->hparams.n_embd;
  7683. }
  7684. float llama_rope_freq_scale_train(const struct llama_model * model) {
  7685. return model->hparams.rope_freq_scale_train;
  7686. }
  7687. int llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  7688. const auto & it = model->gguf_kv.find(key);
  7689. if (it == model->gguf_kv.end()) {
  7690. if (buf_size > 0) {
  7691. buf[0] = '\0';
  7692. }
  7693. return -1;
  7694. }
  7695. return snprintf(buf, buf_size, "%s", it->second.c_str());
  7696. }
  7697. int llama_model_meta_count(const struct llama_model * model) {
  7698. return (int)model->gguf_kv.size();
  7699. }
  7700. int llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  7701. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  7702. if (buf_size > 0) {
  7703. buf[0] = '\0';
  7704. }
  7705. return -1;
  7706. }
  7707. auto it = model->gguf_kv.begin();
  7708. std::advance(it, i);
  7709. return snprintf(buf, buf_size, "%s", it->first.c_str());
  7710. }
  7711. int llama_model_meta_val_str_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  7712. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  7713. if (buf_size > 0) {
  7714. buf[0] = '\0';
  7715. }
  7716. return -1;
  7717. }
  7718. auto it = model->gguf_kv.begin();
  7719. std::advance(it, i);
  7720. return snprintf(buf, buf_size, "%s", it->second.c_str());
  7721. }
  7722. int llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  7723. return snprintf(buf, buf_size, "%s %s %s",
  7724. llama_model_arch_name(model->arch).c_str(),
  7725. llama_model_type_name(model->type),
  7726. llama_model_ftype_name(model->ftype).c_str());
  7727. }
  7728. uint64_t llama_model_size(const struct llama_model * model) {
  7729. uint64_t size = 0;
  7730. for (const auto & it : model->tensors_by_name) {
  7731. size += ggml_nbytes(it.second);
  7732. }
  7733. return size;
  7734. }
  7735. uint64_t llama_model_n_params(const struct llama_model * model) {
  7736. uint64_t nparams = 0;
  7737. for (const auto & it : model->tensors_by_name) {
  7738. nparams += ggml_nelements(it.second);
  7739. }
  7740. return nparams;
  7741. }
  7742. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  7743. return ggml_get_tensor(model->ctx, name);
  7744. }
  7745. int llama_model_quantize(
  7746. const char * fname_inp,
  7747. const char * fname_out,
  7748. const llama_model_quantize_params * params) {
  7749. try {
  7750. llama_model_quantize_internal(fname_inp, fname_out, params);
  7751. return 0;
  7752. } catch (const std::exception & err) {
  7753. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  7754. return 1;
  7755. }
  7756. }
  7757. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int n_threads) {
  7758. try {
  7759. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  7760. } catch (const std::exception & err) {
  7761. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  7762. return 1;
  7763. }
  7764. }
  7765. 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) {
  7766. try {
  7767. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  7768. } catch (const std::exception & err) {
  7769. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  7770. return 1;
  7771. }
  7772. }
  7773. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  7774. struct llama_kv_cache_view result = {
  7775. /*.n_cells = */ 0,
  7776. /*.n_max_seq = */ n_max_seq,
  7777. /*.token_count = */ 0,
  7778. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  7779. /*.max_contiguous = */ 0,
  7780. /*.max_contiguous_idx = */ -1,
  7781. /*.cells = */ nullptr,
  7782. /*.cells_sequences = */ nullptr,
  7783. };
  7784. return result;
  7785. }
  7786. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  7787. if (view->cells != nullptr) {
  7788. free(view->cells);
  7789. view->cells = nullptr;
  7790. }
  7791. if (view->cells_sequences != nullptr) {
  7792. free(view->cells_sequences);
  7793. view->cells_sequences = nullptr;
  7794. }
  7795. }
  7796. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  7797. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  7798. view->n_cells = int32_t(ctx->kv_self.size);
  7799. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  7800. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  7801. view->cells = (struct llama_kv_cache_view_cell *)p;
  7802. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  7803. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  7804. view->cells_sequences = (llama_seq_id *)p;
  7805. }
  7806. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  7807. llama_kv_cache_view_cell * c_curr = view->cells;
  7808. llama_seq_id * cs_curr = view->cells_sequences;
  7809. int32_t used_cells = 0;
  7810. int32_t token_count = 0;
  7811. int32_t curr_contig_idx = -1;
  7812. uint32_t max_contig = 0;
  7813. int32_t max_contig_idx = -1;
  7814. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  7815. const size_t curr_size = kv_cells[i].seq_id.size();
  7816. token_count += curr_size;
  7817. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  7818. if (curr_size > 0) {
  7819. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  7820. max_contig = i - curr_contig_idx;
  7821. max_contig_idx = curr_contig_idx;
  7822. }
  7823. curr_contig_idx = -1;
  7824. } else if (curr_contig_idx < 0) {
  7825. curr_contig_idx = i;
  7826. }
  7827. int seq_idx = 0;
  7828. for (const llama_seq_id it : kv_cells[i].seq_id) {
  7829. if (seq_idx >= view->n_max_seq) {
  7830. break;
  7831. }
  7832. cs_curr[seq_idx] = it;
  7833. seq_idx++;
  7834. }
  7835. if (seq_idx != 0) {
  7836. used_cells++;
  7837. }
  7838. for (; seq_idx < view->n_max_seq; seq_idx++) {
  7839. cs_curr[seq_idx] = -1;
  7840. }
  7841. }
  7842. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  7843. max_contig_idx = curr_contig_idx;
  7844. max_contig = kv_cells.size() - curr_contig_idx;
  7845. }
  7846. view->max_contiguous = max_contig;
  7847. view->max_contiguous_idx = max_contig_idx;
  7848. view->token_count = token_count;
  7849. view->used_cells = used_cells;
  7850. if (uint32_t(used_cells) != ctx->kv_self.used) {
  7851. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  7852. __func__, ctx->kv_self.used, used_cells);
  7853. }
  7854. }
  7855. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  7856. int result = 0;
  7857. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  7858. result += ctx->kv_self.cells[i].seq_id.size();
  7859. }
  7860. return result;
  7861. }
  7862. int llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  7863. return ctx->kv_self.used;
  7864. }
  7865. void llama_kv_cache_clear(struct llama_context * ctx) {
  7866. llama_kv_cache_clear(ctx->kv_self);
  7867. }
  7868. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  7869. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  7870. }
  7871. 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) {
  7872. if (seq_id_src == seq_id_dst) {
  7873. return;
  7874. }
  7875. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  7876. }
  7877. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  7878. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  7879. }
  7880. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  7881. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  7882. }
  7883. // Returns the *maximum* size of the state
  7884. size_t llama_get_state_size(const struct llama_context * ctx) {
  7885. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  7886. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  7887. const size_t s_rng_size = sizeof(size_t);
  7888. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  7889. const size_t s_logits_capacity = sizeof(size_t);
  7890. const size_t s_logits_size = sizeof(size_t);
  7891. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  7892. const size_t s_embedding_size = sizeof(size_t);
  7893. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  7894. const size_t s_kv_size = sizeof(size_t);
  7895. const size_t s_kv_ntok = sizeof(int);
  7896. const size_t s_kv = ctx->kv_self.buf.size;
  7897. const size_t s_total = (
  7898. + s_rng_size
  7899. + s_rng
  7900. + s_logits_capacity
  7901. + s_logits_size
  7902. + s_logits
  7903. + s_embedding_size
  7904. + s_embedding
  7905. + s_kv_size
  7906. + s_kv_ntok
  7907. + s_kv
  7908. );
  7909. return s_total;
  7910. }
  7911. // llama_context_data
  7912. struct llama_data_context {
  7913. virtual void write(const void * src, size_t size) = 0;
  7914. virtual size_t get_size_written() = 0;
  7915. virtual ~llama_data_context() = default;
  7916. };
  7917. struct llama_data_buffer_context : llama_data_context {
  7918. uint8_t * ptr;
  7919. size_t size_written = 0;
  7920. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  7921. void write(const void * src, size_t size) override {
  7922. memcpy(ptr, src, size);
  7923. ptr += size;
  7924. size_written += size;
  7925. }
  7926. size_t get_size_written() override {
  7927. return size_written;
  7928. }
  7929. };
  7930. struct llama_data_file_context : llama_data_context {
  7931. llama_file * file;
  7932. size_t size_written = 0;
  7933. llama_data_file_context(llama_file * f) : file(f) {}
  7934. void write(const void * src, size_t size) override {
  7935. file->write_raw(src, size);
  7936. size_written += size;
  7937. }
  7938. size_t get_size_written() override {
  7939. return size_written;
  7940. }
  7941. };
  7942. /** copy state data into either a buffer or file depending on the passed in context
  7943. *
  7944. * file context:
  7945. * llama_file file("/path", "wb");
  7946. * llama_data_file_context data_ctx(&file);
  7947. * llama_copy_state_data(ctx, &data_ctx);
  7948. *
  7949. * buffer context:
  7950. * std::vector<uint8_t> buf(max_size, 0);
  7951. * llama_data_buffer_context data_ctx(&buf.data());
  7952. * llama_copy_state_data(ctx, &data_ctx);
  7953. *
  7954. */
  7955. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  7956. // copy rng
  7957. {
  7958. std::stringstream rng_ss;
  7959. rng_ss << ctx->rng;
  7960. const size_t rng_size = rng_ss.str().size();
  7961. char rng_buf[LLAMA_MAX_RNG_STATE];
  7962. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  7963. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  7964. data_ctx->write(&rng_size, sizeof(rng_size));
  7965. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  7966. }
  7967. // copy logits
  7968. {
  7969. const size_t logits_cap = ctx->logits.capacity();
  7970. const size_t logits_size = ctx->logits.size();
  7971. data_ctx->write(&logits_cap, sizeof(logits_cap));
  7972. data_ctx->write(&logits_size, sizeof(logits_size));
  7973. if (logits_size) {
  7974. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  7975. }
  7976. // If there is a gap between the size and the capacity, write padding
  7977. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  7978. if (padding_size > 0) {
  7979. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  7980. data_ctx->write(padding.data(), padding_size);
  7981. }
  7982. }
  7983. // copy embeddings
  7984. {
  7985. const size_t embedding_size = ctx->embedding.size();
  7986. data_ctx->write(&embedding_size, sizeof(embedding_size));
  7987. if (embedding_size) {
  7988. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  7989. }
  7990. }
  7991. // copy kv cache
  7992. {
  7993. const auto & kv_self = ctx->kv_self;
  7994. const auto & hparams = ctx->model.hparams;
  7995. const auto & cparams = ctx->cparams;
  7996. const auto n_layer = hparams.n_layer;
  7997. const auto n_embd = hparams.n_embd_gqa();
  7998. const auto n_ctx = cparams.n_ctx;
  7999. const size_t kv_buf_size = kv_self.buf.size;
  8000. const uint32_t kv_head = kv_self.head;
  8001. const uint32_t kv_size = kv_self.size;
  8002. const uint32_t kv_used = kv_self.used;
  8003. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  8004. data_ctx->write(&kv_head, sizeof(kv_head));
  8005. data_ctx->write(&kv_size, sizeof(kv_size));
  8006. data_ctx->write(&kv_used, sizeof(kv_used));
  8007. if (kv_buf_size) {
  8008. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8009. ggml_context * cpy_ctx = ggml_init({ 6*n_layer*ggml_tensor_overhead() + ggml_graph_overhead(), NULL, /* no_alloc */ true });
  8010. ggml_cgraph * gf = ggml_new_graph(cpy_ctx);
  8011. std::vector<std::vector<uint8_t>> kout2d_data(n_layer);
  8012. std::vector<std::vector<uint8_t>> vout2d_data(n_layer);
  8013. for (int il = 0; il < (int) n_layer; ++il) {
  8014. ggml_tensor * kout2d = ggml_new_tensor_2d(cpy_ctx, kv_self.k_l[il]->type, n_embd, kv_head);
  8015. kout2d_data[il].resize(ggml_nbytes(kout2d));
  8016. kout2d->data = kout2d_data[il].data();
  8017. ggml_tensor * vout2d = ggml_new_tensor_2d(cpy_ctx, kv_self.v_l[il]->type, kv_head, n_embd);
  8018. vout2d_data[il].resize(ggml_nbytes(vout2d));
  8019. vout2d->data = vout2d_data[il].data();
  8020. ggml_tensor * k2d = ggml_view_2d(cpy_ctx, kv_self.k_l[il],
  8021. n_embd, kv_head,
  8022. elt_size*n_embd, 0);
  8023. ggml_tensor * v2d = ggml_view_2d(cpy_ctx, kv_self.v_l[il],
  8024. kv_head, n_embd,
  8025. elt_size*n_ctx, 0);
  8026. ggml_build_forward_expand(gf, ggml_cpy(cpy_ctx, k2d, kout2d));
  8027. ggml_build_forward_expand(gf, ggml_cpy(cpy_ctx, v2d, vout2d));
  8028. }
  8029. ggml_graph_compute_helper(ctx->work_buffer, gf, /*n_threads*/ 1);
  8030. ggml_free(cpy_ctx);
  8031. // our data is now in the kout2d_data and vout2d_data buffers
  8032. // write them to file
  8033. for (uint32_t il = 0; il < n_layer; ++il) {
  8034. data_ctx->write(kout2d_data[il].data(), kout2d_data[il].size());
  8035. data_ctx->write(vout2d_data[il].data(), vout2d_data[il].size());
  8036. }
  8037. }
  8038. for (uint32_t i = 0; i < kv_size; ++i) {
  8039. const auto & cell = kv_self.cells[i];
  8040. const llama_pos pos = cell.pos;
  8041. const size_t seq_id_size = cell.seq_id.size();
  8042. data_ctx->write(&pos, sizeof(pos));
  8043. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  8044. for (auto seq_id : cell.seq_id) {
  8045. data_ctx->write(&seq_id, sizeof(seq_id));
  8046. }
  8047. }
  8048. }
  8049. }
  8050. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  8051. llama_data_buffer_context data_ctx(dst);
  8052. llama_copy_state_data_internal(ctx, &data_ctx);
  8053. return data_ctx.get_size_written();
  8054. }
  8055. // Sets the state reading from the specified source address
  8056. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  8057. uint8_t * inp = src;
  8058. // set rng
  8059. {
  8060. size_t rng_size;
  8061. char rng_buf[LLAMA_MAX_RNG_STATE];
  8062. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  8063. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  8064. std::stringstream rng_ss;
  8065. rng_ss.str(std::string(&rng_buf[0], rng_size));
  8066. rng_ss >> ctx->rng;
  8067. GGML_ASSERT(!rng_ss.fail());
  8068. }
  8069. // set logits
  8070. {
  8071. size_t logits_cap;
  8072. size_t logits_size;
  8073. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  8074. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  8075. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  8076. if (logits_size) {
  8077. ctx->logits.resize(logits_size);
  8078. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  8079. }
  8080. inp += logits_cap * sizeof(float);
  8081. }
  8082. // set embeddings
  8083. {
  8084. size_t embedding_size;
  8085. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  8086. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  8087. if (embedding_size) {
  8088. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  8089. inp += embedding_size * sizeof(float);
  8090. }
  8091. }
  8092. // set kv cache
  8093. {
  8094. const auto & kv_self = ctx->kv_self;
  8095. const auto & hparams = ctx->model.hparams;
  8096. const auto & cparams = ctx->cparams;
  8097. const int n_layer = hparams.n_layer;
  8098. const int n_embd = hparams.n_embd_gqa();
  8099. const int n_ctx = cparams.n_ctx;
  8100. size_t kv_buf_size;
  8101. uint32_t kv_head;
  8102. uint32_t kv_size;
  8103. uint32_t kv_used;
  8104. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  8105. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  8106. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  8107. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  8108. if (kv_buf_size) {
  8109. GGML_ASSERT(kv_self.buf.size == kv_buf_size);
  8110. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8111. ggml_context * cpy_ctx = ggml_init({ 6*n_layer*ggml_tensor_overhead() + ggml_graph_overhead(), NULL, /* no_alloc */ true });
  8112. ggml_cgraph * gf = ggml_new_graph(cpy_ctx);
  8113. for (int il = 0; il < n_layer; ++il) {
  8114. ggml_tensor * kin2d = ggml_new_tensor_2d(cpy_ctx, kv_self.k_l[il]->type, n_embd, kv_head);
  8115. kin2d->data = (void *) inp;
  8116. inp += ggml_nbytes(kin2d);
  8117. ggml_tensor * vin2d = ggml_new_tensor_2d(cpy_ctx, kv_self.v_l[il]->type, kv_head, n_embd);
  8118. vin2d->data = (void *) inp;
  8119. inp += ggml_nbytes(vin2d);
  8120. ggml_tensor * k2d = ggml_view_2d(cpy_ctx, kv_self.k_l[il],
  8121. n_embd, kv_head,
  8122. elt_size*n_embd, 0);
  8123. ggml_tensor * v2d = ggml_view_2d(cpy_ctx, kv_self.v_l[il],
  8124. kv_head, n_embd,
  8125. elt_size*n_ctx, 0);
  8126. ggml_build_forward_expand(gf, ggml_cpy(cpy_ctx, kin2d, k2d));
  8127. ggml_build_forward_expand(gf, ggml_cpy(cpy_ctx, vin2d, v2d));
  8128. }
  8129. ggml_graph_compute_helper(ctx->work_buffer, gf, /*n_threads*/ 1);
  8130. ggml_free(cpy_ctx);
  8131. }
  8132. ctx->kv_self.head = kv_head;
  8133. ctx->kv_self.size = kv_size;
  8134. ctx->kv_self.used = kv_used;
  8135. ctx->kv_self.cells.resize(kv_size);
  8136. for (uint32_t i = 0; i < kv_size; ++i) {
  8137. llama_pos pos;
  8138. size_t seq_id_size;
  8139. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  8140. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  8141. ctx->kv_self.cells[i].pos = pos;
  8142. llama_seq_id seq_id;
  8143. for (size_t j = 0; j < seq_id_size; ++j) {
  8144. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  8145. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  8146. }
  8147. }
  8148. }
  8149. const size_t nread = inp - src;
  8150. const size_t max_size = llama_get_state_size(ctx);
  8151. GGML_ASSERT(nread <= max_size);
  8152. return nread;
  8153. }
  8154. 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) {
  8155. llama_file file(path_session, "rb");
  8156. // sanity checks
  8157. {
  8158. const uint32_t magic = file.read_u32();
  8159. const uint32_t version = file.read_u32();
  8160. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  8161. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  8162. return false;
  8163. }
  8164. llama_hparams session_hparams;
  8165. file.read_raw(&session_hparams, sizeof(llama_hparams));
  8166. if (session_hparams != ctx->model.hparams) {
  8167. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  8168. return false;
  8169. }
  8170. }
  8171. // load the prompt
  8172. {
  8173. const uint32_t n_token_count = file.read_u32();
  8174. if (n_token_count > n_token_capacity) {
  8175. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  8176. return false;
  8177. }
  8178. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  8179. *n_token_count_out = n_token_count;
  8180. }
  8181. // restore the context state
  8182. {
  8183. const size_t n_state_size_cur = file.size - file.tell();
  8184. const size_t n_state_size_max = llama_get_state_size(ctx);
  8185. if (n_state_size_cur > n_state_size_max) {
  8186. 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);
  8187. return false;
  8188. }
  8189. std::vector<uint8_t> state_data(n_state_size_max);
  8190. file.read_raw(state_data.data(), n_state_size_cur);
  8191. llama_set_state_data(ctx, state_data.data());
  8192. }
  8193. return true;
  8194. }
  8195. 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) {
  8196. try {
  8197. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  8198. } catch (const std::exception & err) {
  8199. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  8200. return false;
  8201. }
  8202. }
  8203. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  8204. llama_file file(path_session, "wb");
  8205. file.write_u32(LLAMA_SESSION_MAGIC);
  8206. file.write_u32(LLAMA_SESSION_VERSION);
  8207. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  8208. // save the prompt
  8209. file.write_u32((uint32_t) n_token_count);
  8210. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  8211. // save the context state using stream saving
  8212. llama_data_file_context data_ctx(&file);
  8213. llama_copy_state_data_internal(ctx, &data_ctx);
  8214. return true;
  8215. }
  8216. int llama_eval(
  8217. struct llama_context * ctx,
  8218. llama_token * tokens,
  8219. int32_t n_tokens,
  8220. int n_past) {
  8221. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8222. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  8223. if (ret < 0) {
  8224. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8225. }
  8226. return ret;
  8227. }
  8228. int llama_eval_embd(
  8229. struct llama_context * ctx,
  8230. float * embd,
  8231. int32_t n_tokens,
  8232. int n_past) {
  8233. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8234. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  8235. const int ret = llama_decode_internal(*ctx, batch);
  8236. if (ret < 0) {
  8237. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8238. }
  8239. return ret;
  8240. }
  8241. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  8242. ctx->cparams.n_threads = n_threads;
  8243. ctx->cparams.n_threads_batch = n_threads_batch;
  8244. }
  8245. struct llama_batch llama_batch_get_one(
  8246. llama_token * tokens,
  8247. int32_t n_tokens,
  8248. llama_pos pos_0,
  8249. llama_seq_id seq_id) {
  8250. return {
  8251. /*n_tokens =*/ n_tokens,
  8252. /*tokens =*/ tokens,
  8253. /*embd =*/ nullptr,
  8254. /*pos =*/ nullptr,
  8255. /*n_seq_id =*/ nullptr,
  8256. /*seq_id =*/ nullptr,
  8257. /*logits =*/ nullptr,
  8258. /*all_pos_0 =*/ pos_0,
  8259. /*all_pos_1 =*/ 1,
  8260. /*all_seq_id =*/ seq_id,
  8261. };
  8262. }
  8263. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  8264. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  8265. if (embd) {
  8266. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  8267. } else {
  8268. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  8269. }
  8270. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  8271. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  8272. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  8273. for (int i = 0; i < n_tokens; ++i) {
  8274. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  8275. }
  8276. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  8277. return batch;
  8278. }
  8279. void llama_batch_free(struct llama_batch batch) {
  8280. if (batch.token) free(batch.token);
  8281. if (batch.embd) free(batch.embd);
  8282. if (batch.pos) free(batch.pos);
  8283. if (batch.n_seq_id) free(batch.n_seq_id);
  8284. if (batch.seq_id) {
  8285. for (int i = 0; i < batch.n_tokens; ++i) {
  8286. free(batch.seq_id[i]);
  8287. }
  8288. free(batch.seq_id);
  8289. }
  8290. if (batch.logits) free(batch.logits);
  8291. }
  8292. int llama_decode(
  8293. struct llama_context * ctx,
  8294. struct llama_batch batch) {
  8295. const int ret = llama_decode_internal(*ctx, batch);
  8296. if (ret < 0) {
  8297. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8298. }
  8299. return ret;
  8300. }
  8301. float * llama_get_logits(struct llama_context * ctx) {
  8302. return ctx->logits.data();
  8303. }
  8304. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  8305. assert(ctx->logits_valid.at(i));
  8306. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  8307. }
  8308. float * llama_get_embeddings(struct llama_context * ctx) {
  8309. return ctx->embedding.data();
  8310. }
  8311. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  8312. return model->vocab.id_to_token[token].text.c_str();
  8313. }
  8314. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  8315. return model->vocab.id_to_token[token].score;
  8316. }
  8317. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  8318. return model->vocab.id_to_token[token].type;
  8319. }
  8320. llama_token llama_token_bos(const struct llama_model * model) {
  8321. return model->vocab.special_bos_id;
  8322. }
  8323. llama_token llama_token_eos(const struct llama_model * model) {
  8324. return model->vocab.special_eos_id;
  8325. }
  8326. llama_token llama_token_nl(const struct llama_model * model) {
  8327. return model->vocab.linefeed_id;
  8328. }
  8329. int llama_add_bos_token(const struct llama_model * model) {
  8330. return model->vocab.special_add_bos;
  8331. }
  8332. int llama_add_eos_token(const struct llama_model * model) {
  8333. return model->vocab.special_add_eos;
  8334. }
  8335. llama_token llama_token_prefix(const struct llama_model * model) {
  8336. return model->vocab.special_prefix_id;
  8337. }
  8338. llama_token llama_token_middle(const struct llama_model * model) {
  8339. return model->vocab.special_middle_id;
  8340. }
  8341. llama_token llama_token_suffix(const struct llama_model * model) {
  8342. return model->vocab.special_suffix_id;
  8343. }
  8344. llama_token llama_token_eot(const struct llama_model * model) {
  8345. return model->vocab.special_eot_id;
  8346. }
  8347. int llama_tokenize(
  8348. const struct llama_model * model,
  8349. const char * text,
  8350. int text_len,
  8351. llama_token * tokens,
  8352. int n_max_tokens,
  8353. bool add_bos,
  8354. bool special) {
  8355. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  8356. if (n_max_tokens < (int) res.size()) {
  8357. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  8358. return -((int) res.size());
  8359. }
  8360. for (size_t i = 0; i < res.size(); i++) {
  8361. tokens[i] = res[i];
  8362. }
  8363. return res.size();
  8364. }
  8365. static std::string llama_decode_text(const std::string & text) {
  8366. std::string decoded_text;
  8367. auto unicode_sequences = codepoints_from_utf8(text);
  8368. for (auto& unicode_sequence : unicode_sequences) {
  8369. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  8370. }
  8371. return decoded_text;
  8372. }
  8373. // does not write null-terminator to buf
  8374. int llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int length) {
  8375. if (0 <= token && token < llama_n_vocab(model)) {
  8376. switch (llama_vocab_get_type(model->vocab)) {
  8377. case LLAMA_VOCAB_TYPE_SPM: {
  8378. if (llama_is_normal_token(model->vocab, token)) {
  8379. std::string result = model->vocab.id_to_token[token].text;
  8380. llama_unescape_whitespace(result);
  8381. if (length < (int) result.length()) {
  8382. return -result.length();
  8383. }
  8384. memcpy(buf, result.c_str(), result.length());
  8385. return result.length();
  8386. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  8387. if (length < 3) {
  8388. return -3;
  8389. }
  8390. memcpy(buf, "\xe2\x96\x85", 3);
  8391. return 3;
  8392. } else if (llama_is_control_token(model->vocab, token)) {
  8393. ;
  8394. } else if (llama_is_byte_token(model->vocab, token)) {
  8395. if (length < 1) {
  8396. return -1;
  8397. }
  8398. buf[0] = llama_token_to_byte(model->vocab, token);
  8399. return 1;
  8400. } else {
  8401. // TODO: for now we accept all unsupported token types,
  8402. // suppressing them like CONTROL tokens.
  8403. // GGML_ASSERT(false);
  8404. }
  8405. break;
  8406. }
  8407. case LLAMA_VOCAB_TYPE_BPE: {
  8408. if (llama_is_normal_token(model->vocab, token)) {
  8409. std::string result = model->vocab.id_to_token[token].text;
  8410. result = llama_decode_text(result);
  8411. if (length < (int) result.length()) {
  8412. return -result.length();
  8413. }
  8414. memcpy(buf, result.c_str(), result.length());
  8415. return result.length();
  8416. } else if (llama_is_control_token(model->vocab, token)) {
  8417. ;
  8418. } else {
  8419. // TODO: for now we accept all unsupported token types,
  8420. // suppressing them like CONTROL tokens.
  8421. // GGML_ASSERT(false);
  8422. }
  8423. break;
  8424. }
  8425. default:
  8426. GGML_ASSERT(false);
  8427. }
  8428. }
  8429. return 0;
  8430. }
  8431. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  8432. struct llama_timings result = {
  8433. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  8434. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  8435. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  8436. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  8437. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  8438. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  8439. /*.n_sample =*/ std::max(1, ctx->n_sample),
  8440. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  8441. /*.n_eval =*/ std::max(1, ctx->n_eval),
  8442. };
  8443. return result;
  8444. }
  8445. void llama_print_timings(struct llama_context * ctx) {
  8446. const llama_timings timings = llama_get_timings(ctx);
  8447. LLAMA_LOG_INFO("\n");
  8448. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  8449. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  8450. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  8451. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  8452. __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);
  8453. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  8454. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  8455. LLAMA_LOG_INFO("%s: total time = %10.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  8456. }
  8457. void llama_reset_timings(struct llama_context * ctx) {
  8458. ctx->t_start_us = ggml_time_us();
  8459. ctx->t_sample_us = ctx->n_sample = 0;
  8460. ctx->t_eval_us = ctx->n_eval = 0;
  8461. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  8462. }
  8463. const char * llama_print_system_info(void) {
  8464. static std::string s;
  8465. s = "";
  8466. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  8467. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  8468. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  8469. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  8470. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  8471. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  8472. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  8473. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  8474. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  8475. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  8476. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  8477. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  8478. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  8479. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  8480. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  8481. return s.c_str();
  8482. }
  8483. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  8484. fprintf(stream, "\n");
  8485. fprintf(stream, "###########\n");
  8486. fprintf(stream, "# Timings #\n");
  8487. fprintf(stream, "###########\n");
  8488. fprintf(stream, "\n");
  8489. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  8490. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  8491. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  8492. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  8493. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  8494. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  8495. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  8496. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  8497. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  8498. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  8499. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  8500. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  8501. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  8502. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  8503. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  8504. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  8505. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  8506. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  8507. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  8508. }
  8509. // For internal test use
  8510. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  8511. struct llama_context * ctx
  8512. ) {
  8513. return ctx->model.tensors_by_name;
  8514. }
  8515. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  8516. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  8517. g_state.log_callback_user_data = user_data;
  8518. #ifdef GGML_USE_METAL
  8519. ggml_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  8520. #endif
  8521. }
  8522. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  8523. va_list args_copy;
  8524. va_copy(args_copy, args);
  8525. char buffer[128];
  8526. int len = vsnprintf(buffer, 128, format, args);
  8527. if (len < 128) {
  8528. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  8529. } else {
  8530. char* buffer2 = new char[len+1];
  8531. vsnprintf(buffer2, len+1, format, args_copy);
  8532. buffer2[len] = 0;
  8533. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  8534. delete[] buffer2;
  8535. }
  8536. va_end(args_copy);
  8537. }
  8538. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  8539. va_list args;
  8540. va_start(args, format);
  8541. llama_log_internal_v(level, format, args);
  8542. va_end(args);
  8543. }
  8544. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  8545. (void) level;
  8546. (void) user_data;
  8547. fputs(text, stderr);
  8548. fflush(stderr);
  8549. }