1
0

llama.cpp 379 KB

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