llama.cpp 442 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <forward_list>
  65. #include <fstream>
  66. #include <functional>
  67. #include <initializer_list>
  68. #include <map>
  69. #include <memory>
  70. #include <mutex>
  71. #include <numeric>
  72. #include <queue>
  73. #include <random>
  74. #include <regex>
  75. #include <set>
  76. #include <sstream>
  77. #include <thread>
  78. #include <type_traits>
  79. #include <unordered_map>
  80. #if defined(_MSC_VER)
  81. #pragma warning(disable: 4244 4267) // possible loss of data
  82. #endif
  83. #ifdef __GNUC__
  84. #ifdef __MINGW32__
  85. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  86. #else
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  88. #endif
  89. #else
  90. #define LLAMA_ATTRIBUTE_FORMAT(...)
  91. #endif
  92. #define LLAMA_MAX_NODES 8192
  93. #define LLAMA_MAX_EXPERTS 8
  94. //
  95. // logging
  96. //
  97. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  98. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  99. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  100. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  101. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  102. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  103. //
  104. // helpers
  105. //
  106. static size_t utf8_len(char src) {
  107. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  108. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  109. return lookup[highbits];
  110. }
  111. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  112. std::string result;
  113. for (size_t pos = 0; ; pos += search.length()) {
  114. auto new_pos = s.find(search, pos);
  115. if (new_pos == std::string::npos) {
  116. result += s.substr(pos, s.size() - pos);
  117. break;
  118. }
  119. result += s.substr(pos, new_pos - pos) + replace;
  120. pos = new_pos;
  121. }
  122. s = std::move(result);
  123. }
  124. static bool is_float_close(float a, float b, float abs_tol) {
  125. // Check for non-negative tolerance
  126. if (abs_tol < 0.0) {
  127. throw std::invalid_argument("Tolerance must be non-negative");
  128. }
  129. // Exact equality check
  130. if (a == b) {
  131. return true;
  132. }
  133. // Check for infinities
  134. if (std::isinf(a) || std::isinf(b)) {
  135. return false;
  136. }
  137. // Regular comparison using the provided absolute tolerance
  138. return std::fabs(b - a) <= abs_tol;
  139. }
  140. static void zeros(std::ofstream & file, size_t n) {
  141. char zero = 0;
  142. for (size_t i = 0; i < n; ++i) {
  143. file.write(&zero, 1);
  144. }
  145. }
  146. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  147. static std::string format(const char * fmt, ...) {
  148. va_list ap;
  149. va_list ap2;
  150. va_start(ap, fmt);
  151. va_copy(ap2, ap);
  152. int size = vsnprintf(NULL, 0, fmt, ap);
  153. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  154. std::vector<char> buf(size + 1);
  155. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  156. GGML_ASSERT(size2 == size);
  157. va_end(ap2);
  158. va_end(ap);
  159. return std::string(buf.data(), size);
  160. }
  161. //
  162. // gguf constants (sync with gguf.py)
  163. //
  164. enum llm_arch {
  165. LLM_ARCH_LLAMA,
  166. LLM_ARCH_FALCON,
  167. LLM_ARCH_BAICHUAN,
  168. LLM_ARCH_GPT2,
  169. LLM_ARCH_GPTJ,
  170. LLM_ARCH_GPTNEOX,
  171. LLM_ARCH_MPT,
  172. LLM_ARCH_STARCODER,
  173. LLM_ARCH_PERSIMMON,
  174. LLM_ARCH_REFACT,
  175. LLM_ARCH_BLOOM,
  176. LLM_ARCH_STABLELM,
  177. LLM_ARCH_QWEN,
  178. LLM_ARCH_QWEN2,
  179. LLM_ARCH_PHI2,
  180. LLM_ARCH_PLAMO,
  181. LLM_ARCH_CODESHELL,
  182. LLM_ARCH_ORION,
  183. LLM_ARCH_UNKNOWN,
  184. };
  185. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  186. { LLM_ARCH_LLAMA, "llama" },
  187. { LLM_ARCH_FALCON, "falcon" },
  188. { LLM_ARCH_GPT2, "gpt2" },
  189. { LLM_ARCH_GPTJ, "gptj" },
  190. { LLM_ARCH_GPTNEOX, "gptneox" },
  191. { LLM_ARCH_MPT, "mpt" },
  192. { LLM_ARCH_BAICHUAN, "baichuan" },
  193. { LLM_ARCH_STARCODER, "starcoder" },
  194. { LLM_ARCH_PERSIMMON, "persimmon" },
  195. { LLM_ARCH_REFACT, "refact" },
  196. { LLM_ARCH_BLOOM, "bloom" },
  197. { LLM_ARCH_STABLELM, "stablelm" },
  198. { LLM_ARCH_QWEN, "qwen" },
  199. { LLM_ARCH_QWEN2, "qwen2" },
  200. { LLM_ARCH_PHI2, "phi2" },
  201. { LLM_ARCH_PLAMO, "plamo" },
  202. { LLM_ARCH_CODESHELL, "codeshell" },
  203. { LLM_ARCH_ORION, "orion" },
  204. };
  205. enum llm_kv {
  206. LLM_KV_GENERAL_ARCHITECTURE,
  207. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  208. LLM_KV_GENERAL_ALIGNMENT,
  209. LLM_KV_GENERAL_NAME,
  210. LLM_KV_GENERAL_AUTHOR,
  211. LLM_KV_GENERAL_URL,
  212. LLM_KV_GENERAL_DESCRIPTION,
  213. LLM_KV_GENERAL_LICENSE,
  214. LLM_KV_GENERAL_SOURCE_URL,
  215. LLM_KV_GENERAL_SOURCE_HF_REPO,
  216. LLM_KV_CONTEXT_LENGTH,
  217. LLM_KV_EMBEDDING_LENGTH,
  218. LLM_KV_BLOCK_COUNT,
  219. LLM_KV_FEED_FORWARD_LENGTH,
  220. LLM_KV_USE_PARALLEL_RESIDUAL,
  221. LLM_KV_TENSOR_DATA_LAYOUT,
  222. LLM_KV_EXPERT_COUNT,
  223. LLM_KV_EXPERT_USED_COUNT,
  224. LLM_KV_ATTENTION_HEAD_COUNT,
  225. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  226. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  227. LLM_KV_ATTENTION_CLAMP_KQV,
  228. LLM_KV_ATTENTION_KEY_LENGTH,
  229. LLM_KV_ATTENTION_VALUE_LENGTH,
  230. LLM_KV_ATTENTION_LAYERNORM_EPS,
  231. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  232. LLM_KV_ROPE_DIMENSION_COUNT,
  233. LLM_KV_ROPE_FREQ_BASE,
  234. LLM_KV_ROPE_SCALE_LINEAR,
  235. LLM_KV_ROPE_SCALING_TYPE,
  236. LLM_KV_ROPE_SCALING_FACTOR,
  237. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  238. LLM_KV_ROPE_SCALING_FINETUNED,
  239. LLM_KV_TOKENIZER_MODEL,
  240. LLM_KV_TOKENIZER_LIST,
  241. LLM_KV_TOKENIZER_TOKEN_TYPE,
  242. LLM_KV_TOKENIZER_SCORES,
  243. LLM_KV_TOKENIZER_MERGES,
  244. LLM_KV_TOKENIZER_BOS_ID,
  245. LLM_KV_TOKENIZER_EOS_ID,
  246. LLM_KV_TOKENIZER_UNK_ID,
  247. LLM_KV_TOKENIZER_SEP_ID,
  248. LLM_KV_TOKENIZER_PAD_ID,
  249. LLM_KV_TOKENIZER_ADD_BOS,
  250. LLM_KV_TOKENIZER_ADD_EOS,
  251. LLM_KV_TOKENIZER_HF_JSON,
  252. LLM_KV_TOKENIZER_RWKV,
  253. };
  254. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  255. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  256. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  257. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  258. { LLM_KV_GENERAL_NAME, "general.name" },
  259. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  260. { LLM_KV_GENERAL_URL, "general.url" },
  261. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  262. { LLM_KV_GENERAL_LICENSE, "general.license" },
  263. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  264. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  265. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  266. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  267. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  268. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  269. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  270. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  271. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  272. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  273. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  274. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  275. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  276. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  277. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  278. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  279. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  280. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  281. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  282. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  283. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  284. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  285. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  286. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  287. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  288. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  289. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  290. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  291. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  292. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  293. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  294. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  295. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  296. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  297. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  298. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  299. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  300. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  301. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  302. };
  303. struct LLM_KV {
  304. LLM_KV(llm_arch arch) : arch(arch) {}
  305. llm_arch arch;
  306. std::string operator()(llm_kv kv) const {
  307. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  308. }
  309. };
  310. enum llm_tensor {
  311. LLM_TENSOR_TOKEN_EMBD,
  312. LLM_TENSOR_TOKEN_EMBD_NORM,
  313. LLM_TENSOR_POS_EMBD,
  314. LLM_TENSOR_OUTPUT,
  315. LLM_TENSOR_OUTPUT_NORM,
  316. LLM_TENSOR_ROPE_FREQS,
  317. LLM_TENSOR_ATTN_Q,
  318. LLM_TENSOR_ATTN_K,
  319. LLM_TENSOR_ATTN_V,
  320. LLM_TENSOR_ATTN_QKV,
  321. LLM_TENSOR_ATTN_OUT,
  322. LLM_TENSOR_ATTN_NORM,
  323. LLM_TENSOR_ATTN_NORM_2,
  324. LLM_TENSOR_ATTN_ROT_EMBD,
  325. LLM_TENSOR_FFN_GATE_INP,
  326. LLM_TENSOR_FFN_NORM,
  327. LLM_TENSOR_FFN_GATE,
  328. LLM_TENSOR_FFN_DOWN,
  329. LLM_TENSOR_FFN_UP,
  330. LLM_TENSOR_FFN_ACT,
  331. LLM_TENSOR_FFN_DOWN_EXP,
  332. LLM_TENSOR_FFN_GATE_EXP,
  333. LLM_TENSOR_FFN_UP_EXP,
  334. LLM_TENSOR_ATTN_Q_NORM,
  335. LLM_TENSOR_ATTN_K_NORM,
  336. };
  337. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  338. {
  339. LLM_ARCH_LLAMA,
  340. {
  341. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  342. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  343. { LLM_TENSOR_OUTPUT, "output" },
  344. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  345. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  346. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  347. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  348. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  349. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  350. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  351. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  352. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  353. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  354. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  355. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  356. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  357. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  358. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  359. },
  360. },
  361. {
  362. LLM_ARCH_BAICHUAN,
  363. {
  364. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  365. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  366. { LLM_TENSOR_OUTPUT, "output" },
  367. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  368. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  369. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  370. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  371. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  372. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  373. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  374. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  375. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  376. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  377. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  378. },
  379. },
  380. {
  381. LLM_ARCH_FALCON,
  382. {
  383. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  384. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  385. { LLM_TENSOR_OUTPUT, "output" },
  386. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  387. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  388. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  389. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  390. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  391. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  392. },
  393. },
  394. {
  395. LLM_ARCH_GPT2,
  396. {
  397. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  398. { LLM_TENSOR_POS_EMBD, "position_embd" },
  399. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  400. { LLM_TENSOR_OUTPUT, "output" },
  401. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  402. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  403. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  404. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  405. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  406. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  407. },
  408. },
  409. {
  410. LLM_ARCH_GPTJ,
  411. {
  412. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  413. },
  414. },
  415. {
  416. LLM_ARCH_GPTNEOX,
  417. {
  418. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  419. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  420. { LLM_TENSOR_OUTPUT, "output" },
  421. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  422. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  423. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  424. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  425. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  426. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  427. },
  428. },
  429. {
  430. LLM_ARCH_PERSIMMON,
  431. {
  432. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  433. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  434. { LLM_TENSOR_OUTPUT, "output"},
  435. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  436. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  437. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  438. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  439. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  440. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  441. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  442. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  443. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  444. },
  445. },
  446. {
  447. LLM_ARCH_MPT,
  448. {
  449. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  450. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  451. { LLM_TENSOR_OUTPUT, "output" },
  452. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  453. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  454. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  455. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  456. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  457. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  458. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  459. },
  460. },
  461. {
  462. LLM_ARCH_STARCODER,
  463. {
  464. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  465. { LLM_TENSOR_POS_EMBD, "position_embd" },
  466. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  467. { LLM_TENSOR_OUTPUT, "output" },
  468. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  469. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  470. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  471. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  472. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  473. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  474. },
  475. },
  476. {
  477. LLM_ARCH_REFACT,
  478. {
  479. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  480. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  481. { LLM_TENSOR_OUTPUT, "output" },
  482. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  483. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  484. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  485. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  486. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  487. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  488. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  489. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  490. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  491. },
  492. },
  493. {
  494. LLM_ARCH_BLOOM,
  495. {
  496. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  497. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  498. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  499. { LLM_TENSOR_OUTPUT, "output" },
  500. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  501. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  502. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  503. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  504. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  505. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  506. },
  507. },
  508. {
  509. LLM_ARCH_STABLELM,
  510. {
  511. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  512. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  513. { LLM_TENSOR_OUTPUT, "output" },
  514. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  515. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  516. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  517. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  518. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  519. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  520. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  521. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  522. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  523. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  524. },
  525. },
  526. {
  527. LLM_ARCH_QWEN,
  528. {
  529. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  530. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  531. { LLM_TENSOR_OUTPUT, "output" },
  532. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  533. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  534. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  535. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  536. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  537. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  538. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  539. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  540. },
  541. },
  542. {
  543. LLM_ARCH_QWEN2,
  544. {
  545. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  546. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  547. { LLM_TENSOR_OUTPUT, "output" },
  548. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  549. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  550. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  551. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  552. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  553. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  554. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  555. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  556. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  557. },
  558. },
  559. {
  560. LLM_ARCH_PHI2,
  561. {
  562. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  563. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  564. { LLM_TENSOR_OUTPUT, "output" },
  565. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  566. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  567. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  568. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  569. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  570. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  571. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  572. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  573. },
  574. },
  575. {
  576. LLM_ARCH_PLAMO,
  577. {
  578. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  579. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  580. { LLM_TENSOR_OUTPUT, "output" },
  581. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  582. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  583. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  584. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  585. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  586. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  587. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  588. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  589. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  590. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  591. },
  592. },
  593. {
  594. LLM_ARCH_CODESHELL,
  595. {
  596. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  597. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  598. { LLM_TENSOR_OUTPUT, "output" },
  599. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  600. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  601. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  602. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  603. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  604. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  605. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  606. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  607. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  608. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  609. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  610. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  611. },
  612. },
  613. {
  614. LLM_ARCH_ORION,
  615. {
  616. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  617. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  618. { LLM_TENSOR_OUTPUT, "output" },
  619. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  620. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  621. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  622. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  623. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  624. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  625. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  626. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  627. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  628. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  629. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  630. },
  631. },
  632. {
  633. LLM_ARCH_UNKNOWN,
  634. {
  635. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  636. },
  637. },
  638. };
  639. static llm_arch llm_arch_from_string(const std::string & name) {
  640. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  641. if (kv.second == name) {
  642. return kv.first;
  643. }
  644. }
  645. return LLM_ARCH_UNKNOWN;
  646. }
  647. // helper to handle gguf constants
  648. // usage:
  649. //
  650. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  651. //
  652. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  653. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  654. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  655. //
  656. struct LLM_TN {
  657. LLM_TN(llm_arch arch) : arch(arch) {}
  658. llm_arch arch;
  659. std::string operator()(llm_tensor tensor) const {
  660. return LLM_TENSOR_NAMES[arch].at(tensor);
  661. }
  662. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  663. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  664. }
  665. std::string operator()(llm_tensor tensor, int bid) const {
  666. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  667. }
  668. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  669. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  670. }
  671. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  672. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  673. }
  674. };
  675. //
  676. // gguf helpers
  677. //
  678. static std::map<int8_t, std::string> LLAMA_ROPE_SCALING_TYPES = {
  679. { LLAMA_ROPE_SCALING_NONE, "none" },
  680. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  681. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  682. };
  683. static int8_t llama_rope_scaling_type_from_string(const std::string & name) {
  684. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  685. if (kv.second == name) {
  686. return kv.first;
  687. }
  688. }
  689. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  690. }
  691. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  692. switch (type) {
  693. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  694. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  695. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  696. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  697. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  698. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  699. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  700. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  701. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  702. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  703. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  704. default: return format("unknown type %d", type);
  705. }
  706. }
  707. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  708. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  709. switch (type) {
  710. case GGUF_TYPE_STRING:
  711. return gguf_get_val_str(ctx_gguf, i);
  712. case GGUF_TYPE_ARRAY:
  713. {
  714. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  715. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  716. const void * data = gguf_get_arr_data(ctx_gguf, i);
  717. std::stringstream ss;
  718. ss << "[";
  719. for (int j = 0; j < arr_n; j++) {
  720. if (arr_type == GGUF_TYPE_STRING) {
  721. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  722. // escape quotes
  723. replace_all(val, "\\", "\\\\");
  724. replace_all(val, "\"", "\\\"");
  725. ss << '"' << val << '"';
  726. } else if (arr_type == GGUF_TYPE_ARRAY) {
  727. ss << "???";
  728. } else {
  729. ss << gguf_data_to_str(arr_type, data, j);
  730. }
  731. if (j < arr_n - 1) {
  732. ss << ", ";
  733. }
  734. }
  735. ss << "]";
  736. return ss.str();
  737. }
  738. default:
  739. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  740. }
  741. }
  742. //
  743. // ggml helpers
  744. //
  745. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  746. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  747. if (plan.work_size > 0) {
  748. buf.resize(plan.work_size);
  749. plan.work_data = buf.data();
  750. }
  751. ggml_graph_compute(graph, &plan);
  752. }
  753. //
  754. // llama helpers
  755. //
  756. #if defined(_WIN32)
  757. static std::string llama_format_win_err(DWORD err) {
  758. LPSTR buf;
  759. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  760. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  761. if (!size) {
  762. return "FormatMessageA failed";
  763. }
  764. std::string ret(buf, size);
  765. LocalFree(buf);
  766. return ret;
  767. }
  768. #endif
  769. template <typename T>
  770. struct no_init {
  771. T value;
  772. no_init() { /* do nothing */ }
  773. };
  774. struct llama_file {
  775. // use FILE * so we don't have to re-open the file to mmap
  776. FILE * fp;
  777. size_t size;
  778. llama_file(const char * fname, const char * mode) {
  779. fp = std::fopen(fname, mode);
  780. if (fp == NULL) {
  781. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  782. }
  783. seek(0, SEEK_END);
  784. size = tell();
  785. seek(0, SEEK_SET);
  786. }
  787. size_t tell() const {
  788. #ifdef _WIN32
  789. __int64 ret = _ftelli64(fp);
  790. #else
  791. long ret = std::ftell(fp);
  792. #endif
  793. GGML_ASSERT(ret != -1); // this really shouldn't fail
  794. return (size_t) ret;
  795. }
  796. void seek(size_t offset, int whence) const {
  797. #ifdef _WIN32
  798. int ret = _fseeki64(fp, (__int64) offset, whence);
  799. #else
  800. int ret = std::fseek(fp, (long) offset, whence);
  801. #endif
  802. GGML_ASSERT(ret == 0); // same
  803. }
  804. void read_raw(void * ptr, size_t len) const {
  805. if (len == 0) {
  806. return;
  807. }
  808. errno = 0;
  809. std::size_t ret = std::fread(ptr, len, 1, fp);
  810. if (ferror(fp)) {
  811. throw std::runtime_error(format("read error: %s", strerror(errno)));
  812. }
  813. if (ret != 1) {
  814. throw std::runtime_error("unexpectedly reached end of file");
  815. }
  816. }
  817. uint32_t read_u32() const {
  818. uint32_t ret;
  819. read_raw(&ret, sizeof(ret));
  820. return ret;
  821. }
  822. void write_raw(const void * ptr, size_t len) const {
  823. if (len == 0) {
  824. return;
  825. }
  826. errno = 0;
  827. size_t ret = std::fwrite(ptr, len, 1, fp);
  828. if (ret != 1) {
  829. throw std::runtime_error(format("write error: %s", strerror(errno)));
  830. }
  831. }
  832. void write_u32(std::uint32_t val) const {
  833. write_raw(&val, sizeof(val));
  834. }
  835. ~llama_file() {
  836. if (fp) {
  837. std::fclose(fp);
  838. }
  839. }
  840. };
  841. struct llama_mmap {
  842. void * addr;
  843. size_t size;
  844. llama_mmap(const llama_mmap &) = delete;
  845. #ifdef _POSIX_MAPPED_FILES
  846. static constexpr bool SUPPORTED = true;
  847. // list of mapped fragments (first_offset, last_offset)
  848. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  849. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  850. size = file->size;
  851. int fd = fileno(file->fp);
  852. int flags = MAP_SHARED;
  853. // prefetch/readahead impairs performance on NUMA systems
  854. if (numa) { prefetch = 0; }
  855. #ifdef __linux__
  856. // advise the kernel to read the file sequentially (increases readahead)
  857. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  858. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  859. strerror(errno));
  860. }
  861. if (prefetch) { flags |= MAP_POPULATE; }
  862. #endif
  863. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  864. if (addr == MAP_FAILED) { // NOLINT
  865. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  866. }
  867. if (prefetch > 0) {
  868. // advise the kernel to preload the mapped memory
  869. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  870. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  871. strerror(errno));
  872. }
  873. }
  874. if (numa) {
  875. // advise the kernel not to use readahead
  876. // (because the next page might not belong on the same node)
  877. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  878. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  879. strerror(errno));
  880. }
  881. }
  882. // initialize list of mapped_fragments
  883. mapped_fragments.emplace_back(0, file->size);
  884. }
  885. static void align_range(size_t * first, size_t * last, size_t page_size) {
  886. // align first to the next page
  887. size_t offset_in_page = *first & (page_size - 1);
  888. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  889. *first += offset_to_page;
  890. // align last to the previous page
  891. *last = *last & ~(page_size - 1);
  892. if (*last <= *first) {
  893. *last = *first;
  894. }
  895. }
  896. // partially unmap the file in the range [first, last)
  897. void unmap_fragment(size_t first, size_t last) {
  898. // note: this function must not be called multiple times with overlapping ranges
  899. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  900. int page_size = sysconf(_SC_PAGESIZE);
  901. align_range(&first, &last, page_size);
  902. size_t len = last - first;
  903. if (len == 0) {
  904. return;
  905. }
  906. GGML_ASSERT(first % page_size == 0);
  907. GGML_ASSERT(last % page_size == 0);
  908. GGML_ASSERT(last > first);
  909. void * next_page_start = (uint8_t *) addr + first;
  910. // unmap the range
  911. if (munmap(next_page_start, len)) {
  912. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  913. }
  914. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  915. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  916. for (const auto & frag : mapped_fragments) {
  917. if (frag.first < first && frag.second > last) {
  918. // the range is in the middle of the fragment, split it
  919. new_mapped_fragments.emplace_back(frag.first, first);
  920. new_mapped_fragments.emplace_back(last, frag.second);
  921. } else if (frag.first < first && frag.second > first) {
  922. // the range starts in the middle of the fragment
  923. new_mapped_fragments.emplace_back(frag.first, first);
  924. } else if (frag.first < last && frag.second > last) {
  925. // the range ends in the middle of the fragment
  926. new_mapped_fragments.emplace_back(last, frag.second);
  927. } else if (frag.first >= first && frag.second <= last) {
  928. // the range covers the entire fragment
  929. } else {
  930. // the range is outside the fragment
  931. new_mapped_fragments.push_back(frag);
  932. }
  933. }
  934. mapped_fragments = std::move(new_mapped_fragments);
  935. }
  936. ~llama_mmap() {
  937. for (const auto & frag : mapped_fragments) {
  938. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  939. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  940. }
  941. }
  942. }
  943. #elif defined(_WIN32)
  944. static constexpr bool SUPPORTED = true;
  945. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  946. GGML_UNUSED(numa);
  947. size = file->size;
  948. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  949. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  950. if (hMapping == NULL) {
  951. DWORD error = GetLastError();
  952. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  953. }
  954. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  955. DWORD error = GetLastError();
  956. CloseHandle(hMapping);
  957. if (addr == NULL) {
  958. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  959. }
  960. if (prefetch > 0) {
  961. #if _WIN32_WINNT >= 0x602
  962. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  963. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  964. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  965. // may fail on pre-Windows 8 systems
  966. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  967. if (pPrefetchVirtualMemory) {
  968. // advise the kernel to preload the mapped memory
  969. WIN32_MEMORY_RANGE_ENTRY range;
  970. range.VirtualAddress = addr;
  971. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  972. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  973. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  974. llama_format_win_err(GetLastError()).c_str());
  975. }
  976. }
  977. #else
  978. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  979. #endif
  980. }
  981. }
  982. void unmap_fragment(size_t first, size_t last) {
  983. // not supported
  984. GGML_UNUSED(first);
  985. GGML_UNUSED(last);
  986. }
  987. ~llama_mmap() {
  988. if (!UnmapViewOfFile(addr)) {
  989. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  990. llama_format_win_err(GetLastError()).c_str());
  991. }
  992. }
  993. #else
  994. static constexpr bool SUPPORTED = false;
  995. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  996. GGML_UNUSED(file);
  997. GGML_UNUSED(prefetch);
  998. GGML_UNUSED(numa);
  999. throw std::runtime_error("mmap not supported");
  1000. }
  1001. void unmap_fragment(size_t first, size_t last) {
  1002. GGML_UNUSED(first);
  1003. GGML_UNUSED(last);
  1004. throw std::runtime_error("mmap not supported");
  1005. }
  1006. #endif
  1007. };
  1008. // Represents some region of memory being locked using mlock or VirtualLock;
  1009. // will automatically unlock on destruction.
  1010. struct llama_mlock {
  1011. void * addr = NULL;
  1012. size_t size = 0;
  1013. bool failed_already = false;
  1014. llama_mlock() {}
  1015. llama_mlock(const llama_mlock &) = delete;
  1016. ~llama_mlock() {
  1017. if (size) {
  1018. raw_unlock(addr, size);
  1019. }
  1020. }
  1021. void init(void * ptr) {
  1022. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1023. addr = ptr;
  1024. }
  1025. void grow_to(size_t target_size) {
  1026. GGML_ASSERT(addr);
  1027. if (failed_already) {
  1028. return;
  1029. }
  1030. size_t granularity = lock_granularity();
  1031. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1032. if (target_size > size) {
  1033. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1034. size = target_size;
  1035. } else {
  1036. failed_already = true;
  1037. }
  1038. }
  1039. }
  1040. #ifdef _POSIX_MEMLOCK_RANGE
  1041. static constexpr bool SUPPORTED = true;
  1042. static size_t lock_granularity() {
  1043. return (size_t) sysconf(_SC_PAGESIZE);
  1044. }
  1045. #ifdef __APPLE__
  1046. #define MLOCK_SUGGESTION \
  1047. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1048. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1049. #else
  1050. #define MLOCK_SUGGESTION \
  1051. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1052. #endif
  1053. bool raw_lock(const void * addr, size_t size) const {
  1054. if (!mlock(addr, size)) {
  1055. return true;
  1056. }
  1057. char* errmsg = std::strerror(errno);
  1058. bool suggest = (errno == ENOMEM);
  1059. // Check if the resource limit is fine after all
  1060. struct rlimit lock_limit;
  1061. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1062. suggest = false;
  1063. }
  1064. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1065. suggest = false;
  1066. }
  1067. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1068. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1069. return false;
  1070. }
  1071. #undef MLOCK_SUGGESTION
  1072. static void raw_unlock(void * addr, size_t size) {
  1073. if (munlock(addr, size)) {
  1074. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1075. }
  1076. }
  1077. #elif defined(_WIN32)
  1078. static constexpr bool SUPPORTED = true;
  1079. static size_t lock_granularity() {
  1080. SYSTEM_INFO si;
  1081. GetSystemInfo(&si);
  1082. return (size_t) si.dwPageSize;
  1083. }
  1084. bool raw_lock(void * ptr, size_t len) const {
  1085. for (int tries = 1; ; tries++) {
  1086. if (VirtualLock(ptr, len)) {
  1087. return true;
  1088. }
  1089. if (tries == 2) {
  1090. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1091. len, size, llama_format_win_err(GetLastError()).c_str());
  1092. return false;
  1093. }
  1094. // It failed but this was only the first try; increase the working
  1095. // set size and try again.
  1096. SIZE_T min_ws_size, max_ws_size;
  1097. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1098. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1099. llama_format_win_err(GetLastError()).c_str());
  1100. return false;
  1101. }
  1102. // Per MSDN: "The maximum number of pages that a process can lock
  1103. // is equal to the number of pages in its minimum working set minus
  1104. // a small overhead."
  1105. // Hopefully a megabyte is enough overhead:
  1106. size_t increment = len + 1048576;
  1107. // The minimum must be <= the maximum, so we need to increase both:
  1108. min_ws_size += increment;
  1109. max_ws_size += increment;
  1110. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1111. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1112. llama_format_win_err(GetLastError()).c_str());
  1113. return false;
  1114. }
  1115. }
  1116. }
  1117. static void raw_unlock(void * ptr, size_t len) {
  1118. if (!VirtualUnlock(ptr, len)) {
  1119. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1120. llama_format_win_err(GetLastError()).c_str());
  1121. }
  1122. }
  1123. #else
  1124. static constexpr bool SUPPORTED = false;
  1125. static size_t lock_granularity() {
  1126. return (size_t) 65536;
  1127. }
  1128. bool raw_lock(const void * addr, size_t len) const {
  1129. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1130. return false;
  1131. }
  1132. static void raw_unlock(const void * addr, size_t len) {}
  1133. #endif
  1134. };
  1135. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1136. std::vector<char> result(8, 0);
  1137. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1138. if (n_tokens < 0) {
  1139. result.resize(-n_tokens);
  1140. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1141. GGML_ASSERT(check == -n_tokens);
  1142. }
  1143. else {
  1144. result.resize(n_tokens);
  1145. }
  1146. return std::string(result.data(), result.size());
  1147. }
  1148. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1149. ggml_backend_buffer_type_t buft = nullptr;
  1150. #if defined(GGML_USE_CUBLAS)
  1151. // host buffers should only be used when data is expected to be copied to/from the GPU
  1152. if (host_buffer) {
  1153. buft = ggml_backend_cuda_host_buffer_type();
  1154. }
  1155. #elif defined(GGML_USE_SYCL)
  1156. buft = ggml_backend_sycl_host_buffer_type();
  1157. #elif defined(GGML_USE_CPU_HBM)
  1158. buft = ggml_backend_cpu_hbm_buffer_type();
  1159. #elif defined(GGML_USE_VULKAN)
  1160. if (host_buffer) {
  1161. buft = ggml_backend_vk_host_buffer_type();
  1162. }
  1163. #endif
  1164. if (buft == nullptr) {
  1165. buft = ggml_backend_cpu_buffer_type();
  1166. }
  1167. return buft;
  1168. GGML_UNUSED(host_buffer);
  1169. }
  1170. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1171. ggml_backend_buffer_type_t buft = nullptr;
  1172. #ifdef GGML_USE_METAL
  1173. buft = ggml_backend_metal_buffer_type();
  1174. #elif defined(GGML_USE_CUBLAS)
  1175. buft = ggml_backend_cuda_buffer_type(gpu);
  1176. #elif defined(GGML_USE_VULKAN)
  1177. buft = ggml_backend_vk_buffer_type();
  1178. #elif defined(GGML_USE_SYCL)
  1179. buft = ggml_backend_sycl_buffer_type(gpu);
  1180. #elif defined(GGML_USE_CLBLAST)
  1181. buft = ggml_backend_opencl_buffer_type();
  1182. #elif defined(GGML_USE_KOMPUTE)
  1183. buft = ggml_backend_kompute_buffer_type(gpu);
  1184. if (buft == nullptr) {
  1185. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1186. }
  1187. #endif
  1188. if (buft == nullptr) {
  1189. buft = llama_default_buffer_type_cpu(true);
  1190. }
  1191. return buft;
  1192. GGML_UNUSED(gpu);
  1193. }
  1194. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1195. ggml_backend_buffer_type_t buft = nullptr;
  1196. #ifdef GGML_USE_CUBLAS
  1197. if (ggml_backend_cuda_get_device_count() > 1) {
  1198. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1199. }
  1200. #endif
  1201. if (buft == nullptr) {
  1202. buft = llama_default_buffer_type_offload(fallback_gpu);
  1203. }
  1204. return buft;
  1205. GGML_UNUSED(tensor_split);
  1206. }
  1207. //
  1208. // globals
  1209. //
  1210. struct llama_state {
  1211. llama_state() {
  1212. #ifdef GGML_USE_METAL
  1213. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1214. #endif
  1215. }
  1216. // We save the log callback globally
  1217. ggml_log_callback log_callback = llama_log_callback_default;
  1218. void * log_callback_user_data = nullptr;
  1219. };
  1220. static llama_state g_state;
  1221. // available llama models
  1222. enum e_model {
  1223. MODEL_UNKNOWN,
  1224. MODEL_0_5B,
  1225. MODEL_1B,
  1226. MODEL_3B,
  1227. MODEL_4B,
  1228. MODEL_7B,
  1229. MODEL_8B,
  1230. MODEL_13B,
  1231. MODEL_14B,
  1232. MODEL_15B,
  1233. MODEL_30B,
  1234. MODEL_34B,
  1235. MODEL_40B,
  1236. MODEL_65B,
  1237. MODEL_70B,
  1238. MODEL_SMALL,
  1239. MODEL_MEDIUM,
  1240. MODEL_LARGE,
  1241. MODEL_XL,
  1242. };
  1243. static const size_t kiB = 1024;
  1244. static const size_t MiB = 1024*kiB;
  1245. static const size_t GiB = 1024*MiB;
  1246. struct llama_hparams {
  1247. bool vocab_only;
  1248. uint32_t n_vocab;
  1249. uint32_t n_ctx_train; // context size the model was trained on
  1250. uint32_t n_embd;
  1251. uint32_t n_head;
  1252. uint32_t n_head_kv;
  1253. uint32_t n_layer;
  1254. uint32_t n_rot;
  1255. uint32_t n_embd_head_k; // dimension of keys (d_k). d_q is assumed to be the same, but there are n_head q heads, and only n_head_kv k-v heads
  1256. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1257. uint32_t n_ff;
  1258. uint32_t n_expert = 0;
  1259. uint32_t n_expert_used = 0;
  1260. float f_norm_eps;
  1261. float f_norm_rms_eps;
  1262. float rope_freq_base_train;
  1263. float rope_freq_scale_train;
  1264. uint32_t n_yarn_orig_ctx;
  1265. int8_t rope_scaling_type_train : 3;
  1266. bool rope_finetuned : 1;
  1267. float f_clamp_kqv;
  1268. float f_max_alibi_bias;
  1269. bool operator!=(const llama_hparams & other) const {
  1270. if (this->vocab_only != other.vocab_only) return true;
  1271. if (this->n_vocab != other.n_vocab) return true;
  1272. if (this->n_ctx_train != other.n_ctx_train) return true;
  1273. if (this->n_embd != other.n_embd) return true;
  1274. if (this->n_head != other.n_head) return true;
  1275. if (this->n_head_kv != other.n_head_kv) return true;
  1276. if (this->n_layer != other.n_layer) return true;
  1277. if (this->n_rot != other.n_rot) return true;
  1278. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1279. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1280. if (this->n_ff != other.n_ff) return true;
  1281. if (this->n_expert != other.n_expert) return true;
  1282. if (this->n_expert_used != other.n_expert_used) return true;
  1283. if (this->rope_finetuned != other.rope_finetuned) return true;
  1284. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1285. const float EPSILON = 1e-9f;
  1286. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1287. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1288. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1289. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1290. return false;
  1291. }
  1292. uint32_t n_gqa() const {
  1293. return n_head/n_head_kv;
  1294. }
  1295. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1296. return n_embd_head_k * n_head_kv;
  1297. }
  1298. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1299. return n_embd_head_v * n_head_kv;
  1300. }
  1301. };
  1302. struct llama_cparams {
  1303. uint32_t n_ctx; // context size used during inference
  1304. uint32_t n_batch;
  1305. uint32_t n_threads; // number of threads to use for generation
  1306. uint32_t n_threads_batch; // number of threads to use for batch processing
  1307. float rope_freq_base;
  1308. float rope_freq_scale;
  1309. uint32_t n_yarn_orig_ctx;
  1310. // These hyperparameters are not exposed in GGUF, because all
  1311. // existing YaRN models use the same values for them.
  1312. float yarn_ext_factor;
  1313. float yarn_attn_factor;
  1314. float yarn_beta_fast;
  1315. float yarn_beta_slow;
  1316. bool mul_mat_q;
  1317. bool offload_kqv;
  1318. ggml_backend_sched_eval_callback cb_eval;
  1319. void * cb_eval_user_data;
  1320. };
  1321. struct llama_layer {
  1322. // normalization
  1323. struct ggml_tensor * attn_norm;
  1324. struct ggml_tensor * attn_norm_b;
  1325. struct ggml_tensor * attn_norm_2;
  1326. struct ggml_tensor * attn_norm_2_b;
  1327. struct ggml_tensor * attn_q_norm;
  1328. struct ggml_tensor * attn_q_norm_b;
  1329. struct ggml_tensor * attn_k_norm;
  1330. struct ggml_tensor * attn_k_norm_b;
  1331. // attention
  1332. struct ggml_tensor * wq;
  1333. struct ggml_tensor * wk;
  1334. struct ggml_tensor * wv;
  1335. struct ggml_tensor * wo;
  1336. struct ggml_tensor * wqkv;
  1337. // attention bias
  1338. struct ggml_tensor * bq;
  1339. struct ggml_tensor * bk;
  1340. struct ggml_tensor * bv;
  1341. struct ggml_tensor * bo;
  1342. struct ggml_tensor * bqkv;
  1343. // normalization
  1344. struct ggml_tensor * ffn_norm;
  1345. struct ggml_tensor * ffn_norm_b;
  1346. // ff
  1347. struct ggml_tensor * ffn_gate; // w1
  1348. struct ggml_tensor * ffn_down; // w2
  1349. struct ggml_tensor * ffn_up; // w3
  1350. // ff MoE
  1351. struct ggml_tensor * ffn_gate_inp;
  1352. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1353. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1354. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1355. // ff bias
  1356. struct ggml_tensor * ffn_down_b; // b2
  1357. struct ggml_tensor * ffn_up_b; // b3
  1358. struct ggml_tensor * ffn_act;
  1359. };
  1360. struct llama_kv_cell {
  1361. llama_pos pos = -1;
  1362. llama_pos delta = 0;
  1363. std::set<llama_seq_id> seq_id;
  1364. bool has_seq_id(const llama_seq_id & id) const {
  1365. return seq_id.find(id) != seq_id.end();
  1366. }
  1367. };
  1368. // ring-buffer of cached KV data
  1369. struct llama_kv_cache {
  1370. bool has_shift = false;
  1371. // Note: The value of head isn't only used to optimize searching
  1372. // for a free KV slot. llama_decode_internal also uses it, so it
  1373. // cannot be freely changed after a slot has been allocated.
  1374. uint32_t head = 0;
  1375. uint32_t size = 0;
  1376. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1377. // computed before each graph build
  1378. uint32_t n = 0;
  1379. std::vector<llama_kv_cell> cells;
  1380. std::vector<struct ggml_tensor *> k_l; // per layer
  1381. std::vector<struct ggml_tensor *> v_l;
  1382. std::vector<struct ggml_context *> ctxs;
  1383. std::vector<ggml_backend_buffer_t> bufs;
  1384. size_t total_size() const {
  1385. size_t size = 0;
  1386. for (ggml_backend_buffer_t buf : bufs) {
  1387. size += ggml_backend_buffer_get_size(buf);
  1388. }
  1389. return size;
  1390. }
  1391. ~llama_kv_cache() {
  1392. for (struct ggml_context * ctx : ctxs) {
  1393. ggml_free(ctx);
  1394. }
  1395. for (ggml_backend_buffer_t buf : bufs) {
  1396. ggml_backend_buffer_free(buf);
  1397. }
  1398. }
  1399. };
  1400. struct llama_vocab {
  1401. using id = int32_t;
  1402. using token = std::string;
  1403. using ttype = llama_token_type;
  1404. struct token_data {
  1405. token text;
  1406. float score;
  1407. ttype type;
  1408. };
  1409. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1410. std::unordered_map<token, id> token_to_id;
  1411. std::vector<token_data> id_to_token;
  1412. std::unordered_map<token, id> special_tokens_cache;
  1413. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1414. // default LLaMA special tokens
  1415. id special_bos_id = 1;
  1416. id special_eos_id = 2;
  1417. id special_unk_id = 0;
  1418. id special_sep_id = -1;
  1419. id special_pad_id = -1;
  1420. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1421. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1422. id linefeed_id = 13;
  1423. id special_prefix_id = 32007;
  1424. id special_middle_id = 32009;
  1425. id special_suffix_id = 32008;
  1426. id special_eot_id = 32010;
  1427. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1428. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1429. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1430. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1431. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1432. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1433. if (it == bpe_ranks.end()) {
  1434. return -1;
  1435. }
  1436. return it->second;
  1437. }
  1438. };
  1439. struct llama_model {
  1440. e_model type = MODEL_UNKNOWN;
  1441. llm_arch arch = LLM_ARCH_UNKNOWN;
  1442. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1443. std::string name = "n/a";
  1444. llama_hparams hparams = {};
  1445. llama_vocab vocab;
  1446. struct ggml_tensor * tok_embd;
  1447. struct ggml_tensor * pos_embd;
  1448. struct ggml_tensor * tok_norm;
  1449. struct ggml_tensor * tok_norm_b;
  1450. struct ggml_tensor * output_norm;
  1451. struct ggml_tensor * output_norm_b;
  1452. struct ggml_tensor * output;
  1453. struct ggml_tensor * output_b;
  1454. std::vector<llama_layer> layers;
  1455. llama_split_mode split_mode;
  1456. int main_gpu;
  1457. int n_gpu_layers;
  1458. // gguf metadata
  1459. std::unordered_map<std::string, std::string> gguf_kv;
  1460. // layer -> buffer type mapping
  1461. struct layer_buft {
  1462. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1463. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1464. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1465. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1466. ggml_backend_buffer_type_t buft; // everything else
  1467. };
  1468. layer_buft buft_input;
  1469. layer_buft buft_output;
  1470. std::vector<layer_buft> buft_layer;
  1471. // contexts where the model tensors metadata is stored
  1472. std::vector<struct ggml_context *> ctxs;
  1473. // the model memory buffers for the tensor data
  1474. std::vector<ggml_backend_buffer_t> bufs;
  1475. // model memory mapped file
  1476. std::unique_ptr<llama_mmap> mapping;
  1477. // objects representing data potentially being locked in memory
  1478. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1479. llama_mlock mlock_mmap;
  1480. // for quantize-stats only
  1481. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1482. int64_t t_load_us = 0;
  1483. int64_t t_start_us = 0;
  1484. ~llama_model() {
  1485. for (struct ggml_context * ctx : ctxs) {
  1486. ggml_free(ctx);
  1487. }
  1488. for (ggml_backend_buffer_t buf : bufs) {
  1489. ggml_backend_buffer_free(buf);
  1490. }
  1491. }
  1492. };
  1493. struct llama_context {
  1494. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1495. ~llama_context() {
  1496. ggml_backend_sched_free(sched);
  1497. for (ggml_backend_t backend : backends) {
  1498. ggml_backend_free(backend);
  1499. }
  1500. ggml_backend_buffer_free(buf_input);
  1501. ggml_free(ctx_input);
  1502. }
  1503. llama_cparams cparams;
  1504. std::vector<ggml_backend_t> backends;
  1505. #ifdef GGML_USE_METAL
  1506. ggml_backend_t backend_metal = nullptr;
  1507. #endif
  1508. ggml_backend_t backend_cpu = nullptr;
  1509. const llama_model & model;
  1510. // key + value cache for the self attention
  1511. struct llama_kv_cache kv_self;
  1512. std::mt19937 rng;
  1513. bool has_evaluated_once = false;
  1514. int64_t t_start_us;
  1515. int64_t t_load_us;
  1516. int64_t t_sample_us = 0;
  1517. int64_t t_p_eval_us = 0;
  1518. int64_t t_eval_us = 0;
  1519. int32_t n_sample = 0; // number of tokens sampled
  1520. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1521. int32_t n_eval = 0; // number of eval calls
  1522. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1523. std::vector<float> logits;
  1524. #ifndef NDEBUG
  1525. // guard against access to unset logits
  1526. std::vector<bool> logits_valid;
  1527. #endif
  1528. bool logits_all = false;
  1529. // input embedding (1-dimensional array: [n_embd])
  1530. std::vector<float> embedding;
  1531. // memory buffers used to evaluate the model
  1532. std::vector<uint8_t> buf_compute_meta;
  1533. ggml_backend_sched_t sched = nullptr;
  1534. // allocator for the input tensors
  1535. ggml_tallocr * alloc = nullptr;
  1536. // input tensors
  1537. ggml_backend_buffer_t buf_input = nullptr;
  1538. ggml_context * ctx_input = nullptr;
  1539. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1540. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1541. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1542. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1543. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1544. #ifdef GGML_USE_MPI
  1545. ggml_mpi_context * ctx_mpi = NULL;
  1546. #endif
  1547. };
  1548. //
  1549. // kv cache helpers
  1550. //
  1551. static bool llama_kv_cache_init(
  1552. struct llama_kv_cache & cache,
  1553. const llama_model & model,
  1554. ggml_type ktype,
  1555. ggml_type vtype,
  1556. uint32_t n_ctx,
  1557. bool offload) {
  1558. const struct llama_hparams & hparams = model.hparams;
  1559. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1560. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1561. const int64_t n_layer = hparams.n_layer;
  1562. cache.has_shift = false;
  1563. cache.head = 0;
  1564. cache.size = n_ctx;
  1565. cache.used = 0;
  1566. cache.cells.clear();
  1567. cache.cells.resize(n_ctx);
  1568. #ifdef GGML_USE_CLBLAST
  1569. offload = false;
  1570. #endif
  1571. // count used buffer types
  1572. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1573. if (offload) {
  1574. for (int64_t i = 0; i < n_layer; ++i) {
  1575. buft_layer_count[model.buft_layer[i].buft]++;
  1576. }
  1577. } else {
  1578. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1579. }
  1580. // create a context for each buffer type
  1581. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1582. for (auto & it : buft_layer_count) {
  1583. int n_layers = it.second;
  1584. struct ggml_init_params params = {
  1585. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1586. /*.mem_buffer =*/ NULL,
  1587. /*.no_alloc =*/ true,
  1588. };
  1589. ggml_context * ctx = ggml_init(params);
  1590. if (!ctx) {
  1591. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1592. return false;
  1593. }
  1594. ctx_map[it.first] = ctx;
  1595. cache.ctxs.push_back(ctx);
  1596. }
  1597. cache.k_l.reserve(n_layer);
  1598. cache.v_l.reserve(n_layer);
  1599. for (int i = 0; i < (int) n_layer; i++) {
  1600. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1601. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1602. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1603. ggml_format_name(k, "cache_k_l%d", i);
  1604. ggml_format_name(v, "cache_v_l%d", i);
  1605. cache.k_l.push_back(k);
  1606. cache.v_l.push_back(v);
  1607. }
  1608. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1609. for (auto it : ctx_map) {
  1610. ggml_backend_buffer_type_t buft = it.first;
  1611. ggml_context * ctx = it.second;
  1612. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1613. if (!buf) {
  1614. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1615. return false;
  1616. }
  1617. ggml_backend_buffer_clear(buf, 0);
  1618. LLAMA_LOG_INFO("%s: %10s KV buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
  1619. cache.bufs.push_back(buf);
  1620. }
  1621. return true;
  1622. }
  1623. // find an empty slot of size "n_tokens" in the cache
  1624. // updates the cache head
  1625. // Note: On success, it's important that cache.head points
  1626. // to the first cell of the slot.
  1627. static bool llama_kv_cache_find_slot(
  1628. struct llama_kv_cache & cache,
  1629. const struct llama_batch & batch) {
  1630. const uint32_t n_ctx = cache.size;
  1631. const uint32_t n_tokens = batch.n_tokens;
  1632. if (n_tokens > n_ctx) {
  1633. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1634. return false;
  1635. }
  1636. uint32_t n_tested = 0;
  1637. while (true) {
  1638. if (cache.head + n_tokens > n_ctx) {
  1639. n_tested += n_ctx - cache.head;
  1640. cache.head = 0;
  1641. continue;
  1642. }
  1643. bool found = true;
  1644. for (uint32_t i = 0; i < n_tokens; i++) {
  1645. if (cache.cells[cache.head + i].pos >= 0) {
  1646. found = false;
  1647. cache.head += i + 1;
  1648. n_tested += i + 1;
  1649. break;
  1650. }
  1651. }
  1652. if (found) {
  1653. break;
  1654. }
  1655. if (n_tested >= n_ctx) {
  1656. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1657. return false;
  1658. }
  1659. }
  1660. for (uint32_t i = 0; i < n_tokens; i++) {
  1661. cache.cells[cache.head + i].pos = batch.pos[i];
  1662. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1663. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1664. }
  1665. }
  1666. cache.used += n_tokens;
  1667. return true;
  1668. }
  1669. // find how many cells are currently in use
  1670. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1671. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1672. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1673. return i + 1;
  1674. }
  1675. }
  1676. return 0;
  1677. }
  1678. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1679. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1680. cache.cells[i].pos = -1;
  1681. cache.cells[i].seq_id.clear();
  1682. }
  1683. cache.head = 0;
  1684. cache.used = 0;
  1685. }
  1686. static void llama_kv_cache_seq_rm(
  1687. struct llama_kv_cache & cache,
  1688. llama_seq_id seq_id,
  1689. llama_pos p0,
  1690. llama_pos p1) {
  1691. uint32_t new_head = cache.size;
  1692. if (p0 < 0) p0 = 0;
  1693. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1694. for (uint32_t i = 0; i < cache.size; ++i) {
  1695. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1696. if (seq_id < 0) {
  1697. cache.cells[i].seq_id.clear();
  1698. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1699. cache.cells[i].seq_id.erase(seq_id);
  1700. } else {
  1701. continue;
  1702. }
  1703. if (cache.cells[i].seq_id.empty()) {
  1704. // keep count of the number of used cells
  1705. if (cache.cells[i].pos >= 0) cache.used--;
  1706. cache.cells[i].pos = -1;
  1707. if (new_head == cache.size) new_head = i;
  1708. }
  1709. }
  1710. }
  1711. // If we freed up a slot, set head to it so searching can start there.
  1712. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1713. }
  1714. static void llama_kv_cache_seq_cp(
  1715. struct llama_kv_cache & cache,
  1716. llama_seq_id seq_id_src,
  1717. llama_seq_id seq_id_dst,
  1718. llama_pos p0,
  1719. llama_pos p1) {
  1720. if (p0 < 0) p0 = 0;
  1721. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1722. cache.head = 0;
  1723. for (uint32_t i = 0; i < cache.size; ++i) {
  1724. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1725. cache.cells[i].seq_id.insert(seq_id_dst);
  1726. }
  1727. }
  1728. }
  1729. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1730. uint32_t new_head = cache.size;
  1731. for (uint32_t i = 0; i < cache.size; ++i) {
  1732. if (!cache.cells[i].has_seq_id(seq_id)) {
  1733. if (cache.cells[i].pos >= 0) cache.used--;
  1734. cache.cells[i].pos = -1;
  1735. cache.cells[i].seq_id.clear();
  1736. if (new_head == cache.size) new_head = i;
  1737. } else {
  1738. cache.cells[i].seq_id.clear();
  1739. cache.cells[i].seq_id.insert(seq_id);
  1740. }
  1741. }
  1742. // If we freed up a slot, set head to it so searching can start there.
  1743. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1744. }
  1745. static void llama_kv_cache_seq_shift(
  1746. struct llama_kv_cache & cache,
  1747. llama_seq_id seq_id,
  1748. llama_pos p0,
  1749. llama_pos p1,
  1750. llama_pos delta) {
  1751. uint32_t new_head = cache.size;
  1752. if (p0 < 0) p0 = 0;
  1753. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1754. for (uint32_t i = 0; i < cache.size; ++i) {
  1755. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1756. cache.has_shift = true;
  1757. cache.cells[i].pos += delta;
  1758. cache.cells[i].delta += delta;
  1759. if (cache.cells[i].pos < 0) {
  1760. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1761. cache.cells[i].pos = -1;
  1762. cache.cells[i].seq_id.clear();
  1763. if (new_head == cache.size) new_head = i;
  1764. }
  1765. }
  1766. }
  1767. // If we freed up a slot, set head to it so searching can start there.
  1768. // Otherwise we just start the next search from the beginning.
  1769. cache.head = new_head != cache.size ? new_head : 0;
  1770. }
  1771. static void llama_kv_cache_seq_div(
  1772. struct llama_kv_cache & cache,
  1773. llama_seq_id seq_id,
  1774. llama_pos p0,
  1775. llama_pos p1,
  1776. int d) {
  1777. if (p0 < 0) p0 = 0;
  1778. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1779. for (uint32_t i = 0; i < cache.size; ++i) {
  1780. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1781. cache.has_shift = true;
  1782. {
  1783. llama_pos p_old = cache.cells[i].pos;
  1784. cache.cells[i].pos /= d;
  1785. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1786. }
  1787. }
  1788. }
  1789. }
  1790. //
  1791. // model loading and saving
  1792. //
  1793. enum llama_fver {
  1794. GGUF_FILE_VERSION_V1 = 1,
  1795. GGUF_FILE_VERSION_V2 = 2,
  1796. GGUF_FILE_VERSION_V3 = 3,
  1797. };
  1798. static const char * llama_file_version_name(llama_fver version) {
  1799. switch (version) {
  1800. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1801. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1802. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1803. }
  1804. return "unknown";
  1805. }
  1806. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1807. char buf[256];
  1808. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1809. for (size_t i = 1; i < ne.size(); i++) {
  1810. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1811. }
  1812. return buf;
  1813. }
  1814. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1815. char buf[256];
  1816. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1817. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1818. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1819. }
  1820. return buf;
  1821. }
  1822. namespace GGUFMeta {
  1823. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1824. struct GKV_Base_Type {
  1825. static constexpr gguf_type gt = gt_;
  1826. static T getter(const gguf_context * ctx, const int kid) {
  1827. return gfun(ctx, kid);
  1828. }
  1829. };
  1830. template<typename T> struct GKV_Base;
  1831. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1832. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1833. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1834. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1835. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1836. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1837. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1838. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1839. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1840. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1841. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1842. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1843. template<> struct GKV_Base<std::string> {
  1844. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1845. static std::string getter(const gguf_context * ctx, const int kid) {
  1846. return gguf_get_val_str(ctx, kid);
  1847. }
  1848. };
  1849. struct ArrayInfo{
  1850. const gguf_type gt;
  1851. const size_t length;
  1852. const void * data;
  1853. };
  1854. template<> struct GKV_Base<ArrayInfo> {
  1855. public:
  1856. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1857. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1858. return ArrayInfo {
  1859. gguf_get_arr_type(ctx, k),
  1860. size_t(gguf_get_arr_n(ctx, k)),
  1861. gguf_get_arr_data(ctx, k),
  1862. };
  1863. }
  1864. };
  1865. template<typename T>
  1866. class GKV: public GKV_Base<T> {
  1867. GKV() = delete;
  1868. public:
  1869. static T get_kv(const gguf_context * ctx, const int k) {
  1870. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1871. if (kt != GKV::gt) {
  1872. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1873. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1874. }
  1875. return GKV::getter(ctx, k);
  1876. }
  1877. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1878. switch (ty) {
  1879. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1880. case LLAMA_KV_OVERRIDE_INT: return "int";
  1881. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1882. }
  1883. return "unknown";
  1884. }
  1885. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1886. if (!override) { return false; }
  1887. if (override->tag == expected_type) {
  1888. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1889. __func__, override_type_to_str(override->tag), override->key);
  1890. switch (override->tag) {
  1891. case LLAMA_KV_OVERRIDE_BOOL: {
  1892. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  1893. } break;
  1894. case LLAMA_KV_OVERRIDE_INT: {
  1895. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  1896. } break;
  1897. case LLAMA_KV_OVERRIDE_FLOAT: {
  1898. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  1899. } break;
  1900. default:
  1901. // Shouldn't be possible to end up here, but just in case...
  1902. throw std::runtime_error(
  1903. format("Unsupported attempt to override %s type for metadata key %s\n",
  1904. override_type_to_str(override->tag), override->key));
  1905. }
  1906. return true;
  1907. }
  1908. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1909. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1910. return false;
  1911. }
  1912. template<typename OT>
  1913. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1914. try_override(OT & target, const struct llama_model_kv_override *override) {
  1915. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1916. target = override->bool_value;
  1917. return true;
  1918. }
  1919. return false;
  1920. }
  1921. template<typename OT>
  1922. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1923. try_override(OT & target, const struct llama_model_kv_override *override) {
  1924. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1925. target = override->int_value;
  1926. return true;
  1927. }
  1928. return false;
  1929. }
  1930. template<typename OT>
  1931. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1932. try_override(T & target, const struct llama_model_kv_override *override) {
  1933. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1934. target = override->float_value;
  1935. return true;
  1936. }
  1937. return false;
  1938. }
  1939. template<typename OT>
  1940. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1941. try_override(T & target, const struct llama_model_kv_override *override) {
  1942. (void)target;
  1943. (void)override;
  1944. if (!override) { return false; }
  1945. // Currently, we should never end up here so it would be a bug if we do.
  1946. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1947. override ? override->key : "NULL"));
  1948. }
  1949. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1950. if (try_override<T>(target, override)) {
  1951. return true;
  1952. }
  1953. if (k < 0) { return false; }
  1954. target = get_kv(ctx, k);
  1955. return true;
  1956. }
  1957. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1958. return set(ctx, gguf_find_key(ctx, key), target, override);
  1959. }
  1960. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1961. return set(ctx, key.c_str(), target, override);
  1962. }
  1963. };
  1964. }
  1965. struct llama_model_loader {
  1966. int n_kv = 0;
  1967. int n_tensors = 0;
  1968. int n_created = 0;
  1969. int64_t n_elements = 0;
  1970. size_t n_bytes = 0;
  1971. bool use_mmap = false;
  1972. llama_file file;
  1973. llama_ftype ftype;
  1974. llama_fver fver;
  1975. std::unique_ptr<llama_mmap> mapping;
  1976. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1977. struct gguf_context * ctx_gguf = NULL;
  1978. struct ggml_context * ctx_meta = NULL;
  1979. std::string arch_name;
  1980. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1981. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1982. int trace = 0;
  1983. if (getenv("LLAMA_TRACE")) {
  1984. trace = atoi(getenv("LLAMA_TRACE"));
  1985. }
  1986. struct gguf_init_params params = {
  1987. /*.no_alloc = */ true,
  1988. /*.ctx = */ &ctx_meta,
  1989. };
  1990. if (param_overrides_p != nullptr) {
  1991. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1992. kv_overrides.insert({std::string(p->key), *p});
  1993. }
  1994. }
  1995. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1996. if (!ctx_gguf) {
  1997. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1998. }
  1999. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2000. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2001. n_kv = gguf_get_n_kv(ctx_gguf);
  2002. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2003. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2004. for (int i = 0; i < n_tensors; i++) {
  2005. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2006. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2007. n_elements += ggml_nelements(t);
  2008. n_bytes += ggml_nbytes(t);
  2009. }
  2010. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2011. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2012. // determine file type based on the number of tensors for each quantization and print meta data
  2013. // TODO: make optional
  2014. {
  2015. std::map<enum ggml_type, uint32_t> n_type;
  2016. uint32_t n_type_max = 0;
  2017. enum ggml_type type_max = GGML_TYPE_F32;
  2018. for (int i = 0; i < n_tensors; i++) {
  2019. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2020. n_type[type]++;
  2021. if (n_type_max < n_type[type]) {
  2022. n_type_max = n_type[type];
  2023. type_max = type;
  2024. }
  2025. if (trace > 0) {
  2026. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2027. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, ggml_get_name(meta), ggml_type_name(type), llama_format_tensor_shape(meta).c_str());
  2028. }
  2029. }
  2030. switch (type_max) {
  2031. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2032. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2033. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2034. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2035. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2036. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2037. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2038. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2039. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2040. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2041. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2042. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2043. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2044. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2045. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2046. default:
  2047. {
  2048. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2049. ftype = LLAMA_FTYPE_ALL_F32;
  2050. } break;
  2051. }
  2052. // this is a way to mark that we have "guessed" the file type
  2053. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2054. {
  2055. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2056. if (kid >= 0) {
  2057. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2058. }
  2059. }
  2060. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2061. for (int i = 0; i < n_kv; i++) {
  2062. const char * name = gguf_get_key(ctx_gguf, i);
  2063. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2064. const std::string type_name =
  2065. type == GGUF_TYPE_ARRAY
  2066. ? 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))
  2067. : gguf_type_name(type);
  2068. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2069. const size_t MAX_VALUE_LEN = 40;
  2070. if (value.size() > MAX_VALUE_LEN) {
  2071. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2072. }
  2073. replace_all(value, "\n", "\\n");
  2074. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2075. }
  2076. // print type counts
  2077. for (auto & kv : n_type) {
  2078. if (kv.second == 0) {
  2079. continue;
  2080. }
  2081. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2082. }
  2083. }
  2084. if (!llama_mmap::SUPPORTED) {
  2085. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2086. use_mmap = false;
  2087. }
  2088. this->use_mmap = use_mmap;
  2089. }
  2090. ~llama_model_loader() {
  2091. if (ctx_gguf) {
  2092. gguf_free(ctx_gguf);
  2093. }
  2094. if (ctx_meta) {
  2095. ggml_free(ctx_meta);
  2096. }
  2097. }
  2098. template<typename T>
  2099. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2100. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2101. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2102. if (kid < 0) {
  2103. if (required) {
  2104. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2105. }
  2106. return false;
  2107. }
  2108. struct GGUFMeta::ArrayInfo arr_info =
  2109. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2110. result = arr_info.length;
  2111. return true;
  2112. }
  2113. template<typename T>
  2114. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2115. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2116. return get_arr_n(llm_kv(kid), result, required);
  2117. }
  2118. template<typename T>
  2119. bool get_key(const std::string & key, T & result, const bool required = true) {
  2120. auto it = kv_overrides.find(key);
  2121. const struct llama_model_kv_override * override =
  2122. it != kv_overrides.end() ? &it->second : nullptr;
  2123. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2124. if (required && !found) {
  2125. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2126. }
  2127. return found;
  2128. }
  2129. template<typename T>
  2130. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2131. return get_key(llm_kv(kid), result, required);
  2132. }
  2133. std::string get_arch_name() const {
  2134. return arch_name;
  2135. }
  2136. enum llm_arch get_arch() const {
  2137. return llm_kv.arch;
  2138. }
  2139. const char * get_tensor_name(int i) const {
  2140. return gguf_get_tensor_name(ctx_gguf, i);
  2141. }
  2142. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2143. return ggml_get_tensor(ctx_meta, name);
  2144. }
  2145. struct ggml_tensor * get_tensor_meta(int i) const {
  2146. return get_tensor_meta(get_tensor_name(i));
  2147. }
  2148. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2149. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2150. ggml_set_name(tensor, ggml_get_name(meta));
  2151. n_created++;
  2152. return tensor;
  2153. }
  2154. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2155. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2156. if (cur == NULL) {
  2157. if (!required) {
  2158. return NULL;
  2159. }
  2160. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2161. }
  2162. {
  2163. bool is_ok = true;
  2164. for (size_t i = 0; i < ne.size(); ++i) {
  2165. if (ne[i] != cur->ne[i]) {
  2166. is_ok = false;
  2167. break;
  2168. }
  2169. }
  2170. if (!is_ok) {
  2171. throw std::runtime_error(
  2172. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2173. __func__, name.c_str(),
  2174. llama_format_tensor_shape(ne).c_str(),
  2175. llama_format_tensor_shape(cur).c_str()));
  2176. }
  2177. }
  2178. return create_tensor_for(ctx, cur);
  2179. }
  2180. void done_getting_tensors() const {
  2181. if (n_created != n_tensors) {
  2182. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2183. }
  2184. }
  2185. size_t file_offset(const char * name) const {
  2186. const int idx = gguf_find_tensor(ctx_gguf, name);
  2187. if (idx < 0) {
  2188. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2189. }
  2190. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2191. }
  2192. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2193. // prefetch the whole file - all the data is needed anyway
  2194. if (use_mmap) {
  2195. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2196. }
  2197. // compute the total size of all tensors for progress reporting
  2198. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2199. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2200. size_data += ggml_nbytes(cur);
  2201. }
  2202. if (use_mmap && mapping) {
  2203. if (lmlock) {
  2204. lmlock->init(mapping->addr);
  2205. }
  2206. mmap_used_first = mapping->size;
  2207. }
  2208. }
  2209. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2210. GGML_ASSERT(mapping);
  2211. *first = mapping->size;
  2212. *last = 0;
  2213. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2214. const size_t offs = file_offset(ggml_get_name(tensor));
  2215. *first = std::min(*first, offs);
  2216. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2217. }
  2218. }
  2219. // for backwards compatibility, does not support ggml-backend
  2220. void load_data_for(struct ggml_tensor * cur) const {
  2221. const size_t offs = file_offset(ggml_get_name(cur));
  2222. if (use_mmap && mapping) {
  2223. if (cur->data == nullptr) {
  2224. cur->data = (uint8_t *)mapping->addr + offs;
  2225. } else {
  2226. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2227. }
  2228. } else {
  2229. GGML_ASSERT(cur->data != nullptr);
  2230. file.seek(offs, SEEK_SET);
  2231. file.read_raw(cur->data, ggml_nbytes(cur));
  2232. }
  2233. }
  2234. size_t size_done = 0;
  2235. size_t size_data = 0;
  2236. size_t mmap_used_first = -1;
  2237. size_t mmap_used_last = 0;
  2238. // Returns false if cancelled by progress_callback
  2239. bool load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, ggml_backend_buffer_t buf_mmap, llama_mlock * lmlock) {
  2240. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2241. std::vector<no_init<uint8_t>> read_buf;
  2242. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2243. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2244. if (!cur) {
  2245. // some tensors may be allocated in a different context
  2246. continue;
  2247. }
  2248. if (progress_callback) {
  2249. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2250. return false;
  2251. }
  2252. }
  2253. const size_t offs = file_offset(ggml_get_name(cur));
  2254. if (use_mmap && mapping) {
  2255. if (buf_mmap && cur->data == nullptr) {
  2256. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2257. if (lmlock) {
  2258. lmlock->grow_to(offs + ggml_nbytes(cur));
  2259. }
  2260. mmap_used_first = std::min(mmap_used_first, offs);
  2261. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2262. } else {
  2263. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2264. }
  2265. } else {
  2266. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2267. file.seek(offs, SEEK_SET);
  2268. file.read_raw(cur->data, ggml_nbytes(cur));
  2269. } else {
  2270. read_buf.resize(ggml_nbytes(cur));
  2271. file.seek(offs, SEEK_SET);
  2272. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2273. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2274. }
  2275. }
  2276. size_done += ggml_nbytes(cur);
  2277. }
  2278. // check if this is the last call and do final cleanup
  2279. if (size_done >= size_data) {
  2280. // unmap offloaded tensors and metadata
  2281. if (use_mmap && mapping) {
  2282. mapping->unmap_fragment(0, mmap_used_first);
  2283. if (mmap_used_last != 0) {
  2284. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2285. }
  2286. }
  2287. if (progress_callback) {
  2288. // Even though the model is done loading, we still honor
  2289. // cancellation since we need to free allocations.
  2290. return progress_callback(1.0f, progress_callback_user_data);
  2291. }
  2292. }
  2293. return true;
  2294. }
  2295. };
  2296. //
  2297. // load LLaMA models
  2298. //
  2299. static std::string llama_model_arch_name(llm_arch arch) {
  2300. auto it = LLM_ARCH_NAMES.find(arch);
  2301. if (it == LLM_ARCH_NAMES.end()) {
  2302. return "unknown";
  2303. }
  2304. return it->second;
  2305. }
  2306. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2307. if (ftype & LLAMA_FTYPE_GUESSED) {
  2308. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2309. }
  2310. switch (ftype) {
  2311. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2312. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2313. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2314. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2315. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2316. return "Q4_1, some F16";
  2317. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2318. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2319. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2320. // K-quants
  2321. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2322. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2323. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2324. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2325. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2326. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2327. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2328. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2329. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2330. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2331. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2332. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2333. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2334. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2335. default: return "unknown, may not work";
  2336. }
  2337. }
  2338. static const char * llama_model_type_name(e_model type) {
  2339. switch (type) {
  2340. case MODEL_1B: return "1B";
  2341. case MODEL_3B: return "3B";
  2342. case MODEL_7B: return "7B";
  2343. case MODEL_8B: return "8B";
  2344. case MODEL_13B: return "13B";
  2345. case MODEL_14B: return "14B";
  2346. case MODEL_15B: return "15B";
  2347. case MODEL_30B: return "30B";
  2348. case MODEL_34B: return "34B";
  2349. case MODEL_40B: return "40B";
  2350. case MODEL_65B: return "65B";
  2351. case MODEL_70B: return "70B";
  2352. case MODEL_SMALL: return "0.1B";
  2353. case MODEL_MEDIUM: return "0.4B";
  2354. case MODEL_LARGE: return "0.8B";
  2355. case MODEL_XL: return "1.5B";
  2356. default: return "?B";
  2357. }
  2358. }
  2359. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2360. model.arch = ml.get_arch();
  2361. if (model.arch == LLM_ARCH_UNKNOWN) {
  2362. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2363. }
  2364. }
  2365. static void llm_load_hparams(
  2366. llama_model_loader & ml,
  2367. llama_model & model) {
  2368. auto & hparams = model.hparams;
  2369. const gguf_context * ctx = ml.ctx_gguf;
  2370. // get metadata as string
  2371. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2372. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2373. if (type == GGUF_TYPE_ARRAY) {
  2374. continue;
  2375. }
  2376. const char * name = gguf_get_key(ctx, i);
  2377. const std::string value = gguf_kv_to_str(ctx, i);
  2378. model.gguf_kv.emplace(name, value);
  2379. }
  2380. // get general kv
  2381. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2382. // get hparams kv
  2383. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2384. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2385. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2386. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2387. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2388. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2389. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2390. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2391. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2392. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2393. if (hparams.n_expert > 0) {
  2394. GGML_ASSERT(hparams.n_expert_used > 0);
  2395. } else {
  2396. GGML_ASSERT(hparams.n_expert_used == 0);
  2397. }
  2398. // n_head_kv is optional, default to n_head
  2399. hparams.n_head_kv = hparams.n_head;
  2400. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2401. bool rope_finetuned = false;
  2402. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2403. hparams.rope_finetuned = rope_finetuned;
  2404. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2405. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2406. // rope_freq_base (optional)
  2407. hparams.rope_freq_base_train = 10000.0f;
  2408. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2409. std::string rope_scaling("linear");
  2410. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2411. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2412. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2413. // rope_freq_scale (inverse of the kv) is optional
  2414. float ropescale = 0.0f;
  2415. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2416. // try the old key name
  2417. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2418. }
  2419. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2420. // sanity check for n_rot (optional)
  2421. {
  2422. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2423. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2424. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2425. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2426. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2427. }
  2428. }
  2429. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2430. // gpt-j n_rot = rotary_dim
  2431. }
  2432. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2433. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2434. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2435. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2436. // arch-specific KVs
  2437. switch (model.arch) {
  2438. case LLM_ARCH_LLAMA:
  2439. {
  2440. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2441. switch (hparams.n_layer) {
  2442. case 22: model.type = e_model::MODEL_1B; break;
  2443. case 26: model.type = e_model::MODEL_3B; break;
  2444. case 32: model.type = e_model::MODEL_7B; break;
  2445. case 40: model.type = e_model::MODEL_13B; break;
  2446. case 48: model.type = e_model::MODEL_34B; break;
  2447. case 60: model.type = e_model::MODEL_30B; break;
  2448. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2449. default: model.type = e_model::MODEL_UNKNOWN;
  2450. }
  2451. } break;
  2452. case LLM_ARCH_FALCON:
  2453. {
  2454. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2455. switch (hparams.n_layer) {
  2456. case 32: model.type = e_model::MODEL_7B; break;
  2457. case 60: model.type = e_model::MODEL_40B; break;
  2458. default: model.type = e_model::MODEL_UNKNOWN;
  2459. }
  2460. } break;
  2461. case LLM_ARCH_BAICHUAN:
  2462. {
  2463. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2464. switch (hparams.n_layer) {
  2465. case 32: model.type = e_model::MODEL_7B; break;
  2466. case 40: model.type = e_model::MODEL_13B; break;
  2467. default: model.type = e_model::MODEL_UNKNOWN;
  2468. }
  2469. } break;
  2470. case LLM_ARCH_STARCODER:
  2471. {
  2472. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2473. switch (hparams.n_layer) {
  2474. case 24: model.type = e_model::MODEL_1B; break;
  2475. case 36: model.type = e_model::MODEL_3B; break;
  2476. case 42: model.type = e_model::MODEL_7B; break;
  2477. case 40: model.type = e_model::MODEL_15B; break;
  2478. default: model.type = e_model::MODEL_UNKNOWN;
  2479. }
  2480. } break;
  2481. case LLM_ARCH_PERSIMMON:
  2482. {
  2483. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2484. switch (hparams.n_layer) {
  2485. case 36: model.type = e_model::MODEL_8B; break;
  2486. default: model.type = e_model::MODEL_UNKNOWN;
  2487. }
  2488. } break;
  2489. case LLM_ARCH_REFACT:
  2490. {
  2491. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2492. switch (hparams.n_layer) {
  2493. case 32: model.type = e_model::MODEL_1B; break;
  2494. default: model.type = e_model::MODEL_UNKNOWN;
  2495. }
  2496. } break;
  2497. case LLM_ARCH_BLOOM:
  2498. {
  2499. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2500. switch (hparams.n_layer) {
  2501. case 24: model.type = e_model::MODEL_1B; break;
  2502. case 30:
  2503. switch (hparams.n_embd) {
  2504. case 2560: model.type = e_model::MODEL_3B; break;
  2505. case 4096: model.type = e_model::MODEL_7B; break;
  2506. } break;
  2507. }
  2508. } break;
  2509. case LLM_ARCH_MPT:
  2510. {
  2511. hparams.f_clamp_kqv = 0.0f;
  2512. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2513. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2514. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2515. switch (hparams.n_layer) {
  2516. case 32: model.type = e_model::MODEL_7B; break;
  2517. case 48: model.type = e_model::MODEL_30B; break;
  2518. default: model.type = e_model::MODEL_UNKNOWN;
  2519. }
  2520. } break;
  2521. case LLM_ARCH_STABLELM:
  2522. {
  2523. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2524. switch (hparams.n_layer) {
  2525. case 24: model.type = e_model::MODEL_1B; break;
  2526. case 32: model.type = e_model::MODEL_3B; break;
  2527. default: model.type = e_model::MODEL_UNKNOWN;
  2528. }
  2529. } break;
  2530. case LLM_ARCH_QWEN:
  2531. {
  2532. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2533. switch (hparams.n_layer) {
  2534. case 32: model.type = e_model::MODEL_7B; break;
  2535. case 40: model.type = e_model::MODEL_13B; break;
  2536. default: model.type = e_model::MODEL_UNKNOWN;
  2537. }
  2538. } break;
  2539. case LLM_ARCH_QWEN2:
  2540. {
  2541. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2542. switch (hparams.n_layer) {
  2543. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2544. case 32: model.type = e_model::MODEL_7B; break;
  2545. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2546. case 80: model.type = e_model::MODEL_70B; break;
  2547. default: model.type = e_model::MODEL_UNKNOWN;
  2548. }
  2549. } break;
  2550. case LLM_ARCH_PHI2:
  2551. {
  2552. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2553. switch (hparams.n_layer) {
  2554. case 24: model.type = e_model::MODEL_1B; break;
  2555. case 32: model.type = e_model::MODEL_3B; break;
  2556. default: model.type = e_model::MODEL_UNKNOWN;
  2557. }
  2558. } break;
  2559. case LLM_ARCH_PLAMO:
  2560. {
  2561. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2562. switch (hparams.n_layer) {
  2563. case 40: model.type = e_model::MODEL_13B; break;
  2564. default: model.type = e_model::MODEL_UNKNOWN;
  2565. }
  2566. } break;
  2567. case LLM_ARCH_GPT2:
  2568. {
  2569. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2570. switch (hparams.n_layer) {
  2571. case 12: model.type = e_model::MODEL_SMALL; break;
  2572. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2573. case 36: model.type = e_model::MODEL_LARGE; break;
  2574. case 48: model.type = e_model::MODEL_XL; break;
  2575. default: model.type = e_model::MODEL_UNKNOWN;
  2576. }
  2577. } break;
  2578. case LLM_ARCH_CODESHELL:
  2579. {
  2580. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2581. switch (hparams.n_layer) {
  2582. case 42: model.type = e_model::MODEL_SMALL; break;
  2583. default: model.type = e_model::MODEL_UNKNOWN;
  2584. }
  2585. } break;
  2586. case LLM_ARCH_ORION:
  2587. {
  2588. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2589. switch (hparams.n_layer) {
  2590. case 40: model.type = e_model::MODEL_14B; break;
  2591. default: model.type = e_model::MODEL_UNKNOWN;
  2592. }
  2593. } break;
  2594. default: (void)0;
  2595. }
  2596. model.ftype = ml.ftype;
  2597. }
  2598. // TODO: This should probably be in llama.h
  2599. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2600. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2601. static void llm_load_vocab(
  2602. llama_model_loader & ml,
  2603. llama_model & model) {
  2604. auto & vocab = model.vocab;
  2605. struct gguf_context * ctx = ml.ctx_gguf;
  2606. const auto kv = LLM_KV(model.arch);
  2607. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2608. if (token_idx == -1) {
  2609. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2610. }
  2611. const float * scores = nullptr;
  2612. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2613. if (score_idx != -1) {
  2614. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2615. }
  2616. const int * toktypes = nullptr;
  2617. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2618. if (toktype_idx != -1) {
  2619. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2620. }
  2621. // determine vocab type
  2622. {
  2623. std::string tokenizer_name;
  2624. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2625. if (tokenizer_name == "llama") {
  2626. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2627. // default special tokens
  2628. vocab.special_bos_id = 1;
  2629. vocab.special_eos_id = 2;
  2630. vocab.special_unk_id = 0;
  2631. vocab.special_sep_id = -1;
  2632. vocab.special_pad_id = -1;
  2633. } else if (tokenizer_name == "gpt2") {
  2634. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2635. // read bpe merges and populate bpe ranks
  2636. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2637. if (merges_keyidx == -1) {
  2638. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2639. }
  2640. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2641. for (int i = 0; i < n_merges; i++) {
  2642. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2643. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2644. std::string first;
  2645. std::string second;
  2646. const size_t pos = word.find(' ', 1);
  2647. if (pos != std::string::npos) {
  2648. first = word.substr(0, pos);
  2649. second = word.substr(pos + 1);
  2650. }
  2651. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2652. }
  2653. // default special tokens
  2654. vocab.special_bos_id = 11;
  2655. vocab.special_eos_id = 11;
  2656. vocab.special_unk_id = -1;
  2657. vocab.special_sep_id = -1;
  2658. vocab.special_pad_id = -1;
  2659. } else {
  2660. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2661. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2662. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2663. }
  2664. }
  2665. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2666. vocab.id_to_token.resize(n_vocab);
  2667. for (uint32_t i = 0; i < n_vocab; i++) {
  2668. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2669. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2670. vocab.token_to_id[word] = i;
  2671. auto & token_data = vocab.id_to_token[i];
  2672. token_data.text = std::move(word);
  2673. token_data.score = scores ? scores[i] : 0.0f;
  2674. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2675. }
  2676. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2677. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2678. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2679. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2680. } else {
  2681. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2682. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2683. vocab.linefeed_id = ids[0];
  2684. }
  2685. // special tokens
  2686. {
  2687. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2688. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2689. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2690. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2691. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2692. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2693. };
  2694. for (const auto & it : special_token_types) {
  2695. const std::string & key = kv(std::get<0>(it));
  2696. int32_t & id = std::get<1>(it);
  2697. uint32_t new_id;
  2698. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2699. continue;
  2700. }
  2701. if (new_id >= vocab.id_to_token.size()) {
  2702. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2703. __func__, key.c_str(), new_id, id);
  2704. } else {
  2705. id = new_id;
  2706. }
  2707. }
  2708. // Handle add_bos_token and add_eos_token
  2709. {
  2710. bool temp = true;
  2711. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2712. vocab.special_add_bos = int(temp);
  2713. }
  2714. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2715. vocab.special_add_eos = int(temp);
  2716. }
  2717. }
  2718. }
  2719. // build special tokens cache
  2720. {
  2721. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2722. // and will always be correctly labeled in 'added_tokens.json' etc.
  2723. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2724. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2725. // are special tokens.
  2726. // From testing, this appears to correlate 1:1 with special tokens.
  2727. //
  2728. // Counting special tokens and verifying in only one direction
  2729. // is sufficient to detect difference in those two sets.
  2730. //
  2731. uint32_t special_tokens_count_by_type = 0;
  2732. uint32_t special_tokens_count_from_verification = 0;
  2733. bool special_tokens_definition_mismatch = false;
  2734. for (const auto & t : vocab.token_to_id) {
  2735. const auto & token = t.first;
  2736. const auto & id = t.second;
  2737. // Count all non-normal tokens in the vocab while iterating
  2738. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2739. special_tokens_count_by_type++;
  2740. }
  2741. // Skip single character tokens
  2742. if (token.length() > 1) {
  2743. bool is_tokenizable = false;
  2744. // Split token string representation in two, in all possible ways
  2745. // and check if both halves can be matched to a valid token
  2746. for (unsigned i = 1; i < token.length();) {
  2747. const auto left = token.substr(0, i);
  2748. const auto right = token.substr(i);
  2749. // check if we didnt partition in the middle of a utf sequence
  2750. auto utf = utf8_len(left.at(left.length() - 1));
  2751. if (utf == 1) {
  2752. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2753. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2754. is_tokenizable = true;
  2755. break;
  2756. }
  2757. i++;
  2758. } else {
  2759. // skip over the rest of multibyte utf sequence
  2760. i += utf - 1;
  2761. }
  2762. }
  2763. if (!is_tokenizable) {
  2764. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2765. // it's faster to re-filter them here, since there are way less candidates now
  2766. // Calculate a total "utf" length of a token string representation
  2767. size_t utf8_str_len = 0;
  2768. for (unsigned i = 0; i < token.length();) {
  2769. utf8_str_len++;
  2770. i += utf8_len(token.at(i));
  2771. }
  2772. // And skip the ones which are one character
  2773. if (utf8_str_len > 1) {
  2774. // At this point what we have left are special tokens only
  2775. vocab.special_tokens_cache[token] = id;
  2776. // Count manually found special tokens
  2777. special_tokens_count_from_verification++;
  2778. // If this manually found special token is not marked as such, flag a mismatch
  2779. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2780. special_tokens_definition_mismatch = true;
  2781. }
  2782. }
  2783. }
  2784. }
  2785. }
  2786. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2787. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2788. __func__,
  2789. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2790. special_tokens_count_by_type, vocab.id_to_token.size()
  2791. );
  2792. } else {
  2793. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2794. __func__,
  2795. special_tokens_count_from_verification, vocab.id_to_token.size()
  2796. );
  2797. }
  2798. }
  2799. }
  2800. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2801. const auto & hparams = model.hparams;
  2802. const auto & vocab = model.vocab;
  2803. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2804. // hparams
  2805. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2806. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2807. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2808. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2809. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2810. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2811. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2812. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2813. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2814. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2815. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2816. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2817. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2818. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2819. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2820. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2821. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2822. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2823. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2824. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2825. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2826. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2827. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2828. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2829. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2830. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2831. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2832. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2833. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2834. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2835. if (ml.n_elements >= 1e12) {
  2836. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2837. } else if (ml.n_elements >= 1e9) {
  2838. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2839. } else if (ml.n_elements >= 1e6) {
  2840. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2841. } else {
  2842. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2843. }
  2844. if (ml.n_bytes < GiB) {
  2845. 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);
  2846. } else {
  2847. 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);
  2848. }
  2849. // general kv
  2850. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2851. // special tokens
  2852. 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() ); }
  2853. 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() ); }
  2854. 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() ); }
  2855. 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() ); }
  2856. 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() ); }
  2857. 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() ); }
  2858. }
  2859. // Returns false if cancelled by progress_callback
  2860. static bool llm_load_tensors(
  2861. llama_model_loader & ml,
  2862. llama_model & model,
  2863. int n_gpu_layers,
  2864. enum llama_split_mode split_mode,
  2865. int main_gpu,
  2866. const float * tensor_split,
  2867. bool use_mlock,
  2868. llama_progress_callback progress_callback,
  2869. void * progress_callback_user_data) {
  2870. model.t_start_us = ggml_time_us();
  2871. auto & hparams = model.hparams;
  2872. model.split_mode = split_mode;
  2873. model.main_gpu = main_gpu;
  2874. model.n_gpu_layers = n_gpu_layers;
  2875. const int64_t n_layer = hparams.n_layer;
  2876. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2877. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2878. model.buft_input = llama_default_buffer_type_cpu(true);
  2879. model.buft_layer.resize(n_layer);
  2880. // assign cpu layers
  2881. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2882. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2883. }
  2884. #ifdef GGML_USE_CUBLAS
  2885. if (split_mode == LLAMA_SPLIT_LAYER) {
  2886. // calculate the split points
  2887. int device_count = ggml_backend_cuda_get_device_count();
  2888. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2889. float splits[GGML_CUDA_MAX_DEVICES];
  2890. if (all_zero) {
  2891. // default split, by free memory
  2892. for (int i = 0; i < device_count; ++i) {
  2893. size_t total;
  2894. size_t free;
  2895. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2896. splits[i] = free;
  2897. }
  2898. } else {
  2899. std::copy(tensor_split, tensor_split + device_count, splits);
  2900. }
  2901. // sum and normalize the splits to get the split points
  2902. float split_sum = 0.0f;
  2903. for (int i = 0; i < device_count; ++i) {
  2904. split_sum += splits[i];
  2905. splits[i] = split_sum;
  2906. }
  2907. for (int i = 0; i < device_count; ++i) {
  2908. splits[i] /= split_sum;
  2909. }
  2910. // assign the repeating layers to the devices according to the splits
  2911. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2912. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2913. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2914. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2915. }
  2916. // assign the output layer
  2917. if (n_gpu_layers > n_layer) {
  2918. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2919. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2920. } else {
  2921. model.buft_output = llama_default_buffer_type_cpu(true);
  2922. }
  2923. } else
  2924. #endif
  2925. {
  2926. ggml_backend_buffer_type_t split_buft;
  2927. if (split_mode == LLAMA_SPLIT_ROW) {
  2928. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2929. } else {
  2930. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2931. split_buft = llama_default_buffer_type_offload(main_gpu);
  2932. }
  2933. // assign the repeating layers
  2934. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2935. model.buft_layer[i] = {
  2936. split_buft,
  2937. llama_default_buffer_type_offload(main_gpu)
  2938. };
  2939. }
  2940. // assign the output layer
  2941. if (n_gpu_layers > n_layer) {
  2942. model.buft_output = {
  2943. split_buft,
  2944. llama_default_buffer_type_offload(main_gpu)
  2945. };
  2946. } else {
  2947. model.buft_output = llama_default_buffer_type_cpu(true);
  2948. }
  2949. }
  2950. // count used buffer types
  2951. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2952. buft_layer_count[model.buft_input.buft]++;
  2953. buft_layer_count[model.buft_input.buft_matrix]++;
  2954. buft_layer_count[model.buft_output.buft]++;
  2955. buft_layer_count[model.buft_output.buft_matrix]++;
  2956. for (int64_t i = 0; i < n_layer; ++i) {
  2957. buft_layer_count[model.buft_layer[i].buft]++;
  2958. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  2959. }
  2960. // create one context per buffer type
  2961. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  2962. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2963. for (auto & it : buft_layer_count) {
  2964. struct ggml_init_params params = {
  2965. /*.mem_size =*/ ctx_size,
  2966. /*.mem_buffer =*/ NULL,
  2967. /*.no_alloc =*/ true,
  2968. };
  2969. ggml_context * ctx = ggml_init(params);
  2970. if (!ctx) {
  2971. throw std::runtime_error(format("failed to create context"));
  2972. }
  2973. ctx_map[it.first] = ctx;
  2974. model.ctxs.push_back(ctx);
  2975. }
  2976. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  2977. // create tensors for the weights
  2978. {
  2979. const int64_t n_embd = hparams.n_embd;
  2980. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  2981. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  2982. const int64_t n_embd_gqa = n_embd_v_gqa;
  2983. const int64_t n_vocab = hparams.n_vocab;
  2984. const int64_t n_ff = hparams.n_ff;
  2985. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  2986. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  2987. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  2988. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  2989. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  2990. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  2991. model.layers.resize(n_layer);
  2992. const auto tn = LLM_TN(model.arch);
  2993. switch (model.arch) {
  2994. case LLM_ARCH_LLAMA:
  2995. case LLM_ARCH_REFACT:
  2996. {
  2997. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2998. // output
  2999. {
  3000. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3001. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3002. }
  3003. for (int i = 0; i < n_layer; ++i) {
  3004. ggml_context * ctx_layer = ctx_for_layer(i);
  3005. ggml_context * ctx_split = ctx_for_layer_split(i);
  3006. auto & layer = model.layers[i];
  3007. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3008. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3009. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3010. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3011. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3012. // optional bias tensors
  3013. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3014. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3015. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3016. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3017. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3018. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3019. if (layer.ffn_gate_inp == nullptr) {
  3020. GGML_ASSERT(hparams.n_expert == 0);
  3021. GGML_ASSERT(hparams.n_expert_used == 0);
  3022. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3023. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3024. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3025. } else {
  3026. GGML_ASSERT(hparams.n_expert > 0);
  3027. GGML_ASSERT(hparams.n_expert_used > 0);
  3028. // MoE branch
  3029. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3030. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3031. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3032. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3033. }
  3034. }
  3035. }
  3036. } break;
  3037. case LLM_ARCH_BAICHUAN:
  3038. {
  3039. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3040. {
  3041. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3042. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3043. }
  3044. for (int i = 0; i < n_layer; ++i) {
  3045. ggml_context * ctx_layer = ctx_for_layer(i);
  3046. ggml_context * ctx_split = ctx_for_layer_split(i);
  3047. auto & layer = model.layers[i];
  3048. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3049. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3050. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3051. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3052. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3053. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3054. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3055. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3056. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3057. }
  3058. } break;
  3059. case LLM_ARCH_FALCON:
  3060. {
  3061. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3062. // output
  3063. {
  3064. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3065. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3066. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3067. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3068. } else {
  3069. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3070. ml.n_created--; // artificial tensor
  3071. }
  3072. }
  3073. for (int i = 0; i < n_layer; ++i) {
  3074. ggml_context * ctx_layer = ctx_for_layer(i);
  3075. ggml_context * ctx_split = ctx_for_layer_split(i);
  3076. auto & layer = model.layers[i];
  3077. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3078. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3079. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3080. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3081. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3082. }
  3083. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3084. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3085. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3086. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3087. }
  3088. } break;
  3089. case LLM_ARCH_STARCODER:
  3090. {
  3091. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3092. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3093. // output
  3094. {
  3095. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3096. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3097. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3098. }
  3099. for (int i = 0; i < n_layer; ++i) {
  3100. ggml_context * ctx_layer = ctx_for_layer(i);
  3101. ggml_context * ctx_split = ctx_for_layer_split(i);
  3102. auto & layer = model.layers[i];
  3103. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3104. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3105. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3106. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3107. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3108. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3109. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3110. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3111. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3112. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3113. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3114. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3115. }
  3116. } break;
  3117. case LLM_ARCH_PERSIMMON:
  3118. {
  3119. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3120. {
  3121. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3122. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3123. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3124. }
  3125. for (int i = 0; i < n_layer; ++i) {
  3126. ggml_context * ctx_layer = ctx_for_layer(i);
  3127. ggml_context * ctx_split = ctx_for_layer_split(i);
  3128. auto & layer = model.layers[i];
  3129. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3130. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3131. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3132. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3133. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3134. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3135. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3136. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3137. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3138. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3139. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3140. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3141. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3142. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3143. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3144. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3145. }
  3146. } break;
  3147. case LLM_ARCH_BLOOM:
  3148. {
  3149. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3150. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3151. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3152. // output
  3153. {
  3154. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3155. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3156. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3157. }
  3158. for (int i = 0; i < n_layer; ++i) {
  3159. ggml_context * ctx_layer = ctx_for_layer(i);
  3160. ggml_context * ctx_split = ctx_for_layer_split(i);
  3161. auto & layer = model.layers[i];
  3162. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3163. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3164. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3165. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3166. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3167. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3168. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3169. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3170. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3171. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3172. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3173. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3174. }
  3175. } break;
  3176. case LLM_ARCH_MPT:
  3177. {
  3178. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3179. // output
  3180. {
  3181. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3182. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3183. }
  3184. for (int i = 0; i < n_layer; ++i) {
  3185. ggml_context * ctx_layer = ctx_for_layer(i);
  3186. ggml_context * ctx_split = ctx_for_layer_split(i);
  3187. auto & layer = model.layers[i];
  3188. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3189. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3190. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3191. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3192. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3193. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3194. // AWQ ScaleActivation layer
  3195. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3196. }
  3197. } break;
  3198. case LLM_ARCH_STABLELM:
  3199. {
  3200. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3201. // output
  3202. {
  3203. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3204. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3205. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3206. }
  3207. for (int i = 0; i < n_layer; ++i) {
  3208. ggml_context * ctx_layer = ctx_for_layer(i);
  3209. ggml_context * ctx_split = ctx_for_layer_split(i);
  3210. auto & layer = model.layers[i];
  3211. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3212. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3213. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3214. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3215. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3216. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3217. // optional bias tensors, present in Stable LM 2 1.6B
  3218. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3219. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3220. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3221. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3222. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3223. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3224. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3225. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3226. }
  3227. } break;
  3228. case LLM_ARCH_QWEN:
  3229. {
  3230. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3231. // output
  3232. {
  3233. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3234. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3235. }
  3236. for (int i = 0; i < n_layer; ++i) {
  3237. ggml_context * ctx_layer = ctx_for_layer(i);
  3238. ggml_context * ctx_split = ctx_for_layer_split(i);
  3239. auto & layer = model.layers[i];
  3240. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3241. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3242. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3243. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3244. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3245. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3246. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3247. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3248. }
  3249. } break;
  3250. case LLM_ARCH_QWEN2:
  3251. {
  3252. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3253. // output
  3254. {
  3255. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3256. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3257. }
  3258. for (int i = 0; i < n_layer; ++i) {
  3259. ggml_context * ctx_layer = ctx_for_layer(i);
  3260. ggml_context * ctx_split = ctx_for_layer_split(i);
  3261. auto & layer = model.layers[i];
  3262. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3263. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3264. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3265. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3266. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3267. // optional bias tensors
  3268. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3269. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3270. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3271. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3272. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3273. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3274. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3275. }
  3276. } break;
  3277. case LLM_ARCH_PHI2:
  3278. {
  3279. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3280. // output
  3281. {
  3282. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3283. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3284. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3285. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3286. }
  3287. for (int i = 0; i < n_layer; ++i) {
  3288. ggml_context * ctx_layer = ctx_for_layer(i);
  3289. ggml_context * ctx_split = ctx_for_layer_split(i);
  3290. auto & layer = model.layers[i];
  3291. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3292. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3293. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3294. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3295. if (layer.wqkv == nullptr) {
  3296. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3297. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3298. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3299. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3300. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3301. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3302. }
  3303. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3304. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3305. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3306. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3307. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3308. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3309. }
  3310. } break;
  3311. case LLM_ARCH_PLAMO:
  3312. {
  3313. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3314. // output
  3315. {
  3316. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3317. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3318. }
  3319. for (int i = 0; i < n_layer; ++i) {
  3320. ggml_context * ctx_layer = ctx_for_layer(i);
  3321. ggml_context * ctx_split = ctx_for_layer_split(i);
  3322. auto & layer = model.layers[i];
  3323. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3324. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3325. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3326. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3327. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3328. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3329. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3330. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3331. }
  3332. } break;
  3333. case LLM_ARCH_GPT2:
  3334. {
  3335. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3336. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3337. // output
  3338. {
  3339. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3340. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3341. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3342. }
  3343. for (int i = 0; i < n_layer; ++i) {
  3344. ggml_context * ctx_layer = ctx_for_layer(i);
  3345. ggml_context * ctx_split = ctx_for_layer_split(i);
  3346. auto & layer = model.layers[i];
  3347. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3348. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3349. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3350. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3351. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3352. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3353. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3354. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3355. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3356. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3357. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3358. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3359. }
  3360. } break;
  3361. case LLM_ARCH_CODESHELL:
  3362. {
  3363. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3364. // output
  3365. {
  3366. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3367. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3368. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3369. }
  3370. for (int i = 0; i < n_layer; ++i) {
  3371. ggml_context * ctx_layer = ctx_for_layer(i);
  3372. ggml_context * ctx_split = ctx_for_layer_split(i);
  3373. auto & layer = model.layers[i];
  3374. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3375. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3376. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3377. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3378. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3379. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3380. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3381. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3382. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3383. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3384. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3385. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3386. }
  3387. } break;
  3388. case LLM_ARCH_ORION:
  3389. {
  3390. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3391. {
  3392. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3393. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3394. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3395. }
  3396. for (int i = 0; i < n_layer; ++i) {
  3397. ggml_context * ctx_layer = ctx_for_layer(i);
  3398. ggml_context * ctx_split = ctx_for_layer_split(i);
  3399. auto & layer = model.layers[i];
  3400. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3401. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3402. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3403. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3404. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3405. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3406. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3407. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3408. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3409. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3410. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3411. }
  3412. } break;
  3413. default:
  3414. throw std::runtime_error("unknown architecture");
  3415. }
  3416. }
  3417. ml.done_getting_tensors();
  3418. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3419. // create the backend buffers
  3420. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3421. for (auto & it : ctx_map) {
  3422. ggml_backend_buffer_type_t buft = it.first;
  3423. ggml_context * ctx = it.second;
  3424. ggml_backend_buffer_t buf = nullptr;
  3425. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3426. // this is important for metal with apple silicon: if the entire model could be mapped to a metal buffer, then we could just use metal for all layers
  3427. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3428. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3429. size_t first, last;
  3430. ml.get_mapping_range(&first, &last, ctx);
  3431. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3432. }
  3433. #ifdef GGML_USE_METAL
  3434. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3435. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3436. size_t first, last;
  3437. ml.get_mapping_range(&first, &last, ctx);
  3438. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3439. }
  3440. #endif
  3441. else {
  3442. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3443. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3444. model.mlock_bufs.emplace_back(new llama_mlock);
  3445. auto & mlock_buf = model.mlock_bufs.back();
  3446. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3447. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3448. }
  3449. }
  3450. if (buf == nullptr) {
  3451. throw std::runtime_error("failed to allocate buffer");
  3452. }
  3453. // indicate that this buffer contains weights
  3454. // this is used by ggml_backend_sched to improve op scheduling -> ops that use a weight are preferably scheduled to the backend that contains the weight
  3455. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3456. model.bufs.push_back(buf);
  3457. ctx_bufs.emplace_back(ctx, buf);
  3458. }
  3459. // print memory requirements
  3460. {
  3461. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3462. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3463. if (n_gpu_layers > (int) hparams.n_layer) {
  3464. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3465. }
  3466. const int max_backend_supported_layers = hparams.n_layer + 1;
  3467. const int max_offloadable_layers = hparams.n_layer + 1;
  3468. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3469. for (ggml_backend_buffer_t buf : model.bufs) {
  3470. LLAMA_LOG_INFO("%s: %10s buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  3471. }
  3472. }
  3473. // populate tensors_by_name
  3474. for (ggml_context * ctx : model.ctxs) {
  3475. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3476. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3477. }
  3478. }
  3479. // load tensor data
  3480. for (auto & it : ctx_bufs) {
  3481. ggml_context * ctx = it.first;
  3482. ggml_backend_buffer_t buf = it.second;
  3483. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3484. return false;
  3485. }
  3486. }
  3487. model.mapping = std::move(ml.mapping);
  3488. // loading time will be recalculate after the first eval, so
  3489. // we take page faults deferred by mmap() into consideration
  3490. model.t_load_us = ggml_time_us() - model.t_start_us;
  3491. return true;
  3492. }
  3493. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3494. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3495. try {
  3496. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3497. model.hparams.vocab_only = params.vocab_only;
  3498. llm_load_arch (ml, model);
  3499. llm_load_hparams(ml, model);
  3500. llm_load_vocab (ml, model);
  3501. llm_load_print_meta(ml, model);
  3502. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3503. throw std::runtime_error("vocab size mismatch");
  3504. }
  3505. if (params.vocab_only) {
  3506. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3507. return 0;
  3508. }
  3509. #ifdef GGML_USE_KOMPUTE
  3510. if (params.n_gpu_layers > 0 && (
  3511. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3512. || !(
  3513. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3514. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3515. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3516. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3517. )
  3518. )) {
  3519. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3520. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3521. params.n_gpu_layers = 0;
  3522. }
  3523. #endif
  3524. if (!llm_load_tensors(
  3525. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3526. params.progress_callback, params.progress_callback_user_data
  3527. )) {
  3528. return -2;
  3529. }
  3530. } catch (const std::exception & err) {
  3531. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3532. return -1;
  3533. }
  3534. return 0;
  3535. }
  3536. //
  3537. // llm_build
  3538. //
  3539. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3540. enum llm_rope_type {
  3541. LLM_ROPE,
  3542. LLM_ROPE_NEOX,
  3543. LLM_ROPE_GLM,
  3544. };
  3545. enum llm_ffn_op_type {
  3546. LLM_FFN_SILU,
  3547. LLM_FFN_GELU,
  3548. LLM_FFN_RELU,
  3549. LLM_FFN_RELU_SQR,
  3550. };
  3551. enum llm_ffn_gate_type {
  3552. LLM_FFN_SEQ,
  3553. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3554. };
  3555. enum llm_norm_type {
  3556. LLM_NORM,
  3557. LLM_NORM_RMS,
  3558. };
  3559. static struct ggml_tensor * llm_build_inp_embd(
  3560. struct ggml_context * ctx,
  3561. const llama_hparams & hparams,
  3562. const llama_batch & batch,
  3563. struct ggml_tensor * tok_embd,
  3564. struct ggml_tensor * inp_tokens,
  3565. struct ggml_tensor * inp_embd,
  3566. const llm_build_cb & cb) {
  3567. const int64_t n_embd = hparams.n_embd;
  3568. struct ggml_tensor * inpL;
  3569. if (batch.token) {
  3570. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3571. cb(inp_tokens, "inp_tokens", -1);
  3572. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3573. } else {
  3574. #ifdef GGML_USE_MPI
  3575. GGML_ASSERT(false && "not implemented");
  3576. #endif
  3577. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3578. }
  3579. return inpL;
  3580. }
  3581. // Persimmon: n_rot = n_embd_head_k/2
  3582. // Other: n_rot = n_embd_head_k
  3583. static void llm_build_k_shift(
  3584. struct ggml_context * ctx,
  3585. const llama_hparams & hparams,
  3586. const llama_cparams & cparams,
  3587. const llama_kv_cache & kv,
  3588. struct ggml_cgraph * graph,
  3589. struct ggml_tensor * K_shift,
  3590. llm_rope_type type,
  3591. int64_t n_ctx,
  3592. float freq_base,
  3593. float freq_scale,
  3594. const llm_build_cb & cb) {
  3595. const int64_t n_layer = hparams.n_layer;
  3596. const int64_t n_head_kv = hparams.n_head_kv;
  3597. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3598. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3599. const int32_t n_rot = hparams.n_rot;
  3600. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3601. const float ext_factor = cparams.yarn_ext_factor;
  3602. const float attn_factor = cparams.yarn_attn_factor;
  3603. const float beta_fast = cparams.yarn_beta_fast;
  3604. const float beta_slow = cparams.yarn_beta_slow;
  3605. int rope_type = 0;
  3606. switch (type) {
  3607. case LLM_ROPE: rope_type = 0; break;
  3608. case LLM_ROPE_NEOX: rope_type = 2; break;
  3609. case LLM_ROPE_GLM: rope_type = 4; break;
  3610. }
  3611. for (int il = 0; il < n_layer; ++il) {
  3612. struct ggml_tensor * tmp =
  3613. // we rotate only the first n_rot dimensions
  3614. ggml_rope_custom_inplace(ctx,
  3615. ggml_view_3d(ctx, kv.k_l[il],
  3616. n_embd_head_k, n_head_kv, n_ctx,
  3617. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3618. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3619. 0),
  3620. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3621. ext_factor, attn_factor, beta_fast, beta_slow);
  3622. cb(tmp, "K_shifted", il);
  3623. ggml_build_forward_expand(graph, tmp);
  3624. }
  3625. }
  3626. static void llm_build_kv_store(
  3627. struct ggml_context * ctx,
  3628. const llama_hparams & hparams,
  3629. const llama_kv_cache & kv,
  3630. struct ggml_cgraph * graph,
  3631. struct ggml_tensor * k_cur,
  3632. struct ggml_tensor * v_cur,
  3633. int64_t n_ctx,
  3634. int32_t n_tokens,
  3635. int32_t kv_head,
  3636. const llm_build_cb & cb,
  3637. int64_t il) {
  3638. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3639. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3640. // compute the transposed [n_tokens, n_embd] V matrix
  3641. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3642. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3643. cb(v_cur_t, "v_cur_t", il);
  3644. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3645. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3646. cb(k_cache_view, "k_cache_view", il);
  3647. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3648. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3649. (kv_head)*ggml_element_size(kv.v_l[il]));
  3650. cb(v_cache_view, "v_cache_view", il);
  3651. // important: storing RoPE-ed version of K in the KV cache!
  3652. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3653. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3654. }
  3655. static struct ggml_tensor * llm_build_norm(
  3656. struct ggml_context * ctx,
  3657. struct ggml_tensor * cur,
  3658. const llama_hparams & hparams,
  3659. struct ggml_tensor * mw,
  3660. struct ggml_tensor * mb,
  3661. llm_norm_type type,
  3662. const llm_build_cb & cb,
  3663. int il) {
  3664. switch (type) {
  3665. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3666. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3667. }
  3668. if (mw || mb) {
  3669. cb(cur, "norm", il);
  3670. }
  3671. if (mw) {
  3672. cur = ggml_mul(ctx, cur, mw);
  3673. if (mb) {
  3674. cb(cur, "norm_w", il);
  3675. }
  3676. }
  3677. if (mb) {
  3678. cur = ggml_add(ctx, cur, mb);
  3679. }
  3680. return cur;
  3681. }
  3682. static struct ggml_tensor * llm_build_ffn(
  3683. struct ggml_context * ctx,
  3684. struct ggml_tensor * cur,
  3685. struct ggml_tensor * up,
  3686. struct ggml_tensor * up_b,
  3687. struct ggml_tensor * gate,
  3688. struct ggml_tensor * gate_b,
  3689. struct ggml_tensor * down,
  3690. struct ggml_tensor * down_b,
  3691. struct ggml_tensor * act_scales,
  3692. llm_ffn_op_type type_op,
  3693. llm_ffn_gate_type type_gate,
  3694. const llm_build_cb & cb,
  3695. int il) {
  3696. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3697. cb(tmp, "ffn_up", il);
  3698. if (up_b) {
  3699. tmp = ggml_add(ctx, tmp, up_b);
  3700. cb(tmp, "ffn_up_b", il);
  3701. }
  3702. if (gate) {
  3703. switch (type_gate) {
  3704. case LLM_FFN_SEQ:
  3705. {
  3706. cur = ggml_mul_mat(ctx, gate, tmp);
  3707. cb(cur, "ffn_gate", il);
  3708. } break;
  3709. case LLM_FFN_PAR:
  3710. {
  3711. cur = ggml_mul_mat(ctx, gate, cur);
  3712. cb(cur, "ffn_gate", il);
  3713. } break;
  3714. }
  3715. if (gate_b) {
  3716. cur = ggml_add(ctx, cur, gate_b);
  3717. cb(cur, "ffn_gate_b", il);
  3718. }
  3719. } else {
  3720. cur = tmp;
  3721. }
  3722. switch (type_op) {
  3723. case LLM_FFN_SILU:
  3724. {
  3725. cur = ggml_silu(ctx, cur);
  3726. cb(cur, "ffn_silu", il);
  3727. } break;
  3728. case LLM_FFN_GELU:
  3729. {
  3730. cur = ggml_gelu(ctx, cur);
  3731. cb(cur, "ffn_gelu", il);
  3732. if (act_scales != NULL) {
  3733. cur = ggml_div(ctx, cur, act_scales);
  3734. cb(cur, "ffn_act", il);
  3735. }
  3736. } break;
  3737. case LLM_FFN_RELU:
  3738. {
  3739. cur = ggml_relu(ctx, cur);
  3740. cb(cur, "ffn_relu", il);
  3741. } break;
  3742. case LLM_FFN_RELU_SQR:
  3743. {
  3744. cur = ggml_relu(ctx, cur);
  3745. cb(cur, "ffn_relu", il);
  3746. cur = ggml_sqr(ctx, cur);
  3747. cb(cur, "ffn_sqr(relu)", il);
  3748. } break;
  3749. }
  3750. if (type_gate == LLM_FFN_PAR) {
  3751. cur = ggml_mul(ctx, cur, tmp);
  3752. cb(cur, "ffn_gate_par", il);
  3753. }
  3754. cur = ggml_mul_mat(ctx, down, cur);
  3755. if (down_b) {
  3756. cb(cur, "ffn_down", il);
  3757. }
  3758. if (down_b) {
  3759. cur = ggml_add(ctx, cur, down_b);
  3760. }
  3761. return cur;
  3762. }
  3763. // if max_alibi_bias > 0 then apply ALiBi
  3764. static struct ggml_tensor * llm_build_kqv(
  3765. struct ggml_context * ctx,
  3766. const llama_model & model,
  3767. const llama_hparams & hparams,
  3768. const llama_kv_cache & kv,
  3769. struct ggml_cgraph * graph,
  3770. struct ggml_tensor * wo,
  3771. struct ggml_tensor * wo_b,
  3772. struct ggml_tensor * q_cur,
  3773. struct ggml_tensor * kq_mask,
  3774. int64_t n_ctx,
  3775. int32_t n_tokens,
  3776. int32_t n_kv,
  3777. float max_alibi_bias,
  3778. float kq_scale,
  3779. const llm_build_cb & cb,
  3780. int il) {
  3781. const int64_t n_head = hparams.n_head;
  3782. const int64_t n_head_kv = hparams.n_head_kv;
  3783. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3784. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3785. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3786. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3787. cb(q, "q", il);
  3788. struct ggml_tensor * k =
  3789. ggml_view_3d(ctx, kv.k_l[il],
  3790. n_embd_head_k, n_kv, n_head_kv,
  3791. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3792. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3793. 0);
  3794. cb(k, "k", il);
  3795. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3796. cb(kq, "kq", il);
  3797. if (model.arch == LLM_ARCH_PHI2) {
  3798. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3799. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3800. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3801. }
  3802. if (max_alibi_bias > 0.0f) {
  3803. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3804. kq = ggml_scale(ctx, kq, kq_scale);
  3805. cb(kq, "kq_scaled", il);
  3806. if (max_alibi_bias > 0.0f) {
  3807. // TODO: n_head or n_head_kv
  3808. // TODO: K-shift is likely not working
  3809. // TODO: change to ggml_add
  3810. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3811. cb(kq, "kq_scaled_alibi", il);
  3812. }
  3813. kq = ggml_add(ctx, kq, kq_mask);
  3814. cb(kq, "kq_masked", il);
  3815. kq = ggml_soft_max(ctx, kq);
  3816. cb(kq, "kq_soft_max", il);
  3817. } else {
  3818. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3819. cb(kq, "kq_soft_max_ext", il);
  3820. }
  3821. // split cached v into n_head heads
  3822. struct ggml_tensor * v =
  3823. ggml_view_3d(ctx, kv.v_l[il],
  3824. n_kv, n_embd_head_v, n_head_kv,
  3825. ggml_element_size(kv.v_l[il])*n_ctx,
  3826. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3827. 0);
  3828. cb(v, "v", il);
  3829. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3830. cb(kqv, "kqv", il);
  3831. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3832. cb(kqv_merged, "kqv_merged", il);
  3833. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3834. cb(cur, "kqv_merged_cont", il);
  3835. ggml_build_forward_expand(graph, cur);
  3836. cur = ggml_mul_mat(ctx, wo, cur);
  3837. if (wo_b) {
  3838. cb(cur, "kqv_wo", il);
  3839. }
  3840. if (wo_b) {
  3841. cur = ggml_add(ctx, cur, wo_b);
  3842. }
  3843. return cur;
  3844. }
  3845. static struct ggml_tensor * llm_build_kv(
  3846. struct ggml_context * ctx,
  3847. const llama_model & model,
  3848. const llama_hparams & hparams,
  3849. const llama_kv_cache & kv,
  3850. struct ggml_cgraph * graph,
  3851. struct ggml_tensor * wo,
  3852. struct ggml_tensor * wo_b,
  3853. struct ggml_tensor * k_cur,
  3854. struct ggml_tensor * v_cur,
  3855. struct ggml_tensor * q_cur,
  3856. struct ggml_tensor * kq_mask,
  3857. int64_t n_ctx,
  3858. int32_t n_tokens,
  3859. int32_t kv_head,
  3860. int32_t n_kv,
  3861. float max_alibi_bias,
  3862. float kq_scale,
  3863. const llm_build_cb & cb,
  3864. int il) {
  3865. // these nodes are added to the graph together so that they are not reordered
  3866. // by doing so, the number of splits in the graph is reduced
  3867. ggml_build_forward_expand(graph, q_cur);
  3868. ggml_build_forward_expand(graph, k_cur);
  3869. ggml_build_forward_expand(graph, v_cur);
  3870. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  3871. struct ggml_tensor * cur;
  3872. cur = llm_build_kqv(ctx, model, hparams, kv, graph,
  3873. wo, wo_b,
  3874. q_cur, kq_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, kq_scale, cb, il);
  3875. cb(cur, "kqv_out", il);
  3876. return cur;
  3877. }
  3878. struct llm_build_context {
  3879. const llama_model & model;
  3880. const llama_context & lctx;
  3881. const llama_hparams & hparams;
  3882. const llama_cparams & cparams;
  3883. const llama_batch & batch;
  3884. const llama_kv_cache & kv_self;
  3885. const int64_t n_embd;
  3886. const int64_t n_layer;
  3887. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3888. const int64_t n_head;
  3889. const int64_t n_head_kv;
  3890. const int64_t n_embd_head_k;
  3891. const int64_t n_embd_k_gqa;
  3892. const int64_t n_embd_head_v;
  3893. const int64_t n_embd_v_gqa;
  3894. const int64_t n_expert;
  3895. const int64_t n_expert_used;
  3896. const float freq_base;
  3897. const float freq_scale;
  3898. const float ext_factor;
  3899. const float attn_factor;
  3900. const float beta_fast;
  3901. const float beta_slow;
  3902. const float norm_eps;
  3903. const float norm_rms_eps;
  3904. const int32_t n_tokens;
  3905. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3906. const int32_t kv_head; // index of where we store new KV data in the cache
  3907. const int32_t n_orig_ctx;
  3908. const bool do_rope_shift;
  3909. const llm_build_cb & cb;
  3910. std::vector<uint8_t> & buf_compute_meta;
  3911. struct ggml_context * ctx0 = nullptr;
  3912. // TODO: consider making the entire interface noexcept
  3913. llm_build_context(
  3914. llama_context & lctx,
  3915. const llama_batch & batch,
  3916. const llm_build_cb & cb,
  3917. bool worst_case) :
  3918. model (lctx.model),
  3919. lctx (lctx),
  3920. hparams (model.hparams),
  3921. cparams (lctx.cparams),
  3922. batch (batch),
  3923. kv_self (lctx.kv_self),
  3924. n_embd (hparams.n_embd),
  3925. n_layer (hparams.n_layer),
  3926. n_ctx (cparams.n_ctx),
  3927. n_head (hparams.n_head),
  3928. n_head_kv (hparams.n_head_kv),
  3929. n_embd_head_k (hparams.n_embd_head_k),
  3930. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3931. n_embd_head_v (hparams.n_embd_head_v),
  3932. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  3933. n_expert (hparams.n_expert),
  3934. n_expert_used (hparams.n_expert_used),
  3935. freq_base (cparams.rope_freq_base),
  3936. freq_scale (cparams.rope_freq_scale),
  3937. ext_factor (cparams.yarn_ext_factor),
  3938. attn_factor (cparams.yarn_attn_factor),
  3939. beta_fast (cparams.yarn_beta_fast),
  3940. beta_slow (cparams.yarn_beta_slow),
  3941. norm_eps (hparams.f_norm_eps),
  3942. norm_rms_eps (hparams.f_norm_rms_eps),
  3943. n_tokens (batch.n_tokens),
  3944. n_kv (worst_case ? n_ctx : kv_self.n),
  3945. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3946. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3947. do_rope_shift (worst_case || kv_self.has_shift),
  3948. cb (cb),
  3949. buf_compute_meta (lctx.buf_compute_meta) {
  3950. // all initializations should be done in init()
  3951. }
  3952. void init() {
  3953. struct ggml_init_params params = {
  3954. /*.mem_size =*/ buf_compute_meta.size(),
  3955. /*.mem_buffer =*/ buf_compute_meta.data(),
  3956. /*.no_alloc =*/ true,
  3957. };
  3958. ctx0 = ggml_init(params);
  3959. }
  3960. void free() {
  3961. if (ctx0) {
  3962. ggml_free(ctx0);
  3963. ctx0 = nullptr;
  3964. }
  3965. }
  3966. struct ggml_cgraph * build_orion() {
  3967. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3968. const int64_t n_embd_head = hparams.n_embd_head_v;
  3969. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3970. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3971. struct ggml_tensor * cur;
  3972. struct ggml_tensor * inpL;
  3973. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  3974. cb(inpL, "inp_embd", -1);
  3975. // inp_pos - contains the positions
  3976. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  3977. cb(inp_pos, "inp_pos", -1);
  3978. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3979. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  3980. cb(KQ_mask, "KQ_mask", -1);
  3981. // shift the entire K-cache if needed
  3982. if (do_rope_shift) {
  3983. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3984. }
  3985. for (int il = 0; il < n_layer; ++il) {
  3986. struct ggml_tensor * inpSA = inpL;
  3987. // norm
  3988. cur = llm_build_norm(ctx0, inpL, hparams,
  3989. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  3990. LLM_NORM, cb, il);
  3991. cb(cur, "attn_norm", il);
  3992. // self-attention
  3993. {
  3994. // compute Q and K and RoPE them
  3995. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3996. cb(Qcur, "Qcur", il);
  3997. // if (model.layers[il].bq) {
  3998. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3999. // cb(Qcur, "Qcur", il);
  4000. // }
  4001. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4002. cb(Kcur, "Kcur", il);
  4003. // if (model.layers[il].bk) {
  4004. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4005. // cb(Kcur, "Kcur", il);
  4006. // }
  4007. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4008. cb(Vcur, "Vcur", il);
  4009. // if (model.layers[il].bv) {
  4010. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4011. // cb(Vcur, "Vcur", il);
  4012. // }
  4013. Qcur = ggml_rope_custom(
  4014. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4015. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4016. ext_factor, attn_factor, beta_fast, beta_slow
  4017. );
  4018. cb(Qcur, "Qcur", il);
  4019. Kcur = ggml_rope_custom(
  4020. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4021. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4022. ext_factor, attn_factor, beta_fast, beta_slow
  4023. );
  4024. cb(Kcur, "Kcur", il);
  4025. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4026. model.layers[il].wo, NULL,
  4027. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4028. cb(cur, "kqv_out", il);
  4029. }
  4030. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4031. cb(ffn_inp, "ffn_inp", il);
  4032. // feed-forward network
  4033. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4034. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  4035. LLM_NORM, cb, il);
  4036. cb(cur, "ffn_norm", il);
  4037. cur = llm_build_ffn(ctx0, cur,
  4038. model.layers[il].ffn_up, NULL,
  4039. model.layers[il].ffn_gate, NULL,
  4040. model.layers[il].ffn_down, NULL,
  4041. NULL,
  4042. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4043. cb(cur, "ffn_out", il);
  4044. cur = ggml_add(ctx0, cur, ffn_inp);
  4045. cb(cur, "l_out", il);
  4046. // input for next layer
  4047. inpL = cur;
  4048. }
  4049. cur = inpL;
  4050. cur = llm_build_norm(ctx0, cur, hparams,
  4051. model.output_norm, model.output_norm_b,
  4052. LLM_NORM, cb, -1);
  4053. cb(cur, "result_norm", -1);
  4054. // lm_head
  4055. cur = ggml_mul_mat(ctx0, model.output, cur);
  4056. cb(cur, "result_output", -1);
  4057. ggml_build_forward_expand(gf, cur);
  4058. return gf;
  4059. }
  4060. struct ggml_cgraph * build_llama() {
  4061. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4062. const int64_t n_embd_head = hparams.n_embd_head_v;
  4063. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4064. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4065. struct ggml_tensor * cur;
  4066. struct ggml_tensor * inpL;
  4067. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4068. cb(inpL, "inp_embd", -1);
  4069. // inp_pos - contains the positions
  4070. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4071. cb(inp_pos, "inp_pos", -1);
  4072. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4073. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4074. cb(KQ_mask, "KQ_mask", -1);
  4075. // shift the entire K-cache if needed
  4076. if (do_rope_shift) {
  4077. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4078. }
  4079. for (int il = 0; il < n_layer; ++il) {
  4080. struct ggml_tensor * inpSA = inpL;
  4081. // norm
  4082. cur = llm_build_norm(ctx0, inpL, hparams,
  4083. model.layers[il].attn_norm, NULL,
  4084. LLM_NORM_RMS, cb, il);
  4085. cb(cur, "attn_norm", il);
  4086. // self-attention
  4087. {
  4088. // compute Q and K and RoPE them
  4089. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4090. cb(Qcur, "Qcur", il);
  4091. if (model.layers[il].bq) {
  4092. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4093. cb(Qcur, "Qcur", il);
  4094. }
  4095. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4096. cb(Kcur, "Kcur", il);
  4097. if (model.layers[il].bk) {
  4098. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4099. cb(Kcur, "Kcur", il);
  4100. }
  4101. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4102. cb(Vcur, "Vcur", il);
  4103. if (model.layers[il].bv) {
  4104. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4105. cb(Vcur, "Vcur", il);
  4106. }
  4107. Qcur = ggml_rope_custom(
  4108. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4109. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4110. ext_factor, attn_factor, beta_fast, beta_slow
  4111. );
  4112. cb(Qcur, "Qcur", il);
  4113. Kcur = ggml_rope_custom(
  4114. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4115. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4116. ext_factor, attn_factor, beta_fast, beta_slow
  4117. );
  4118. cb(Kcur, "Kcur", il);
  4119. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4120. model.layers[il].wo, model.layers[il].bo,
  4121. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4122. cb(cur, "kqv_out", il);
  4123. }
  4124. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4125. cb(ffn_inp, "ffn_inp", il);
  4126. // feed-forward network
  4127. if (model.layers[il].ffn_gate_inp == nullptr) {
  4128. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4129. model.layers[il].ffn_norm, NULL,
  4130. LLM_NORM_RMS, cb, il);
  4131. cb(cur, "ffn_norm", il);
  4132. cur = llm_build_ffn(ctx0, cur,
  4133. model.layers[il].ffn_up, NULL,
  4134. model.layers[il].ffn_gate, NULL,
  4135. model.layers[il].ffn_down, NULL,
  4136. NULL,
  4137. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4138. cb(cur, "ffn_out", il);
  4139. } else {
  4140. // MoE branch
  4141. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4142. model.layers[il].ffn_norm, NULL,
  4143. LLM_NORM_RMS, cb, il);
  4144. cb(cur, "ffn_norm", il);
  4145. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4146. cb(logits, "ffn_moe_logits", il);
  4147. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4148. cb(probs, "ffn_moe_probs", il);
  4149. // select experts
  4150. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4151. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4152. ggml_tensor * weights = ggml_get_rows(ctx0,
  4153. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4154. cb(weights, "ffn_moe_weights", il);
  4155. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4156. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4157. cb(weights_sum, "ffn_moe_weights_sum", il);
  4158. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4159. cb(weights, "ffn_moe_weights_norm", il);
  4160. // compute expert outputs
  4161. ggml_tensor * moe_out = nullptr;
  4162. for (int i = 0; i < n_expert_used; ++i) {
  4163. ggml_tensor * cur_expert;
  4164. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4165. cb(cur_up, "ffn_moe_up", il);
  4166. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4167. cb(cur_gate, "ffn_moe_gate", il);
  4168. cur_gate = ggml_silu(ctx0, cur_gate);
  4169. cb(cur_gate, "ffn_moe_silu", il);
  4170. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4171. cb(cur_expert, "ffn_moe_gate_par", il);
  4172. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4173. cb(cur_expert, "ffn_moe_down", il);
  4174. cur_expert = ggml_mul(ctx0, cur_expert,
  4175. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4176. cb(cur_expert, "ffn_moe_weighted", il);
  4177. if (i == 0) {
  4178. moe_out = cur_expert;
  4179. } else {
  4180. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4181. cb(moe_out, "ffn_moe_out", il);
  4182. }
  4183. }
  4184. cur = moe_out;
  4185. }
  4186. cur = ggml_add(ctx0, cur, ffn_inp);
  4187. cb(cur, "l_out", il);
  4188. // input for next layer
  4189. inpL = cur;
  4190. }
  4191. cur = inpL;
  4192. cur = llm_build_norm(ctx0, cur, hparams,
  4193. model.output_norm, NULL,
  4194. LLM_NORM_RMS, cb, -1);
  4195. cb(cur, "result_norm", -1);
  4196. // lm_head
  4197. cur = ggml_mul_mat(ctx0, model.output, cur);
  4198. cb(cur, "result_output", -1);
  4199. ggml_build_forward_expand(gf, cur);
  4200. return gf;
  4201. }
  4202. struct ggml_cgraph * build_baichuan() {
  4203. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4204. const int64_t n_embd_head = hparams.n_embd_head_v;
  4205. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4206. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4207. struct ggml_tensor * cur;
  4208. struct ggml_tensor * inpL;
  4209. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4210. cb(inpL, "inp_embd", -1);
  4211. // inp_pos - contains the positions
  4212. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4213. cb(inp_pos, "inp_pos", -1);
  4214. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4215. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4216. cb(KQ_mask, "KQ_mask", -1);
  4217. // shift the entire K-cache if needed
  4218. if (do_rope_shift) {
  4219. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4220. }
  4221. for (int il = 0; il < n_layer; ++il) {
  4222. struct ggml_tensor * inpSA = inpL;
  4223. cur = llm_build_norm(ctx0, inpL, hparams,
  4224. model.layers[il].attn_norm, NULL,
  4225. LLM_NORM_RMS, cb, il);
  4226. cb(cur, "attn_norm", il);
  4227. // self-attention
  4228. {
  4229. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4230. cb(Qcur, "Qcur", il);
  4231. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4232. cb(Kcur, "Kcur", il);
  4233. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4234. cb(Vcur, "Vcur", il);
  4235. switch (model.type) {
  4236. case MODEL_7B:
  4237. Qcur = ggml_rope_custom(
  4238. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4239. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4240. ext_factor, attn_factor, beta_fast, beta_slow
  4241. );
  4242. Kcur = ggml_rope_custom(
  4243. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4244. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4245. ext_factor, attn_factor, beta_fast, beta_slow
  4246. );
  4247. break;
  4248. case MODEL_13B:
  4249. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4250. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4251. break;
  4252. default:
  4253. GGML_ASSERT(false);
  4254. }
  4255. cb(Qcur, "Qcur", il);
  4256. cb(Kcur, "Kcur", il);
  4257. // apply ALiBi for 13B model
  4258. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4259. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4260. model.layers[il].wo, NULL,
  4261. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4262. cb(cur, "kqv_out", il);
  4263. }
  4264. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4265. cb(ffn_inp, "ffn_inp", il);
  4266. // feed-forward network
  4267. {
  4268. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4269. model.layers[il].ffn_norm, NULL,
  4270. LLM_NORM_RMS, cb, il);
  4271. cb(cur, "ffn_norm", il);
  4272. cur = llm_build_ffn(ctx0, cur,
  4273. model.layers[il].ffn_up, NULL,
  4274. model.layers[il].ffn_gate, NULL,
  4275. model.layers[il].ffn_down, NULL,
  4276. NULL,
  4277. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4278. cb(cur, "ffn_out", il);
  4279. }
  4280. cur = ggml_add(ctx0, cur, ffn_inp);
  4281. cb(cur, "l_out", il);
  4282. // input for next layer
  4283. inpL = cur;
  4284. }
  4285. cur = inpL;
  4286. cur = llm_build_norm(ctx0, cur, hparams,
  4287. model.output_norm, NULL,
  4288. LLM_NORM_RMS, cb, -1);
  4289. cb(cur, "result_norm", -1);
  4290. // lm_head
  4291. cur = ggml_mul_mat(ctx0, model.output, cur);
  4292. cb(cur, "result_output", -1);
  4293. ggml_build_forward_expand(gf, cur);
  4294. return gf;
  4295. }
  4296. struct ggml_cgraph * build_falcon() {
  4297. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4298. const int64_t n_embd_head = hparams.n_embd_head_v;
  4299. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4300. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4301. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4302. struct ggml_tensor * cur;
  4303. struct ggml_tensor * inpL;
  4304. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4305. cb(inpL, "inp_embd", -1);
  4306. // inp_pos - contains the positions
  4307. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4308. cb(inp_pos, "inp_pos", -1);
  4309. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4310. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4311. cb(KQ_mask, "KQ_mask", -1);
  4312. // shift the entire K-cache if needed
  4313. if (do_rope_shift) {
  4314. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4315. }
  4316. for (int il = 0; il < n_layer; ++il) {
  4317. struct ggml_tensor * attn_norm;
  4318. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4319. model.layers[il].attn_norm,
  4320. model.layers[il].attn_norm_b,
  4321. LLM_NORM, cb, il);
  4322. cb(attn_norm, "attn_norm", il);
  4323. // self-attention
  4324. {
  4325. if (model.layers[il].attn_norm_2) {
  4326. // Falcon-40B
  4327. cur = llm_build_norm(ctx0, inpL, hparams,
  4328. model.layers[il].attn_norm_2,
  4329. model.layers[il].attn_norm_2_b,
  4330. LLM_NORM, cb, il);
  4331. cb(cur, "attn_norm_2", il);
  4332. } else {
  4333. cur = attn_norm;
  4334. }
  4335. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4336. cb(cur, "wqkv", il);
  4337. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4338. 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)));
  4339. 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)));
  4340. cb(Qcur, "Qcur", il);
  4341. cb(Kcur, "Kcur", il);
  4342. cb(Vcur, "Vcur", il);
  4343. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4344. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4345. // using mode = 2 for neox mode
  4346. Qcur = ggml_rope_custom(
  4347. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4348. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4349. );
  4350. cb(Qcur, "Qcur", il);
  4351. Kcur = ggml_rope_custom(
  4352. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4353. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4354. );
  4355. cb(Kcur, "Kcur", il);
  4356. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4357. model.layers[il].wo, NULL,
  4358. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4359. cb(cur, "kqv_out", il);
  4360. }
  4361. struct ggml_tensor * ffn_inp = cur;
  4362. // feed forward
  4363. {
  4364. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4365. model.layers[il].ffn_up, NULL,
  4366. NULL, NULL,
  4367. model.layers[il].ffn_down, NULL,
  4368. NULL,
  4369. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4370. cb(cur, "ffn_out", il);
  4371. }
  4372. cur = ggml_add(ctx0, cur, ffn_inp);
  4373. cb(cur, "l_out", il);
  4374. cur = ggml_add(ctx0, cur, inpL);
  4375. cb(cur, "l_out", il);
  4376. // input for next layer
  4377. inpL = cur;
  4378. }
  4379. cur = inpL;
  4380. // norm
  4381. cur = llm_build_norm(ctx0, cur, hparams,
  4382. model.output_norm,
  4383. model.output_norm_b,
  4384. LLM_NORM, cb, -1);
  4385. cb(cur, "result_norm", -1);
  4386. cur = ggml_mul_mat(ctx0, model.output, cur);
  4387. cb(cur, "result_output", -1);
  4388. ggml_build_forward_expand(gf, cur);
  4389. return gf;
  4390. }
  4391. struct ggml_cgraph * build_starcoder() {
  4392. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4393. const int64_t n_embd_head = hparams.n_embd_head_v;
  4394. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4395. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4396. struct ggml_tensor * cur;
  4397. struct ggml_tensor * pos;
  4398. struct ggml_tensor * inpL;
  4399. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4400. cb(inpL, "inp_embd", -1);
  4401. // inp_pos - contains the positions
  4402. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4403. cb(inp_pos, "inp_pos", -1);
  4404. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4405. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4406. cb(KQ_mask, "KQ_mask", -1);
  4407. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4408. cb(pos, "pos_embd", -1);
  4409. inpL = ggml_add(ctx0, inpL, pos);
  4410. cb(inpL, "inpL", -1);
  4411. for (int il = 0; il < n_layer; ++il) {
  4412. cur = llm_build_norm(ctx0, inpL, hparams,
  4413. model.layers[il].attn_norm,
  4414. model.layers[il].attn_norm_b,
  4415. LLM_NORM, cb, il);
  4416. cb(cur, "attn_norm", il);
  4417. // self-attention
  4418. {
  4419. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4420. cb(cur, "wqkv", il);
  4421. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4422. cb(cur, "bqkv", il);
  4423. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4424. 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)));
  4425. 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)));
  4426. cb(Qcur, "Qcur", il);
  4427. cb(Kcur, "Kcur", il);
  4428. cb(Vcur, "Vcur", il);
  4429. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4430. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4431. model.layers[il].wo, model.layers[il].bo,
  4432. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4433. cb(cur, "kqv_out", il);
  4434. }
  4435. // add the input
  4436. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4437. cb(ffn_inp, "ffn_inp", il);
  4438. // FF
  4439. {
  4440. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4441. model.layers[il].ffn_norm,
  4442. model.layers[il].ffn_norm_b,
  4443. LLM_NORM, cb, il);
  4444. cb(cur, "ffn_norm", il);
  4445. cur = llm_build_ffn(ctx0, cur,
  4446. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4447. NULL, NULL,
  4448. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4449. NULL,
  4450. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4451. cb(cur, "ffn_out", il);
  4452. }
  4453. inpL = ggml_add(ctx0, cur, ffn_inp);
  4454. cb(inpL, "l_out", il);
  4455. }
  4456. cur = llm_build_norm(ctx0, inpL, hparams,
  4457. model.output_norm,
  4458. model.output_norm_b,
  4459. LLM_NORM, cb, -1);
  4460. cb(cur, "result_norm", -1);
  4461. cur = ggml_mul_mat(ctx0, model.output, cur);
  4462. cb(cur, "result_output", -1);
  4463. ggml_build_forward_expand(gf, cur);
  4464. return gf;
  4465. }
  4466. struct ggml_cgraph * build_persimmon() {
  4467. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4468. const int64_t n_embd_head = hparams.n_embd_head_v;
  4469. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4470. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4471. struct ggml_tensor * cur;
  4472. struct ggml_tensor * inpL;
  4473. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4474. cb(inpL, "inp_embd", -1);
  4475. // inp_pos - contains the positions
  4476. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4477. cb(inp_pos, "inp_pos", -1);
  4478. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4479. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4480. cb(KQ_mask, "KQ_mask", -1);
  4481. if (do_rope_shift) {
  4482. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4483. }
  4484. for (int il = 0; il < n_layer; ++il) {
  4485. struct ggml_tensor * residual = inpL;
  4486. cur = llm_build_norm(ctx0, inpL, hparams,
  4487. model.layers[il].attn_norm,
  4488. model.layers[il].attn_norm_b,
  4489. LLM_NORM, cb, il);
  4490. cb(cur, "attn_norm", il);
  4491. // self attention
  4492. {
  4493. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4494. cb(cur, "wqkv", il);
  4495. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4496. cb(cur, "bqkv", il);
  4497. // split qkv
  4498. GGML_ASSERT(n_head_kv == n_head);
  4499. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4500. cb(tmpqkv, "tmpqkv", il);
  4501. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4502. cb(tmpqkv_perm, "tmpqkv", il);
  4503. struct ggml_tensor * tmpq = ggml_view_3d(
  4504. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4505. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4506. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4507. 0
  4508. );
  4509. cb(tmpq, "tmpq", il);
  4510. struct ggml_tensor * tmpk = ggml_view_3d(
  4511. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4512. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4513. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4514. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4515. );
  4516. cb(tmpk, "tmpk", il);
  4517. // Q/K Layernorm
  4518. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4519. model.layers[il].attn_q_norm,
  4520. model.layers[il].attn_q_norm_b,
  4521. LLM_NORM, cb, il);
  4522. cb(tmpq, "tmpq", il);
  4523. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4524. model.layers[il].attn_k_norm,
  4525. model.layers[il].attn_k_norm_b,
  4526. LLM_NORM, cb, il);
  4527. cb(tmpk, "tmpk", il);
  4528. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4529. struct ggml_tensor * qrot = ggml_view_3d(
  4530. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4531. ggml_element_size(tmpq) * n_embd_head,
  4532. ggml_element_size(tmpq) * n_embd_head * n_head,
  4533. 0
  4534. );
  4535. cb(qrot, "qrot", il);
  4536. struct ggml_tensor * krot = ggml_view_3d(
  4537. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4538. ggml_element_size(tmpk) * n_embd_head,
  4539. ggml_element_size(tmpk) * n_embd_head * n_head,
  4540. 0
  4541. );
  4542. cb(krot, "krot", il);
  4543. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4544. struct ggml_tensor * qpass = ggml_view_3d(
  4545. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4546. ggml_element_size(tmpq) * n_embd_head,
  4547. ggml_element_size(tmpq) * n_embd_head * n_head,
  4548. ggml_element_size(tmpq) * hparams.n_rot
  4549. );
  4550. cb(qpass, "qpass", il);
  4551. struct ggml_tensor * kpass = ggml_view_3d(
  4552. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4553. ggml_element_size(tmpk) * n_embd_head,
  4554. ggml_element_size(tmpk) * n_embd_head * n_head,
  4555. ggml_element_size(tmpk) * hparams.n_rot
  4556. );
  4557. cb(kpass, "kpass", il);
  4558. struct ggml_tensor * qrotated = ggml_rope_custom(
  4559. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4560. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4561. );
  4562. cb(qrotated, "qrotated", il);
  4563. struct ggml_tensor * krotated = ggml_rope_custom(
  4564. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4565. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4566. );
  4567. cb(krotated, "krotated", il);
  4568. // ggml currently only supports concatenation on dim=2
  4569. // so we need to permute qrot, qpass, concat, then permute back.
  4570. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4571. cb(qrotated, "qrotated", il);
  4572. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4573. cb(krotated, "krotated", il);
  4574. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4575. cb(qpass, "qpass", il);
  4576. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4577. cb(kpass, "kpass", il);
  4578. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4579. cb(Qcur, "Qcur", il);
  4580. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4581. cb(Kcur, "Kcur", il);
  4582. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4583. cb(Q, "Q", il);
  4584. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4585. cb(Kcur, "Kcur", il);
  4586. struct ggml_tensor * Vcur = ggml_view_3d(
  4587. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4588. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4589. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4590. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4591. );
  4592. cb(Vcur, "Vcur", il);
  4593. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4594. model.layers[il].wo, model.layers[il].bo,
  4595. Kcur, Vcur, Q, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4596. cb(cur, "kqv_out", il);
  4597. }
  4598. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4599. cb(ffn_inp, "ffn_inp", il);
  4600. // feed-forward network
  4601. {
  4602. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4603. model.layers[il].ffn_norm,
  4604. model.layers[il].ffn_norm_b,
  4605. LLM_NORM, cb, il);
  4606. cb(cur, "ffn_norm", il);
  4607. cur = llm_build_ffn(ctx0, cur,
  4608. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4609. NULL, NULL,
  4610. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4611. NULL,
  4612. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4613. cb(cur, "ffn_out", il);
  4614. }
  4615. cur = ggml_add(ctx0, cur, ffn_inp);
  4616. cb(cur, "l_out", il);
  4617. inpL = cur;
  4618. }
  4619. cur = inpL;
  4620. cur = llm_build_norm(ctx0, cur, hparams,
  4621. model.output_norm,
  4622. model.output_norm_b,
  4623. LLM_NORM, cb, -1);
  4624. cb(cur, "result_norm", -1);
  4625. cur = ggml_mul_mat(ctx0, model.output, cur);
  4626. cb(cur, "result_output", -1);
  4627. ggml_build_forward_expand(gf, cur);
  4628. return gf;
  4629. }
  4630. struct ggml_cgraph * build_refact() {
  4631. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4632. const int64_t n_embd_head = hparams.n_embd_head_v;
  4633. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4634. struct ggml_tensor * cur;
  4635. struct ggml_tensor * inpL;
  4636. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4637. cb(inpL, "inp_embd", -1);
  4638. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4639. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4640. cb(KQ_mask, "KQ_mask", -1);
  4641. for (int il = 0; il < n_layer; ++il) {
  4642. struct ggml_tensor * inpSA = inpL;
  4643. cur = llm_build_norm(ctx0, inpL, hparams,
  4644. model.layers[il].attn_norm, NULL,
  4645. LLM_NORM_RMS, cb, il);
  4646. cb(cur, "attn_norm", il);
  4647. // self-attention
  4648. {
  4649. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4650. cb(Qcur, "Qcur", il);
  4651. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4652. cb(Kcur, "Kcur", il);
  4653. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4654. cb(Vcur, "Vcur", il);
  4655. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4656. cb(Kcur, "Kcur", il);
  4657. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4658. cb(Qcur, "Qcur", il);
  4659. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4660. model.layers[il].wo, NULL,
  4661. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4662. cb(cur, "kqv_out", il);
  4663. }
  4664. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4665. cb(ffn_inp, "ffn_inp", il);
  4666. // feed-forward network
  4667. {
  4668. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4669. model.layers[il].ffn_norm, NULL,
  4670. LLM_NORM_RMS, cb, il);
  4671. cb(cur, "ffn_norm", il);
  4672. cur = llm_build_ffn(ctx0, cur,
  4673. model.layers[il].ffn_up, NULL,
  4674. model.layers[il].ffn_gate, NULL,
  4675. model.layers[il].ffn_down, NULL,
  4676. NULL,
  4677. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4678. cb(cur, "ffn_out", il);
  4679. }
  4680. cur = ggml_add(ctx0, cur, ffn_inp);
  4681. cb(cur, "l_out", il);
  4682. // input for next layer
  4683. inpL = cur;
  4684. }
  4685. cur = inpL;
  4686. cur = llm_build_norm(ctx0, cur, hparams,
  4687. model.output_norm, NULL,
  4688. LLM_NORM_RMS, cb, -1);
  4689. cb(cur, "result_norm", -1);
  4690. // lm_head
  4691. cur = ggml_mul_mat(ctx0, model.output, cur);
  4692. cb(cur, "result_output", -1);
  4693. ggml_build_forward_expand(gf, cur);
  4694. return gf;
  4695. }
  4696. struct ggml_cgraph * build_bloom() {
  4697. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4698. const int64_t n_embd_head = hparams.n_embd_head_v;
  4699. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4700. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4701. struct ggml_tensor * cur;
  4702. struct ggml_tensor * inpL;
  4703. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4704. cb(inpL, "inp_embd", -1);
  4705. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4706. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4707. cb(KQ_mask, "KQ_mask", -1);
  4708. inpL = llm_build_norm(ctx0, inpL, hparams,
  4709. model.tok_norm,
  4710. model.tok_norm_b,
  4711. LLM_NORM, cb, -1);
  4712. cb(inpL, "inp_norm", -1);
  4713. for (int il = 0; il < n_layer; ++il) {
  4714. cur = llm_build_norm(ctx0, inpL, hparams,
  4715. model.layers[il].attn_norm,
  4716. model.layers[il].attn_norm_b,
  4717. LLM_NORM, cb, il);
  4718. cb(cur, "attn_norm", il);
  4719. // self-attention
  4720. {
  4721. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4722. cb(cur, "wqkv", il);
  4723. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4724. cb(cur, "bqkv", il);
  4725. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4726. 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)));
  4727. 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)));
  4728. cb(Qcur, "Qcur", il);
  4729. cb(Kcur, "Kcur", il);
  4730. cb(Vcur, "Vcur", il);
  4731. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4732. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4733. model.layers[il].wo, model.layers[il].bo,
  4734. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4735. cb(cur, "kqv_out", il);
  4736. }
  4737. // Add the input
  4738. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4739. cb(ffn_inp, "ffn_inp", il);
  4740. // FF
  4741. {
  4742. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4743. model.layers[il].ffn_norm,
  4744. model.layers[il].ffn_norm_b,
  4745. LLM_NORM, cb, il);
  4746. cb(cur, "ffn_norm", il);
  4747. cur = llm_build_ffn(ctx0, cur,
  4748. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4749. NULL, NULL,
  4750. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4751. NULL,
  4752. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4753. cb(cur, "ffn_out", il);
  4754. }
  4755. inpL = ggml_add(ctx0, cur, ffn_inp);
  4756. cb(inpL, "l_out", il);
  4757. }
  4758. cur = llm_build_norm(ctx0, inpL, hparams,
  4759. model.output_norm,
  4760. model.output_norm_b,
  4761. LLM_NORM, cb, -1);
  4762. cb(cur, "result_norm", -1);
  4763. cur = ggml_mul_mat(ctx0, model.output, cur);
  4764. cb(cur, "result_output", -1);
  4765. ggml_build_forward_expand(gf, cur);
  4766. return gf;
  4767. }
  4768. struct ggml_cgraph * build_mpt() {
  4769. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4770. const int64_t n_embd_head = hparams.n_embd_head_v;
  4771. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4772. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4773. struct ggml_tensor * cur;
  4774. struct ggml_tensor * inpL;
  4775. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4776. cb(inpL, "inp_embd", -1);
  4777. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4778. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4779. cb(KQ_mask, "KQ_mask", -1);
  4780. for (int il = 0; il < n_layer; ++il) {
  4781. struct ggml_tensor * attn_norm;
  4782. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4783. model.layers[il].attn_norm,
  4784. NULL,
  4785. LLM_NORM, cb, il);
  4786. cb(attn_norm, "attn_norm", il);
  4787. // self-attention
  4788. {
  4789. cur = attn_norm;
  4790. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4791. cb(cur, "wqkv", il);
  4792. if (hparams.f_clamp_kqv > 0.0f) {
  4793. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4794. cb(cur, "wqkv_clamped", il);
  4795. }
  4796. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4797. 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)));
  4798. 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)));
  4799. cb(Qcur, "Qcur", il);
  4800. cb(Kcur, "Kcur", il);
  4801. cb(Vcur, "Vcur", il);
  4802. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4803. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4804. model.layers[il].wo, NULL,
  4805. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4806. cb(cur, "kqv_out", il);
  4807. }
  4808. // Add the input
  4809. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4810. cb(ffn_inp, "ffn_inp", il);
  4811. // feed forward
  4812. {
  4813. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4814. model.layers[il].ffn_norm,
  4815. NULL,
  4816. LLM_NORM, cb, il);
  4817. cb(cur, "ffn_norm", il);
  4818. cur = llm_build_ffn(ctx0, cur,
  4819. model.layers[il].ffn_up, NULL,
  4820. NULL, NULL,
  4821. model.layers[il].ffn_down, NULL,
  4822. model.layers[il].ffn_act,
  4823. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4824. cb(cur, "ffn_out", il);
  4825. }
  4826. cur = ggml_add(ctx0, cur, ffn_inp);
  4827. cb(cur, "l_out", il);
  4828. // input for next layer
  4829. inpL = cur;
  4830. }
  4831. cur = inpL;
  4832. cur = llm_build_norm(ctx0, cur, hparams,
  4833. model.output_norm,
  4834. NULL,
  4835. LLM_NORM, cb, -1);
  4836. cb(cur, "result_norm", -1);
  4837. cur = ggml_mul_mat(ctx0, model.output, cur);
  4838. cb(cur, "result_output", -1);
  4839. ggml_build_forward_expand(gf, cur);
  4840. return gf;
  4841. }
  4842. struct ggml_cgraph * build_stablelm() {
  4843. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4844. const int64_t n_embd_head = hparams.n_embd_head_v;
  4845. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4846. struct ggml_tensor * cur;
  4847. struct ggml_tensor * inpL;
  4848. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4849. cb(inpL, "inp_embd", -1);
  4850. // inp_pos - contains the positions
  4851. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4852. cb(inp_pos, "inp_pos", -1);
  4853. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4854. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4855. cb(KQ_mask, "KQ_mask", -1);
  4856. // shift the entire K-cache if needed
  4857. if (do_rope_shift) {
  4858. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4859. }
  4860. for (int il = 0; il < n_layer; ++il) {
  4861. struct ggml_tensor * inpSA = inpL;
  4862. // norm
  4863. cur = llm_build_norm(ctx0, inpL, hparams,
  4864. model.layers[il].attn_norm,
  4865. model.layers[il].attn_norm_b,
  4866. LLM_NORM, cb, il);
  4867. cb(cur, "attn_norm", il);
  4868. // self-attention
  4869. {
  4870. // compute Q and K and RoPE them
  4871. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4872. cb(Qcur, "Qcur", il);
  4873. if (model.layers[il].bq) {
  4874. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4875. cb(Qcur, "Qcur", il);
  4876. }
  4877. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4878. cb(Kcur, "Kcur", il);
  4879. if (model.layers[il].bk) {
  4880. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4881. cb(Kcur, "Kcur", il);
  4882. }
  4883. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4884. cb(Vcur, "Vcur", il);
  4885. if (model.layers[il].bv) {
  4886. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4887. cb(Vcur, "Vcur", il);
  4888. }
  4889. Qcur = ggml_rope_custom(
  4890. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4891. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4892. ext_factor, attn_factor, beta_fast, beta_slow
  4893. );
  4894. cb(Qcur, "Qcur", il);
  4895. Kcur = ggml_rope_custom(
  4896. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4897. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4898. ext_factor, attn_factor, beta_fast, beta_slow
  4899. );
  4900. cb(Kcur, "Kcur", il);
  4901. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4902. model.layers[il].wo, NULL,
  4903. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4904. cb(cur, "kqv_out", il);
  4905. }
  4906. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4907. cb(ffn_inp, "ffn_inp", il);
  4908. // feed-forward network
  4909. {
  4910. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4911. model.layers[il].ffn_norm,
  4912. model.layers[il].ffn_norm_b,
  4913. LLM_NORM, cb, il);
  4914. cb(cur, "ffn_norm", il);
  4915. cur = llm_build_ffn(ctx0, cur,
  4916. model.layers[il].ffn_up, NULL,
  4917. model.layers[il].ffn_gate, NULL,
  4918. model.layers[il].ffn_down, NULL,
  4919. NULL,
  4920. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4921. cb(cur, "ffn_out", il);
  4922. }
  4923. cur = ggml_add(ctx0, cur, ffn_inp);
  4924. cb(cur, "l_out", il);
  4925. // input for next layer
  4926. inpL = cur;
  4927. }
  4928. cur = inpL;
  4929. cur = llm_build_norm(ctx0, cur, hparams,
  4930. model.output_norm,
  4931. model.output_norm_b,
  4932. LLM_NORM, cb, -1);
  4933. cb(cur, "result_norm", -1);
  4934. // lm_head
  4935. cur = ggml_mul_mat(ctx0, model.output, cur);
  4936. cb(cur, "result_output", -1);
  4937. ggml_build_forward_expand(gf, cur);
  4938. return gf;
  4939. }
  4940. struct ggml_cgraph * build_qwen() {
  4941. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4942. const int64_t n_embd_head = hparams.n_embd_head_v;
  4943. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4944. struct ggml_tensor * cur;
  4945. struct ggml_tensor * inpL;
  4946. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4947. cb(inpL, "inp_embd", -1);
  4948. // inp_pos - contains the positions
  4949. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4950. cb(inp_pos, "inp_pos", -1);
  4951. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4952. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4953. cb(KQ_mask, "KQ_mask", -1);
  4954. // shift the entire K-cache if needed
  4955. if (do_rope_shift) {
  4956. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4957. }
  4958. for (int il = 0; il < n_layer; ++il) {
  4959. struct ggml_tensor * inpSA = inpL;
  4960. cur = llm_build_norm(ctx0, inpL, hparams,
  4961. model.layers[il].attn_norm, NULL,
  4962. LLM_NORM_RMS, cb, il);
  4963. cb(cur, "attn_norm", il);
  4964. // self-attention
  4965. {
  4966. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4967. cb(cur, "wqkv", il);
  4968. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4969. cb(cur, "bqkv", il);
  4970. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4971. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4972. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4973. cb(Qcur, "Qcur", il);
  4974. cb(Kcur, "Kcur", il);
  4975. cb(Vcur, "Vcur", il);
  4976. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4977. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4978. // using mode = 2 for neox mode
  4979. Qcur = ggml_rope_custom(
  4980. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4981. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4982. );
  4983. cb(Qcur, "Qcur", il);
  4984. Kcur = ggml_rope_custom(
  4985. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4986. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4987. );
  4988. cb(Kcur, "Kcur", il);
  4989. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4990. model.layers[il].wo, NULL,
  4991. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4992. cb(cur, "kqv_out", il);
  4993. }
  4994. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4995. cb(ffn_inp, "ffn_inp", il);
  4996. // feed-forward forward
  4997. {
  4998. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4999. model.layers[il].ffn_norm, NULL,
  5000. LLM_NORM_RMS, cb, il);
  5001. cb(cur, "ffn_norm", il);
  5002. cur = llm_build_ffn(ctx0, cur,
  5003. model.layers[il].ffn_up, NULL,
  5004. model.layers[il].ffn_gate, NULL,
  5005. model.layers[il].ffn_down, NULL,
  5006. NULL,
  5007. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5008. cb(cur, "ffn_out", il);
  5009. }
  5010. cur = ggml_add(ctx0, cur, ffn_inp);
  5011. cb(cur, "l_out", il);
  5012. // input for next layer
  5013. inpL = cur;
  5014. }
  5015. cur = inpL;
  5016. cur = llm_build_norm(ctx0, cur, hparams,
  5017. model.output_norm, NULL,
  5018. LLM_NORM_RMS, cb, -1);
  5019. cb(cur, "result_norm", -1);
  5020. // lm_head
  5021. cur = ggml_mul_mat(ctx0, model.output, cur);
  5022. cb(cur, "result_output", -1);
  5023. ggml_build_forward_expand(gf, cur);
  5024. return gf;
  5025. }
  5026. struct ggml_cgraph * build_qwen2() {
  5027. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5028. const int64_t n_embd_head = hparams.n_embd_head_v;
  5029. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5030. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5031. struct ggml_tensor * cur;
  5032. struct ggml_tensor * inpL;
  5033. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5034. cb(inpL, "inp_embd", -1);
  5035. // inp_pos - contains the positions
  5036. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5037. cb(inp_pos, "inp_pos", -1);
  5038. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5039. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5040. cb(KQ_mask, "KQ_mask", -1);
  5041. // shift the entire K-cache if needed
  5042. if (do_rope_shift) {
  5043. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5044. }
  5045. for (int il = 0; il < n_layer; ++il) {
  5046. struct ggml_tensor * inpSA = inpL;
  5047. // norm
  5048. cur = llm_build_norm(ctx0, inpL, hparams,
  5049. model.layers[il].attn_norm, NULL,
  5050. LLM_NORM_RMS, cb, il);
  5051. cb(cur, "attn_norm", il);
  5052. // self-attention
  5053. {
  5054. // compute Q and K and RoPE them
  5055. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5056. cb(Qcur, "Qcur", il);
  5057. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5058. cb(Qcur, "Qcur", il);
  5059. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5060. cb(Kcur, "Kcur", il);
  5061. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5062. cb(Kcur, "Kcur", il);
  5063. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5064. cb(Vcur, "Vcur", il);
  5065. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5066. cb(Vcur, "Vcur", il);
  5067. // these nodes are added to the graph together so that they are not reordered
  5068. // by doing so, the number of splits in the graph is reduced
  5069. ggml_build_forward_expand(gf, Qcur);
  5070. ggml_build_forward_expand(gf, Kcur);
  5071. ggml_build_forward_expand(gf, Vcur);
  5072. Qcur = ggml_rope_custom(
  5073. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5074. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5075. ext_factor, attn_factor, beta_fast, beta_slow
  5076. );
  5077. cb(Qcur, "Qcur", il);
  5078. Kcur = ggml_rope_custom(
  5079. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5080. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5081. ext_factor, attn_factor, beta_fast, beta_slow
  5082. );
  5083. cb(Kcur, "Kcur", il);
  5084. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5085. model.layers[il].wo, model.layers[il].bo,
  5086. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5087. cb(cur, "kqv_out", il);
  5088. }
  5089. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5090. cb(ffn_inp, "ffn_inp", il);
  5091. // feed-forward network
  5092. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5093. model.layers[il].ffn_norm, NULL,
  5094. LLM_NORM_RMS, cb, il);
  5095. cb(cur, "ffn_norm", il);
  5096. cur = llm_build_ffn(ctx0, cur,
  5097. model.layers[il].ffn_up, NULL,
  5098. model.layers[il].ffn_gate, NULL,
  5099. model.layers[il].ffn_down, NULL,
  5100. NULL,
  5101. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5102. cb(cur, "ffn_out", il);
  5103. cur = ggml_add(ctx0, cur, ffn_inp);
  5104. cb(cur, "l_out", il);
  5105. // input for next layer
  5106. inpL = cur;
  5107. }
  5108. cur = inpL;
  5109. cur = llm_build_norm(ctx0, cur, hparams,
  5110. model.output_norm, NULL,
  5111. LLM_NORM_RMS, cb, -1);
  5112. cb(cur, "result_norm", -1);
  5113. // lm_head
  5114. cur = ggml_mul_mat(ctx0, model.output, cur);
  5115. cb(cur, "result_output", -1);
  5116. ggml_build_forward_expand(gf, cur);
  5117. return gf;
  5118. }
  5119. struct ggml_cgraph * build_phi2() {
  5120. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5121. const int64_t n_embd_head = hparams.n_embd_head_v;
  5122. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5123. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5124. struct ggml_tensor * cur;
  5125. struct ggml_tensor * attn_norm_output;
  5126. struct ggml_tensor * ffn_output;
  5127. struct ggml_tensor * inpL;
  5128. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5129. cb(inpL, "inp_embd", -1);
  5130. // inp_pos - contains the positions
  5131. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5132. cb(inp_pos, "inp_pos", -1);
  5133. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5134. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5135. cb(KQ_mask, "KQ_mask", -1);
  5136. // shift the entire K-cache if needed
  5137. if (do_rope_shift) {
  5138. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5139. }
  5140. for (int il = 0; il < n_layer; ++il) {
  5141. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5142. model.layers[il].attn_norm,
  5143. model.layers[il].attn_norm_b,
  5144. LLM_NORM, cb, il);
  5145. cb(attn_norm_output, "attn_norm", il);
  5146. // self-attention
  5147. {
  5148. struct ggml_tensor * Qcur = nullptr;
  5149. struct ggml_tensor * Kcur = nullptr;
  5150. struct ggml_tensor * Vcur = nullptr;
  5151. if (model.layers[il].wqkv) {
  5152. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5153. cb(cur, "wqkv", il);
  5154. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5155. cb(cur, "bqkv", il);
  5156. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5157. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5158. 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)));
  5159. } else {
  5160. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5161. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5162. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5163. }
  5164. cb(Qcur, "Qcur", il);
  5165. cb(Kcur, "Kcur", il);
  5166. cb(Vcur, "Vcur", il);
  5167. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5168. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5169. Qcur = ggml_rope_custom(
  5170. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5171. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5172. );
  5173. cb(Qcur, "Qcur", il);
  5174. // with phi2, we scale the Q to avoid precision issues
  5175. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5176. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5177. cb(Qcur, "Qcur", il);
  5178. Kcur = ggml_rope_custom(
  5179. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5180. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5181. );
  5182. cb(Kcur, "Kcur", il);
  5183. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5184. model.layers[il].wo, model.layers[il].bo,
  5185. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f, cb, il);
  5186. cb(cur, "kqv_out", il);
  5187. }
  5188. // FF
  5189. {
  5190. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5191. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5192. NULL, NULL,
  5193. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5194. NULL,
  5195. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5196. cb(ffn_output, "ffn_out", il);
  5197. }
  5198. cur = ggml_add(ctx0, cur, ffn_output);
  5199. cb(cur, "l_out", il);
  5200. cur = ggml_add(ctx0, cur, inpL);
  5201. cb(cur, "l_out", il);
  5202. inpL = cur;
  5203. }
  5204. cur = llm_build_norm(ctx0, inpL, hparams,
  5205. model.output_norm,
  5206. model.output_norm_b,
  5207. LLM_NORM, cb, -1);
  5208. cb(cur, "result_norm", -1);
  5209. cur = ggml_mul_mat(ctx0, model.output, cur);
  5210. cb(cur, "result_output_no_bias", -1);
  5211. cur = ggml_add(ctx0, cur, model.output_b);
  5212. cb(cur, "result_output", -1);
  5213. ggml_build_forward_expand(gf, cur);
  5214. return gf;
  5215. }
  5216. struct ggml_cgraph * build_plamo() {
  5217. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5218. const int64_t n_embd_head = hparams.n_embd_head_v;
  5219. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5220. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5221. struct ggml_tensor * cur;
  5222. struct ggml_tensor * inpL;
  5223. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5224. cb(inpL, "inp_embd", -1);
  5225. // inp_pos - contains the positions
  5226. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5227. cb(inp_pos, "inp_pos", -1);
  5228. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5229. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5230. cb(KQ_mask, "KQ_mask", -1);
  5231. // shift the entire K-cache if needed
  5232. if (do_rope_shift) {
  5233. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5234. }
  5235. for (int il = 0; il < n_layer; ++il) {
  5236. // norm
  5237. cur = llm_build_norm(ctx0, inpL, hparams,
  5238. model.layers[il].attn_norm, NULL,
  5239. LLM_NORM_RMS, cb, il);
  5240. cb(cur, "attn_norm", il);
  5241. struct ggml_tensor * attention_norm = cur;
  5242. // self-attention
  5243. {
  5244. // compute Q and K and RoPE them
  5245. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5246. cb(Qcur, "Qcur", il);
  5247. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5248. cb(Kcur, "Kcur", il);
  5249. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5250. cb(Vcur, "Vcur", il);
  5251. Qcur = ggml_rope_custom(
  5252. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5253. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5254. ext_factor, attn_factor, beta_fast, beta_slow);
  5255. cb(Qcur, "Qcur", il);
  5256. Kcur = ggml_rope_custom(
  5257. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5258. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5259. ext_factor, attn_factor, beta_fast, beta_slow);
  5260. cb(Kcur, "Kcur", il);
  5261. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5262. model.layers[il].wo, NULL,
  5263. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5264. cb(cur, "kqv_out", il);
  5265. }
  5266. struct ggml_tensor * sa_out = cur;
  5267. cur = attention_norm;
  5268. // feed-forward network
  5269. {
  5270. cur = llm_build_ffn(ctx0, cur,
  5271. model.layers[il].ffn_up, NULL,
  5272. model.layers[il].ffn_gate, NULL,
  5273. model.layers[il].ffn_down, NULL,
  5274. NULL,
  5275. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5276. cb(cur, "ffn_out", il);
  5277. }
  5278. cur = ggml_add(ctx0, cur, sa_out);
  5279. cb(cur, "l_out", il);
  5280. cur = ggml_add(ctx0, cur, inpL);
  5281. cb(cur, "l_out", il);
  5282. // input for next layer
  5283. inpL = cur;
  5284. }
  5285. cur = inpL;
  5286. cur = llm_build_norm(ctx0, cur, hparams,
  5287. model.output_norm, NULL,
  5288. LLM_NORM_RMS, cb, -1);
  5289. cb(cur, "result_norm", -1);
  5290. // lm_head
  5291. cur = ggml_mul_mat(ctx0, model.output, cur);
  5292. cb(cur, "result_output", -1);
  5293. ggml_build_forward_expand(gf, cur);
  5294. return gf;
  5295. }
  5296. struct ggml_cgraph * build_gpt2() {
  5297. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5298. const int64_t n_embd_head = hparams.n_embd_head_v;
  5299. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5300. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5301. struct ggml_tensor * cur;
  5302. struct ggml_tensor * pos;
  5303. struct ggml_tensor * inpL;
  5304. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5305. cb(inpL, "inp_embd", -1);
  5306. // inp_pos - contains the positions
  5307. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5308. cb(inp_pos, "inp_pos", -1);
  5309. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5310. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5311. cb(KQ_mask, "KQ_mask", -1);
  5312. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5313. cb(pos, "pos_embd", -1);
  5314. inpL = ggml_add(ctx0, inpL, pos);
  5315. cb(inpL, "inpL", -1);
  5316. for (int il = 0; il < n_layer; ++il) {
  5317. cur = llm_build_norm(ctx0, inpL, hparams,
  5318. model.layers[il].attn_norm,
  5319. model.layers[il].attn_norm_b,
  5320. LLM_NORM, cb, il);
  5321. cb(cur, "attn_norm", il);
  5322. // self-attention
  5323. {
  5324. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5325. cb(cur, "wqkv", il);
  5326. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5327. cb(cur, "bqkv", il);
  5328. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5329. 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)));
  5330. 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)));
  5331. cb(Qcur, "Qcur", il);
  5332. cb(Kcur, "Kcur", il);
  5333. cb(Vcur, "Vcur", il);
  5334. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5335. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5336. model.layers[il].wo, model.layers[il].bo,
  5337. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5338. cb(cur, "kqv_out", il);
  5339. }
  5340. // add the input
  5341. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5342. cb(ffn_inp, "ffn_inp", il);
  5343. // FF
  5344. {
  5345. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5346. model.layers[il].ffn_norm,
  5347. model.layers[il].ffn_norm_b,
  5348. LLM_NORM, cb, il);
  5349. cb(cur, "ffn_norm", il);
  5350. cur = llm_build_ffn(ctx0, cur,
  5351. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5352. NULL, NULL,
  5353. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5354. NULL,
  5355. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5356. cb(cur, "ffn_out", il);
  5357. }
  5358. inpL = ggml_add(ctx0, cur, ffn_inp);
  5359. cb(inpL, "l_out", il);
  5360. }
  5361. cur = llm_build_norm(ctx0, inpL, hparams,
  5362. model.output_norm,
  5363. model.output_norm_b,
  5364. LLM_NORM, cb, -1);
  5365. cb(cur, "result_norm", -1);
  5366. cur = ggml_mul_mat(ctx0, model.output, cur);
  5367. cb(cur, "result_output", -1);
  5368. ggml_build_forward_expand(gf, cur);
  5369. return gf;
  5370. }
  5371. struct ggml_cgraph * build_codeshell() {
  5372. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5373. const int64_t n_embd_head = hparams.n_embd_head_v;
  5374. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5375. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5376. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5377. struct ggml_tensor * cur;
  5378. struct ggml_tensor * inpL;
  5379. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5380. cb(inpL, "inp_embd", -1);
  5381. // inp_pos - contains the positions
  5382. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5383. cb(inp_pos, "inp_pos", -1);
  5384. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5385. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5386. cb(KQ_mask, "KQ_mask", -1);
  5387. // shift the entire K-cache if needed
  5388. if (do_rope_shift) {
  5389. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5390. }
  5391. for (int il = 0; il < n_layer; ++il) {
  5392. cur = llm_build_norm(ctx0, inpL, hparams,
  5393. model.layers[il].attn_norm,
  5394. model.layers[il].attn_norm_b,
  5395. LLM_NORM, cb, il);
  5396. cb(cur, "attn_norm", il);
  5397. // self-attention
  5398. {
  5399. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5400. cb(cur, "wqkv", il);
  5401. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5402. cb(cur, "bqkv", il);
  5403. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5404. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5405. 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)));
  5406. cb(tmpq, "tmpq", il);
  5407. cb(tmpk, "tmpk", il);
  5408. cb(Vcur, "Vcur", il);
  5409. struct ggml_tensor * Qcur = ggml_rope_custom(
  5410. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5411. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5412. ext_factor, attn_factor, beta_fast, beta_slow
  5413. );
  5414. cb(Qcur, "Qcur", il);
  5415. struct ggml_tensor * Kcur = ggml_rope_custom(
  5416. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5417. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5418. ext_factor, attn_factor, beta_fast, beta_slow
  5419. );
  5420. cb(Kcur, "Kcur", il);
  5421. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5422. model.layers[il].wo, model.layers[il].bo,
  5423. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5424. cb(cur, "kqv_out", il);
  5425. }
  5426. // add the input
  5427. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5428. cb(ffn_inp, "ffn_inp", il);
  5429. // FF
  5430. {
  5431. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5432. model.layers[il].ffn_norm,
  5433. model.layers[il].ffn_norm_b,
  5434. LLM_NORM, cb, il);
  5435. cb(cur, "ffn_norm", il);
  5436. cur = llm_build_ffn(ctx0, cur,
  5437. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5438. NULL, NULL,
  5439. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5440. NULL,
  5441. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5442. cb(cur, "ffn_out", il);
  5443. }
  5444. inpL = ggml_add(ctx0, cur, ffn_inp);
  5445. cb(inpL, "l_out", il);
  5446. }
  5447. cur = llm_build_norm(ctx0, inpL, hparams,
  5448. model.output_norm,
  5449. model.output_norm_b,
  5450. LLM_NORM, cb, -1);
  5451. cb(cur, "result_norm", -1);
  5452. cur = ggml_mul_mat(ctx0, model.output, cur);
  5453. cb(cur, "result_output", -1);
  5454. ggml_build_forward_expand(gf, cur);
  5455. return gf;
  5456. }
  5457. };
  5458. static struct ggml_cgraph * llama_build_graph(
  5459. llama_context & lctx,
  5460. const llama_batch & batch) {
  5461. const auto & model = lctx.model;
  5462. // check if we should build the worst-case graph (for memory measurement)
  5463. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  5464. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5465. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5466. if (il >= 0) {
  5467. ggml_format_name(cur, "%s-%d", name, il);
  5468. } else {
  5469. ggml_set_name(cur, name);
  5470. }
  5471. if (!lctx.cparams.offload_kqv) {
  5472. if (strcmp(name, "kqv_merged_cont") == 0) {
  5473. // all nodes between the KV store and the attention output are run on the CPU
  5474. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  5475. }
  5476. }
  5477. };
  5478. struct ggml_cgraph * result = NULL;
  5479. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5480. //
  5481. // set input data
  5482. //
  5483. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5484. if (batch.token) {
  5485. const int64_t n_tokens = batch.n_tokens;
  5486. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  5487. }
  5488. if (batch.embd) {
  5489. const int64_t n_embd = llm.n_embd;
  5490. const int64_t n_tokens = batch.n_tokens;
  5491. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  5492. }
  5493. if (batch.pos) {
  5494. const int64_t n_tokens = batch.n_tokens;
  5495. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  5496. }
  5497. {
  5498. const int64_t n_kv = llm.n_kv;
  5499. const int64_t n_tokens = batch.n_tokens;
  5500. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  5501. float * data = (float *) lctx.inp_KQ_mask->data;
  5502. for (int h = 0; h < 1; ++h) {
  5503. for (int j = 0; j < n_tokens; ++j) {
  5504. const llama_pos pos = batch.pos[j];
  5505. const llama_seq_id seq_id = batch.seq_id[j][0];
  5506. for (int i = 0; i < n_kv; ++i) {
  5507. float f;
  5508. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  5509. f = -INFINITY;
  5510. } else {
  5511. f = 0;
  5512. }
  5513. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  5514. }
  5515. }
  5516. }
  5517. }
  5518. if (llm.do_rope_shift) {
  5519. const int64_t n_ctx = llm.n_ctx;
  5520. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  5521. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  5522. for (int i = 0; i < n_ctx; ++i) {
  5523. data[i] = lctx.kv_self.cells[i].delta;
  5524. }
  5525. }
  5526. }
  5527. llm.init();
  5528. switch (model.arch) {
  5529. case LLM_ARCH_LLAMA:
  5530. {
  5531. result = llm.build_llama();
  5532. } break;
  5533. case LLM_ARCH_BAICHUAN:
  5534. {
  5535. result = llm.build_baichuan();
  5536. } break;
  5537. case LLM_ARCH_FALCON:
  5538. {
  5539. result = llm.build_falcon();
  5540. } break;
  5541. case LLM_ARCH_STARCODER:
  5542. {
  5543. result = llm.build_starcoder();
  5544. } break;
  5545. case LLM_ARCH_PERSIMMON:
  5546. {
  5547. result = llm.build_persimmon();
  5548. } break;
  5549. case LLM_ARCH_REFACT:
  5550. {
  5551. result = llm.build_refact();
  5552. } break;
  5553. case LLM_ARCH_BLOOM:
  5554. {
  5555. result = llm.build_bloom();
  5556. } break;
  5557. case LLM_ARCH_MPT:
  5558. {
  5559. result = llm.build_mpt();
  5560. } break;
  5561. case LLM_ARCH_STABLELM:
  5562. {
  5563. result = llm.build_stablelm();
  5564. } break;
  5565. case LLM_ARCH_QWEN:
  5566. {
  5567. result = llm.build_qwen();
  5568. } break;
  5569. case LLM_ARCH_QWEN2:
  5570. {
  5571. result = llm.build_qwen2();
  5572. } break;
  5573. case LLM_ARCH_PHI2:
  5574. {
  5575. result = llm.build_phi2();
  5576. } break;
  5577. case LLM_ARCH_PLAMO:
  5578. {
  5579. result = llm.build_plamo();
  5580. } break;
  5581. case LLM_ARCH_GPT2:
  5582. {
  5583. result = llm.build_gpt2();
  5584. } break;
  5585. case LLM_ARCH_CODESHELL:
  5586. {
  5587. result = llm.build_codeshell();
  5588. } break;
  5589. case LLM_ARCH_ORION:
  5590. {
  5591. result = llm.build_orion();
  5592. } break;
  5593. default:
  5594. GGML_ASSERT(false);
  5595. }
  5596. llm.free();
  5597. return result;
  5598. }
  5599. // decode a batch of tokens by evaluating the transformer
  5600. //
  5601. // - lctx: llama context
  5602. // - batch: batch to evaluate
  5603. //
  5604. // return 0 on success
  5605. // return positive int on warning
  5606. // return negative int on error
  5607. //
  5608. static int llama_decode_internal(
  5609. llama_context & lctx,
  5610. llama_batch batch) {
  5611. const uint32_t n_tokens = batch.n_tokens;
  5612. if (n_tokens == 0) {
  5613. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5614. return -1;
  5615. }
  5616. const auto & model = lctx.model;
  5617. const auto & hparams = model.hparams;
  5618. const auto & cparams = lctx.cparams;
  5619. const auto n_batch = cparams.n_batch;
  5620. GGML_ASSERT(n_tokens <= n_batch);
  5621. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5622. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5623. const int64_t t_start_us = ggml_time_us();
  5624. #ifdef GGML_USE_MPI
  5625. // TODO: needs fix after #3228
  5626. GGML_ASSERT(false && "not implemented");
  5627. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5628. #endif
  5629. GGML_ASSERT(n_threads > 0);
  5630. auto & kv_self = lctx.kv_self;
  5631. const int64_t n_embd = hparams.n_embd;
  5632. const int64_t n_vocab = hparams.n_vocab;
  5633. // helpers for smoother batch API transition
  5634. // after deprecating the llama_eval calls, these will be removed
  5635. std::vector<llama_pos> pos;
  5636. std::vector<int32_t> n_seq_id;
  5637. std::vector<llama_seq_id *> seq_id_arr;
  5638. std::vector<std::vector<llama_seq_id>> seq_id;
  5639. if (batch.pos == nullptr) {
  5640. pos.resize(n_tokens);
  5641. for (uint32_t i = 0; i < n_tokens; i++) {
  5642. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5643. }
  5644. batch.pos = pos.data();
  5645. }
  5646. if (batch.seq_id == nullptr) {
  5647. n_seq_id.resize(n_tokens);
  5648. seq_id.resize(n_tokens);
  5649. seq_id_arr.resize(n_tokens);
  5650. for (uint32_t i = 0; i < n_tokens; i++) {
  5651. n_seq_id[i] = 1;
  5652. seq_id[i].resize(1);
  5653. seq_id[i][0] = batch.all_seq_id;
  5654. seq_id_arr[i] = seq_id[i].data();
  5655. }
  5656. batch.n_seq_id = n_seq_id.data();
  5657. batch.seq_id = seq_id_arr.data();
  5658. }
  5659. // if we have enough unused cells before the current head ->
  5660. // better to start searching from the beginning of the cache, hoping to fill it
  5661. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5662. kv_self.head = 0;
  5663. }
  5664. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5665. return 1;
  5666. }
  5667. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5668. // after enough generations, the benefit from this heuristic disappears
  5669. // if we start defragmenting the cache, the benefit from this will be more important
  5670. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5671. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5672. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5673. ggml_backend_sched_reset(lctx.sched);
  5674. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  5675. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5676. // the output is always the last tensor in the graph
  5677. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5678. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5679. // the embeddings could be the second to last tensor, or the third to last tensor
  5680. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5681. if (strcmp(embeddings->name, "result_norm") != 0) {
  5682. embeddings = gf->nodes[gf->n_nodes - 3];
  5683. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5684. }
  5685. // 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);
  5686. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5687. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5688. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5689. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5690. // with the BLAS calls. need a better solution
  5691. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5692. n_threads = std::min(4, n_threads);
  5693. }
  5694. #ifdef GGML_USE_MPI
  5695. const int64_t n_layer = hparams.n_layer;
  5696. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5697. #endif
  5698. #ifdef GGML_USE_METAL
  5699. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5700. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5701. }
  5702. #endif
  5703. if (lctx.backend_cpu != nullptr) {
  5704. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5705. }
  5706. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5707. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5708. #ifdef GGML_USE_MPI
  5709. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5710. #endif
  5711. // update the kv ring buffer
  5712. {
  5713. if (kv_self.has_shift) {
  5714. kv_self.has_shift = false;
  5715. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5716. kv_self.cells[i].delta = 0;
  5717. }
  5718. }
  5719. kv_self.head += n_tokens;
  5720. // Ensure kv cache head points to a valid index.
  5721. if (kv_self.head >= kv_self.size) {
  5722. kv_self.head = 0;
  5723. }
  5724. }
  5725. #ifdef GGML_PERF
  5726. // print timing information per ggml operation (for debugging purposes)
  5727. // requires GGML_PERF to be defined
  5728. ggml_graph_print(gf);
  5729. #endif
  5730. // plot the computation graph in dot format (for debugging purposes)
  5731. //if (n_past%100 == 0) {
  5732. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5733. //}
  5734. // extract logits
  5735. // TODO: do not compute and extract logits if only embeddings are needed
  5736. // need to update the graphs to skip "result_output"
  5737. {
  5738. auto & logits_out = lctx.logits;
  5739. #ifndef NDEBUG
  5740. auto & logits_valid = lctx.logits_valid;
  5741. logits_valid.clear();
  5742. logits_valid.resize(n_tokens);
  5743. logits_out.clear();
  5744. #endif
  5745. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5746. GGML_ASSERT(res_backend != nullptr);
  5747. if (batch.logits) {
  5748. logits_out.resize(n_vocab * n_tokens);
  5749. for (uint32_t i = 0; i < n_tokens; i++) {
  5750. if (batch.logits[i] == 0) {
  5751. continue;
  5752. }
  5753. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5754. #ifndef NDEBUG
  5755. logits_valid[i] = true;
  5756. #endif
  5757. }
  5758. } else if (lctx.logits_all) {
  5759. logits_out.resize(n_vocab * n_tokens);
  5760. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5761. #ifndef NDEBUG
  5762. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5763. #endif
  5764. } else {
  5765. logits_out.resize(n_vocab);
  5766. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5767. #ifndef NDEBUG
  5768. logits_valid[0] = true;
  5769. #endif
  5770. }
  5771. ggml_backend_synchronize(res_backend);
  5772. }
  5773. // extract embeddings
  5774. if (!lctx.embedding.empty()) {
  5775. auto & embedding_out = lctx.embedding;
  5776. embedding_out.resize(n_embd);
  5777. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5778. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5779. ggml_backend_synchronize(embeddings_backend);
  5780. }
  5781. // measure the performance only for the single-token evals
  5782. if (n_tokens == 1) {
  5783. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5784. lctx.n_eval++;
  5785. }
  5786. else if (n_tokens > 1) {
  5787. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5788. lctx.n_p_eval += n_tokens;
  5789. }
  5790. // get a more accurate load time, upon first eval
  5791. // TODO: fix this
  5792. if (!lctx.has_evaluated_once) {
  5793. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5794. lctx.has_evaluated_once = true;
  5795. }
  5796. return 0;
  5797. }
  5798. //
  5799. // tokenizer
  5800. //
  5801. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5802. return vocab.type;
  5803. }
  5804. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5805. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5806. }
  5807. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5808. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5809. }
  5810. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5811. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5812. }
  5813. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5814. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5815. }
  5816. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5817. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5818. }
  5819. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5820. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5821. const auto& token_data = vocab.id_to_token.at(id);
  5822. switch (llama_vocab_get_type(vocab)) {
  5823. case LLAMA_VOCAB_TYPE_SPM: {
  5824. auto buf = token_data.text.substr(3, 2);
  5825. return strtol(buf.c_str(), NULL, 16);
  5826. }
  5827. case LLAMA_VOCAB_TYPE_BPE: {
  5828. GGML_ASSERT(false);
  5829. return unicode_to_bytes_bpe(token_data.text);
  5830. }
  5831. default:
  5832. GGML_ASSERT(false);
  5833. }
  5834. }
  5835. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5836. static const char * hex = "0123456789ABCDEF";
  5837. switch (llama_vocab_get_type(vocab)) {
  5838. case LLAMA_VOCAB_TYPE_SPM: {
  5839. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5840. return vocab.token_to_id.at(buf);
  5841. }
  5842. case LLAMA_VOCAB_TYPE_BPE: {
  5843. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5844. }
  5845. default:
  5846. GGML_ASSERT(false);
  5847. }
  5848. }
  5849. static void llama_escape_whitespace(std::string & text) {
  5850. replace_all(text, " ", "\xe2\x96\x81");
  5851. }
  5852. static void llama_unescape_whitespace(std::string & word) {
  5853. replace_all(word, "\xe2\x96\x81", " ");
  5854. }
  5855. struct llm_symbol {
  5856. using index = int;
  5857. index prev;
  5858. index next;
  5859. const char * text;
  5860. size_t n;
  5861. };
  5862. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5863. // SPM tokenizer
  5864. // original implementation:
  5865. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5866. struct llm_bigram_spm {
  5867. struct comparator {
  5868. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5869. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5870. }
  5871. };
  5872. using queue_storage = std::vector<llm_bigram_spm>;
  5873. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5874. llm_symbol::index left;
  5875. llm_symbol::index right;
  5876. float score;
  5877. size_t size;
  5878. };
  5879. struct llm_tokenizer_spm {
  5880. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5881. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5882. // split string into utf8 chars
  5883. int index = 0;
  5884. size_t offs = 0;
  5885. while (offs < text.size()) {
  5886. llm_symbol sym;
  5887. size_t len = utf8_len(text[offs]);
  5888. sym.text = text.c_str() + offs;
  5889. sym.n = std::min(len, text.size() - offs);
  5890. offs += sym.n;
  5891. sym.prev = index - 1;
  5892. sym.next = offs == text.size() ? -1 : index + 1;
  5893. index++;
  5894. symbols.emplace_back(sym);
  5895. }
  5896. // seed the work queue with all possible 2-character tokens.
  5897. for (size_t i = 1; i < symbols.size(); ++i) {
  5898. try_add_bigram(i - 1, i);
  5899. }
  5900. // keep substituting the highest frequency pairs for as long as we can.
  5901. while (!work_queue.empty()) {
  5902. auto bigram = work_queue.top();
  5903. work_queue.pop();
  5904. auto & left_sym = symbols[bigram.left];
  5905. auto & right_sym = symbols[bigram.right];
  5906. // if one of the symbols already got merged, skip it.
  5907. if (left_sym.n == 0 || right_sym.n == 0 ||
  5908. left_sym.n + right_sym.n != bigram.size) {
  5909. continue;
  5910. }
  5911. // merge the right sym into the left one
  5912. left_sym.n += right_sym.n;
  5913. right_sym.n = 0;
  5914. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5915. // remove the right sym from the chain
  5916. left_sym.next = right_sym.next;
  5917. if (right_sym.next >= 0) {
  5918. symbols[right_sym.next].prev = bigram.left;
  5919. }
  5920. // find more substitutions
  5921. try_add_bigram(left_sym.prev, bigram.left);
  5922. try_add_bigram(bigram.left, left_sym.next);
  5923. }
  5924. for (int i = 0; i != -1; i = symbols[i].next) {
  5925. auto & symbol = symbols[i];
  5926. resegment(symbol, output);
  5927. }
  5928. }
  5929. private:
  5930. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5931. auto text = std::string(symbol.text, symbol.n);
  5932. auto token = vocab.token_to_id.find(text);
  5933. // Do we need to support is_unused?
  5934. if (token != vocab.token_to_id.end()) {
  5935. output.push_back((*token).second);
  5936. return;
  5937. }
  5938. const auto p = rev_merge.find(text);
  5939. if (p == rev_merge.end()) {
  5940. // output any symbols that did not form tokens as bytes.
  5941. for (int j = 0; j < (int)symbol.n; ++j) {
  5942. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5943. output.push_back(token_id);
  5944. }
  5945. return;
  5946. }
  5947. resegment(symbols[p->second.first], output);
  5948. resegment(symbols[p->second.second], output);
  5949. }
  5950. void try_add_bigram(int left, int right) {
  5951. if (left == -1 || right == -1) {
  5952. return;
  5953. }
  5954. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5955. auto token = vocab.token_to_id.find(text);
  5956. if (token == vocab.token_to_id.end()) {
  5957. return;
  5958. }
  5959. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5960. return;
  5961. }
  5962. const auto & tok_data = vocab.id_to_token[(*token).second];
  5963. llm_bigram_spm bigram;
  5964. bigram.left = left;
  5965. bigram.right = right;
  5966. bigram.score = tok_data.score;
  5967. bigram.size = text.size();
  5968. work_queue.push(bigram);
  5969. // Do we need to support is_unused?
  5970. rev_merge[text] = std::make_pair(left, right);
  5971. }
  5972. const llama_vocab & vocab;
  5973. std::vector<llm_symbol> symbols;
  5974. llm_bigram_spm::queue work_queue;
  5975. std::map<std::string, std::pair<int, int>> rev_merge;
  5976. };
  5977. // BPE tokenizer
  5978. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5979. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5980. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5981. struct llm_bigram_bpe {
  5982. struct comparator {
  5983. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5984. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5985. }
  5986. };
  5987. using queue_storage = std::vector<llm_bigram_bpe>;
  5988. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5989. llm_symbol::index left;
  5990. llm_symbol::index right;
  5991. std::string text;
  5992. int rank;
  5993. size_t size;
  5994. };
  5995. struct llm_tokenizer_bpe {
  5996. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5997. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5998. int final_prev_index = -1;
  5999. auto word_collection = bpe_gpt2_preprocess(text);
  6000. symbols_final.clear();
  6001. for (auto & word : word_collection) {
  6002. work_queue = llm_bigram_bpe::queue();
  6003. symbols.clear();
  6004. int index = 0;
  6005. size_t offset = 0;
  6006. while (offset < word.size()) {
  6007. llm_symbol sym;
  6008. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  6009. sym.text = word.c_str() + offset;
  6010. sym.n = char_len;
  6011. offset += sym.n;
  6012. sym.prev = index - 1;
  6013. sym.next = offset == word.size() ? -1 : index + 1;
  6014. index++;
  6015. symbols.emplace_back(sym);
  6016. }
  6017. for (size_t i = 1; i < symbols.size(); ++i) {
  6018. add_new_bigram(i - 1, i);
  6019. }
  6020. // build token(s)
  6021. while (!work_queue.empty()) {
  6022. auto bigram = work_queue.top();
  6023. work_queue.pop();
  6024. auto & left_symbol = symbols[bigram.left];
  6025. auto & right_symbol = symbols[bigram.right];
  6026. if (left_symbol.n == 0 || right_symbol.n == 0) {
  6027. continue;
  6028. }
  6029. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  6030. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  6031. if (left_token + right_token != bigram.text) {
  6032. continue; // Skip this bigram if it's outdated
  6033. }
  6034. // merge the right sym into the left one
  6035. left_symbol.n += right_symbol.n;
  6036. right_symbol.n = 0;
  6037. // remove the right sym from the chain
  6038. left_symbol.next = right_symbol.next;
  6039. if (right_symbol.next >= 0) {
  6040. symbols[right_symbol.next].prev = bigram.left;
  6041. }
  6042. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  6043. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  6044. }
  6045. // add the fnished tokens to the final list keeping correct order for next and prev
  6046. for (auto & sym : symbols) {
  6047. if (sym.n > 0) {
  6048. sym.prev = final_prev_index;
  6049. sym.next = -1;
  6050. if (final_prev_index != -1) {
  6051. symbols_final[final_prev_index].next = symbols_final.size();
  6052. }
  6053. symbols_final.emplace_back(sym);
  6054. final_prev_index = symbols_final.size() - 1;
  6055. }
  6056. }
  6057. }
  6058. symbols = symbols_final;
  6059. if (!symbols.empty()) {
  6060. for (int i = 0; i != -1; i = symbols[i].next) {
  6061. auto & symbol = symbols[i];
  6062. if (symbol.n == 0) {
  6063. continue;
  6064. }
  6065. const std::string str = std::string(symbol.text, symbol.n);
  6066. const auto token = vocab.token_to_id.find(str);
  6067. if (token == vocab.token_to_id.end()) {
  6068. for (auto j = str.begin(); j != str.end(); ++j) {
  6069. std::string byte_str(1, *j);
  6070. auto token_multibyte = vocab.token_to_id.find(byte_str);
  6071. if (token_multibyte == vocab.token_to_id.end()) {
  6072. throw std::runtime_error("ERROR: byte not found in vocab");
  6073. }
  6074. output.push_back((*token_multibyte).second);
  6075. }
  6076. } else {
  6077. output.push_back((*token).second);
  6078. }
  6079. }
  6080. }
  6081. }
  6082. private:
  6083. void add_new_bigram(int left, int right) {
  6084. if (left == -1 || right == -1) {
  6085. return;
  6086. }
  6087. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  6088. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  6089. int rank_found = -1;
  6090. rank_found = vocab.find_bpe_rank(left_token, right_token);
  6091. if (rank_found < 0) {
  6092. return;
  6093. }
  6094. llm_bigram_bpe bigram;
  6095. bigram.left = left;
  6096. bigram.right = right;
  6097. bigram.text = left_token + right_token;
  6098. bigram.size = left_token.size() + right_token.size();
  6099. bigram.rank = rank_found;
  6100. work_queue.push(bigram);
  6101. }
  6102. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  6103. std::vector<std::string> bpe_words;
  6104. std::vector<std::string> bpe_encoded_words;
  6105. std::string token = "";
  6106. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  6107. bool collecting_numeric = false;
  6108. bool collecting_letter = false;
  6109. bool collecting_special = false;
  6110. bool collecting_whitespace_lookahead = false;
  6111. bool collecting = false;
  6112. std::vector<std::string> text_utf;
  6113. text_utf.reserve(text.size());
  6114. bpe_words.reserve(text.size());
  6115. bpe_encoded_words.reserve(text.size());
  6116. auto cps = codepoints_from_utf8(text);
  6117. for (size_t i = 0; i < cps.size(); ++i)
  6118. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  6119. for (int i = 0; i < (int)text_utf.size(); i++) {
  6120. const std::string & utf_char = text_utf[i];
  6121. bool split_condition = false;
  6122. int bytes_remain = text_utf.size() - i;
  6123. // forward backward lookups
  6124. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  6125. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  6126. // handling contractions
  6127. if (!split_condition && bytes_remain >= 2) {
  6128. // 's|'t|'m|'d
  6129. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  6130. split_condition = true;
  6131. }
  6132. if (split_condition) {
  6133. if (token.size()) {
  6134. bpe_words.emplace_back(token); // push previous content as token
  6135. }
  6136. token = utf_char + utf_char_next;
  6137. bpe_words.emplace_back(token);
  6138. token = "";
  6139. i++;
  6140. continue;
  6141. }
  6142. }
  6143. if (!split_condition && bytes_remain >= 3) {
  6144. // 're|'ve|'ll
  6145. if (utf_char == "\'" && (
  6146. (utf_char_next == "r" && utf_char_next_next == "e") ||
  6147. (utf_char_next == "v" && utf_char_next_next == "e") ||
  6148. (utf_char_next == "l" && utf_char_next_next == "l"))
  6149. ) {
  6150. split_condition = true;
  6151. }
  6152. if (split_condition) {
  6153. // current token + next token can be defined
  6154. if (token.size()) {
  6155. bpe_words.emplace_back(token); // push previous content as token
  6156. }
  6157. token = utf_char + utf_char_next + utf_char_next_next;
  6158. bpe_words.emplace_back(token); // the contraction
  6159. token = "";
  6160. i += 2;
  6161. continue;
  6162. }
  6163. }
  6164. if (!split_condition && !collecting) {
  6165. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  6166. collecting_letter = true;
  6167. collecting = true;
  6168. }
  6169. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6170. collecting_numeric = true;
  6171. collecting = true;
  6172. }
  6173. else if (
  6174. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  6175. (!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)
  6176. ) {
  6177. collecting_special = true;
  6178. collecting = true;
  6179. }
  6180. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  6181. collecting_whitespace_lookahead = true;
  6182. collecting = true;
  6183. }
  6184. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  6185. split_condition = true;
  6186. }
  6187. }
  6188. else if (!split_condition && collecting) {
  6189. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  6190. split_condition = true;
  6191. }
  6192. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  6193. split_condition = true;
  6194. }
  6195. 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)) {
  6196. split_condition = true;
  6197. }
  6198. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6199. split_condition = true;
  6200. }
  6201. }
  6202. if (utf_char_next == "") {
  6203. split_condition = true; // final
  6204. token += utf_char;
  6205. }
  6206. if (split_condition) {
  6207. if (token.size()) {
  6208. bpe_words.emplace_back(token);
  6209. }
  6210. token = utf_char;
  6211. collecting = false;
  6212. collecting_letter = false;
  6213. collecting_numeric = false;
  6214. collecting_special = false;
  6215. collecting_whitespace_lookahead = false;
  6216. }
  6217. else {
  6218. token += utf_char;
  6219. }
  6220. }
  6221. for (std::string & word : bpe_words) {
  6222. std::string encoded_token = "";
  6223. for (char & c : word) {
  6224. encoded_token += bytes_to_unicode_bpe(c);
  6225. }
  6226. bpe_encoded_words.emplace_back(encoded_token);
  6227. }
  6228. return bpe_encoded_words;
  6229. }
  6230. const llama_vocab & vocab;
  6231. std::vector<llm_symbol> symbols;
  6232. std::vector<llm_symbol> symbols_final;
  6233. llm_bigram_bpe::queue work_queue;
  6234. };
  6235. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  6236. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6237. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6238. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6239. struct fragment_buffer_variant{
  6240. fragment_buffer_variant(llama_vocab::id _token)
  6241. :
  6242. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6243. token(_token),
  6244. raw_text(_dummy),
  6245. offset(0),
  6246. length(0){}
  6247. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6248. :
  6249. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6250. token((llama_vocab::id)-1),
  6251. raw_text(_raw_text),
  6252. offset(_offset),
  6253. length(_length){
  6254. GGML_ASSERT( _offset >= 0 );
  6255. GGML_ASSERT( _length >= 1 );
  6256. GGML_ASSERT( offset + length <= raw_text.length() );
  6257. }
  6258. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6259. const llama_vocab::id token;
  6260. const std::string _dummy;
  6261. const std::string & raw_text;
  6262. const uint64_t offset;
  6263. const uint64_t length;
  6264. };
  6265. // #define PRETOKENIZERDEBUG
  6266. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  6267. {
  6268. // for each special token
  6269. for (const auto & st: vocab.special_tokens_cache) {
  6270. const auto & special_token = st.first;
  6271. const auto & special_id = st.second;
  6272. // for each text fragment
  6273. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  6274. while (it != buffer.end()) {
  6275. auto & fragment = (*it);
  6276. // if a fragment is text ( not yet processed )
  6277. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  6278. auto * raw_text = &(fragment.raw_text);
  6279. auto raw_text_base_offset = fragment.offset;
  6280. auto raw_text_base_length = fragment.length;
  6281. // loop over the text
  6282. while (true) {
  6283. // find the first occurrence of a given special token in this fragment
  6284. // passing offset argument only limit the "search area" but match coordinates
  6285. // are still relative to the source full raw_text
  6286. auto match = raw_text->find(special_token, raw_text_base_offset);
  6287. // no occurrences found, stop processing this fragment for a given special token
  6288. if (match == std::string::npos) break;
  6289. // check if match is within bounds of offset <-> length
  6290. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  6291. #ifdef PRETOKENIZERDEBUG
  6292. LLAMA_LOG_WARN("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());
  6293. #endif
  6294. auto source = std::distance(buffer.begin(), it);
  6295. // if match is further than base offset
  6296. // then we have some text to the left of it
  6297. if (match > raw_text_base_offset) {
  6298. // left
  6299. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  6300. const int64_t left_reminder_length = match - raw_text_base_offset;
  6301. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  6302. #ifdef PRETOKENIZERDEBUG
  6303. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  6304. #endif
  6305. it++;
  6306. }
  6307. // special token
  6308. buffer.emplace_after(it, special_id);
  6309. it++;
  6310. // right
  6311. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  6312. const int64_t right_reminder_offset = match + special_token.length();
  6313. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  6314. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  6315. #ifdef PRETOKENIZERDEBUG
  6316. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  6317. #endif
  6318. it++;
  6319. if (source == 0) {
  6320. buffer.erase_after(buffer.before_begin());
  6321. } else {
  6322. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6323. }
  6324. // repeat for the right side
  6325. raw_text_base_offset = right_reminder_offset;
  6326. raw_text_base_length = right_reminder_length;
  6327. #ifdef PRETOKENIZERDEBUG
  6328. LLAMA_LOG_WARN("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());
  6329. #endif
  6330. } else {
  6331. if (source == 0) {
  6332. buffer.erase_after(buffer.before_begin());
  6333. } else {
  6334. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6335. }
  6336. break;
  6337. }
  6338. }
  6339. }
  6340. it++;
  6341. }
  6342. }
  6343. }
  6344. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  6345. std::vector<llama_vocab::id> output;
  6346. // OG tokenizer behavior:
  6347. //
  6348. // tokenizer.encode('', add_bos=True) returns [1]
  6349. // tokenizer.encode('', add_bos=False) returns []
  6350. if (bos && vocab.special_bos_id != -1) {
  6351. output.push_back(vocab.special_bos_id);
  6352. }
  6353. if (raw_text.empty()) {
  6354. return output;
  6355. }
  6356. std::forward_list<fragment_buffer_variant> fragment_buffer;
  6357. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  6358. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  6359. switch (vocab.type) {
  6360. case LLAMA_VOCAB_TYPE_SPM:
  6361. {
  6362. for (const auto & fragment: fragment_buffer)
  6363. {
  6364. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6365. {
  6366. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  6367. // TODO: It's likely possible to get rid of this string copy entirely
  6368. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  6369. // and passing 'add space prefix' as bool argument
  6370. //
  6371. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6372. if (&fragment == &fragment_buffer.front()) {
  6373. raw_text = " " + raw_text; // prefix with space if the first token is not special
  6374. }
  6375. #ifdef PRETOKENIZERDEBUG
  6376. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6377. #endif
  6378. llm_tokenizer_spm tokenizer(vocab);
  6379. llama_escape_whitespace(raw_text);
  6380. tokenizer.tokenize(raw_text, output);
  6381. }
  6382. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6383. {
  6384. output.push_back(fragment.token);
  6385. }
  6386. }
  6387. } break;
  6388. case LLAMA_VOCAB_TYPE_BPE:
  6389. {
  6390. for (const auto & fragment: fragment_buffer)
  6391. {
  6392. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6393. {
  6394. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6395. #ifdef PRETOKENIZERDEBUG
  6396. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6397. #endif
  6398. llm_tokenizer_bpe tokenizer(vocab);
  6399. tokenizer.tokenize(raw_text, output);
  6400. }
  6401. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6402. {
  6403. output.push_back(fragment.token);
  6404. }
  6405. }
  6406. } break;
  6407. }
  6408. return output;
  6409. }
  6410. //
  6411. // grammar - internal
  6412. //
  6413. struct llama_partial_utf8 {
  6414. uint32_t value; // bit value so far (unshifted)
  6415. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  6416. };
  6417. struct llama_grammar {
  6418. const std::vector<std::vector<llama_grammar_element>> rules;
  6419. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6420. // buffer for partially generated UTF-8 sequence from accepted tokens
  6421. llama_partial_utf8 partial_utf8;
  6422. };
  6423. struct llama_grammar_candidate {
  6424. size_t index;
  6425. const uint32_t * code_points;
  6426. llama_partial_utf8 partial_utf8;
  6427. };
  6428. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  6429. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  6430. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  6431. const std::string & src,
  6432. llama_partial_utf8 partial_start) {
  6433. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  6434. const char * pos = src.c_str();
  6435. std::vector<uint32_t> code_points;
  6436. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  6437. code_points.reserve(src.size() + 1);
  6438. uint32_t value = partial_start.value;
  6439. int n_remain = partial_start.n_remain;
  6440. // continue previous decode, if applicable
  6441. while (*pos != 0 && n_remain > 0) {
  6442. uint8_t next_byte = static_cast<uint8_t>(*pos);
  6443. if ((next_byte >> 6) != 2) {
  6444. // invalid sequence, abort
  6445. code_points.push_back(0);
  6446. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  6447. }
  6448. value = (value << 6) + (next_byte & 0x3F);
  6449. ++pos;
  6450. --n_remain;
  6451. }
  6452. if (partial_start.n_remain > 0 && n_remain == 0) {
  6453. code_points.push_back(value);
  6454. }
  6455. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  6456. while (*pos != 0) {
  6457. uint8_t first_byte = static_cast<uint8_t>(*pos);
  6458. uint8_t highbits = first_byte >> 4;
  6459. n_remain = lookup[highbits] - 1;
  6460. if (n_remain < 0) {
  6461. // invalid sequence, abort
  6462. code_points.clear();
  6463. code_points.push_back(0);
  6464. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  6465. }
  6466. uint8_t mask = (1 << (7 - n_remain)) - 1;
  6467. value = first_byte & mask;
  6468. ++pos;
  6469. while (*pos != 0 && n_remain > 0) {
  6470. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  6471. ++pos;
  6472. --n_remain;
  6473. }
  6474. if (n_remain == 0) {
  6475. code_points.push_back(value);
  6476. }
  6477. }
  6478. code_points.push_back(0);
  6479. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  6480. }
  6481. // returns true iff pos points to the end of one of the definitions of a rule
  6482. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  6483. switch (pos->type) {
  6484. case LLAMA_GRETYPE_END: return true; // NOLINT
  6485. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  6486. default: return false;
  6487. }
  6488. }
  6489. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  6490. // asserts that pos is pointing to a char range element
  6491. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  6492. const llama_grammar_element * pos,
  6493. const uint32_t chr) {
  6494. bool found = false;
  6495. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6496. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  6497. do {
  6498. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6499. // inclusive range, e.g. [a-z]
  6500. found = found || (pos->value <= chr && chr <= pos[1].value);
  6501. pos += 2;
  6502. } else {
  6503. // exact char match, e.g. [a] or "a"
  6504. found = found || pos->value == chr;
  6505. pos += 1;
  6506. }
  6507. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6508. return std::make_pair(found == is_positive_char, pos);
  6509. }
  6510. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  6511. // range at pos (regular or inverse range)
  6512. // asserts that pos is pointing to a char range element
  6513. static bool llama_grammar_match_partial_char(
  6514. const llama_grammar_element * pos,
  6515. const llama_partial_utf8 partial_utf8) {
  6516. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6517. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6518. uint32_t partial_value = partial_utf8.value;
  6519. int n_remain = partial_utf8.n_remain;
  6520. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6521. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6522. return false;
  6523. }
  6524. // range of possible code points this partial UTF-8 sequence could complete to
  6525. uint32_t low = partial_value << (n_remain * 6);
  6526. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6527. if (low == 0) {
  6528. if (n_remain == 2) {
  6529. low = 1 << 11;
  6530. } else if (n_remain == 3) {
  6531. low = 1 << 16;
  6532. }
  6533. }
  6534. do {
  6535. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6536. // inclusive range, e.g. [a-z]
  6537. if (pos->value <= high && low <= pos[1].value) {
  6538. return is_positive_char;
  6539. }
  6540. pos += 2;
  6541. } else {
  6542. // exact char match, e.g. [a] or "a"
  6543. if (low <= pos->value && pos->value <= high) {
  6544. return is_positive_char;
  6545. }
  6546. pos += 1;
  6547. }
  6548. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6549. return !is_positive_char;
  6550. }
  6551. // transforms a grammar pushdown stack into N possible stacks, all ending
  6552. // at a character range (terminal element)
  6553. static void llama_grammar_advance_stack(
  6554. const std::vector<std::vector<llama_grammar_element>> & rules,
  6555. const std::vector<const llama_grammar_element *> & stack,
  6556. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6557. if (stack.empty()) {
  6558. new_stacks.emplace_back(stack);
  6559. return;
  6560. }
  6561. const llama_grammar_element * pos = stack.back();
  6562. switch (pos->type) {
  6563. case LLAMA_GRETYPE_RULE_REF: {
  6564. const size_t rule_id = static_cast<size_t>(pos->value);
  6565. const llama_grammar_element * subpos = rules[rule_id].data();
  6566. do {
  6567. // init new stack without the top (pos)
  6568. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6569. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6570. // if this rule ref is followed by another element, add that to stack
  6571. new_stack.push_back(pos + 1);
  6572. }
  6573. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6574. // if alternate is nonempty, add to stack
  6575. new_stack.push_back(subpos);
  6576. }
  6577. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6578. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6579. // scan to end of alternate def
  6580. subpos++;
  6581. }
  6582. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6583. // there's another alternate def of this rule to process
  6584. subpos++;
  6585. } else {
  6586. break;
  6587. }
  6588. } while (true);
  6589. break;
  6590. }
  6591. case LLAMA_GRETYPE_CHAR:
  6592. case LLAMA_GRETYPE_CHAR_NOT:
  6593. new_stacks.emplace_back(stack);
  6594. break;
  6595. default:
  6596. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6597. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6598. // those
  6599. GGML_ASSERT(false);
  6600. }
  6601. }
  6602. // takes a set of possible pushdown stacks on a grammar, which are required to
  6603. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6604. // produces the N possible stacks if the given char is accepted at those
  6605. // positions
  6606. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6607. const std::vector<std::vector<llama_grammar_element>> & rules,
  6608. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6609. const uint32_t chr) {
  6610. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6611. for (const auto & stack : stacks) {
  6612. if (stack.empty()) {
  6613. continue;
  6614. }
  6615. auto match = llama_grammar_match_char(stack.back(), chr);
  6616. if (match.first) {
  6617. const llama_grammar_element * pos = match.second;
  6618. // update top of stack to next element, if any
  6619. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6620. if (!llama_grammar_is_end_of_sequence(pos)) {
  6621. new_stack.push_back(pos);
  6622. }
  6623. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6624. }
  6625. }
  6626. return new_stacks;
  6627. }
  6628. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6629. const std::vector<std::vector<llama_grammar_element>> & rules,
  6630. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6631. const std::vector<llama_grammar_candidate> & candidates);
  6632. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6633. const std::vector<std::vector<llama_grammar_element>> & rules,
  6634. const std::vector<const llama_grammar_element *> & stack,
  6635. const std::vector<llama_grammar_candidate> & candidates) {
  6636. std::vector<llama_grammar_candidate> rejects;
  6637. if (stack.empty()) {
  6638. for (const auto & tok : candidates) {
  6639. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6640. rejects.push_back(tok);
  6641. }
  6642. }
  6643. return rejects;
  6644. }
  6645. const llama_grammar_element * stack_pos = stack.back();
  6646. std::vector<llama_grammar_candidate> next_candidates;
  6647. for (const auto & tok : candidates) {
  6648. if (*tok.code_points == 0) {
  6649. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6650. // that cannot satisfy this position in grammar
  6651. if (tok.partial_utf8.n_remain != 0 &&
  6652. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6653. rejects.push_back(tok);
  6654. }
  6655. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6656. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6657. } else {
  6658. rejects.push_back(tok);
  6659. }
  6660. }
  6661. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6662. // update top of stack to next element, if any
  6663. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6664. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6665. stack_after.push_back(stack_pos_after);
  6666. }
  6667. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6668. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6669. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6670. for (const auto & tok : next_rejects) {
  6671. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6672. }
  6673. return rejects;
  6674. }
  6675. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6676. const std::vector<std::vector<llama_grammar_element>> & rules,
  6677. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6678. const std::vector<llama_grammar_candidate> & candidates) {
  6679. GGML_ASSERT(!stacks.empty()); // REVIEW
  6680. if (candidates.empty()) {
  6681. return std::vector<llama_grammar_candidate>();
  6682. }
  6683. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6684. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6685. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6686. }
  6687. return rejects;
  6688. }
  6689. //
  6690. // grammar - external
  6691. //
  6692. struct llama_grammar * llama_grammar_init(
  6693. const llama_grammar_element ** rules,
  6694. size_t n_rules,
  6695. size_t start_rule_index) {
  6696. const llama_grammar_element * pos;
  6697. // copy rule definitions into vectors
  6698. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6699. for (size_t i = 0; i < n_rules; i++) {
  6700. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6701. vec_rules[i].push_back(*pos);
  6702. }
  6703. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6704. }
  6705. // loop over alternates of start rule to build initial stacks
  6706. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6707. pos = rules[start_rule_index];
  6708. do {
  6709. std::vector<const llama_grammar_element *> stack;
  6710. if (!llama_grammar_is_end_of_sequence(pos)) {
  6711. // if alternate is nonempty, add to stack
  6712. stack.push_back(pos);
  6713. }
  6714. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6715. while (!llama_grammar_is_end_of_sequence(pos)) {
  6716. // scan to end of alternate def
  6717. pos++;
  6718. }
  6719. if (pos->type == LLAMA_GRETYPE_ALT) {
  6720. // there's another alternate def of this rule to process
  6721. pos++;
  6722. } else {
  6723. break;
  6724. }
  6725. } while (true);
  6726. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6727. }
  6728. void llama_grammar_free(struct llama_grammar * grammar) {
  6729. delete grammar;
  6730. }
  6731. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6732. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6733. // redirect elements in stacks to point to new rules
  6734. for (size_t is = 0; is < result->stacks.size(); is++) {
  6735. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6736. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6737. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6738. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6739. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6740. }
  6741. }
  6742. }
  6743. }
  6744. }
  6745. return result;
  6746. }
  6747. //
  6748. // sampling
  6749. //
  6750. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6751. if (seed == LLAMA_DEFAULT_SEED) {
  6752. seed = time(NULL);
  6753. }
  6754. ctx->rng.seed(seed);
  6755. }
  6756. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6757. GGML_ASSERT(candidates->size > 0);
  6758. const int64_t t_start_sample_us = ggml_time_us();
  6759. // Sort the logits in descending order
  6760. if (!candidates->sorted) {
  6761. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6762. return a.logit > b.logit;
  6763. });
  6764. candidates->sorted = true;
  6765. }
  6766. float max_l = candidates->data[0].logit;
  6767. float cum_sum = 0.0f;
  6768. for (size_t i = 0; i < candidates->size; ++i) {
  6769. float p = expf(candidates->data[i].logit - max_l);
  6770. candidates->data[i].p = p;
  6771. cum_sum += p;
  6772. }
  6773. for (size_t i = 0; i < candidates->size; ++i) {
  6774. candidates->data[i].p /= cum_sum;
  6775. }
  6776. if (ctx) {
  6777. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6778. }
  6779. }
  6780. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6781. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  6782. // if (k >= (int32_t)candidates->size) {
  6783. // return;
  6784. // }
  6785. const int64_t t_start_sample_us = ggml_time_us();
  6786. k = std::max(k, (int) min_keep);
  6787. k = std::min(k, (int) candidates->size);
  6788. // Sort scores in descending order
  6789. if (!candidates->sorted) {
  6790. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6791. return a.logit > b.logit;
  6792. };
  6793. if (k <= 128) {
  6794. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6795. } else {
  6796. constexpr int nbuckets = 128;
  6797. constexpr float bucket_low = -10.0f;
  6798. constexpr float bucket_high = 10.0f;
  6799. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  6800. constexpr float bucker_inter = -bucket_low * bucket_scale;
  6801. std::vector<int> bucket_idx(candidates->size);
  6802. std::vector<int> histo(nbuckets, 0);
  6803. for (int i = 0; i < (int)candidates->size; ++i) {
  6804. const float val = candidates->data[i].logit;
  6805. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  6806. ib = std::max(0, std::min(nbuckets-1, ib));
  6807. bucket_idx[i] = ib;
  6808. ++histo[ib];
  6809. }
  6810. int nhave = 0;
  6811. int ib = nbuckets - 1;
  6812. for ( ; ib >= 0; --ib) {
  6813. nhave += histo[ib];
  6814. if (nhave >= k) break;
  6815. }
  6816. std::vector<llama_token_data> tmp_tokens(nhave);
  6817. auto ptr = tmp_tokens.data();
  6818. std::vector<llama_token_data*> bucket_ptrs;
  6819. bucket_ptrs.reserve(nbuckets - ib);
  6820. for (int j = nbuckets - 1; j >= ib; --j) {
  6821. bucket_ptrs.push_back(ptr);
  6822. ptr += histo[j];
  6823. }
  6824. for (int i = 0; i < (int)candidates->size; ++i) {
  6825. int j = bucket_idx[i];
  6826. if (j >= ib) {
  6827. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  6828. }
  6829. }
  6830. ptr = tmp_tokens.data();
  6831. int ndone = 0;
  6832. for (int j = nbuckets-1; j > ib; --j) {
  6833. std::sort(ptr, ptr + histo[j], comp);
  6834. ptr += histo[j];
  6835. ndone += histo[j];
  6836. }
  6837. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  6838. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  6839. }
  6840. candidates->sorted = true;
  6841. }
  6842. candidates->size = k;
  6843. if (ctx) {
  6844. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6845. }
  6846. }
  6847. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6848. if (p >= 1.0f) {
  6849. return;
  6850. }
  6851. llama_sample_softmax(ctx, candidates);
  6852. const int64_t t_start_sample_us = ggml_time_us();
  6853. // Compute the cumulative probabilities
  6854. float cum_sum = 0.0f;
  6855. size_t last_idx = candidates->size;
  6856. for (size_t i = 0; i < candidates->size; ++i) {
  6857. cum_sum += candidates->data[i].p;
  6858. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6859. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6860. if (cum_sum >= p && i + 1 >= min_keep) {
  6861. last_idx = i + 1;
  6862. break;
  6863. }
  6864. }
  6865. // Resize the output vector to keep only the top-p tokens
  6866. candidates->size = last_idx;
  6867. if (ctx) {
  6868. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6869. }
  6870. }
  6871. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6872. if (p <= 0.0f || !candidates->size) {
  6873. return;
  6874. }
  6875. const int64_t t_start_sample_us = ggml_time_us();
  6876. bool min_p_applied = false;
  6877. // if the candidates aren't sorted, try the unsorted implementation first
  6878. if (!candidates->sorted) {
  6879. std::vector<llama_token_data> filtered_tokens;
  6880. float max_logit = -FLT_MAX;
  6881. for (size_t i = 0; i < candidates->size; ++i) {
  6882. max_logit = std::max(max_logit, candidates->data[i].logit);
  6883. }
  6884. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  6885. for (size_t i = 0; i < candidates->size; ++i) {
  6886. if (candidates->data[i].logit >= min_logit) {
  6887. filtered_tokens.push_back(candidates->data[i]);
  6888. }
  6889. }
  6890. // if we have enough values the operation was a success
  6891. if (filtered_tokens.size() >= min_keep) {
  6892. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  6893. candidates->size = filtered_tokens.size();
  6894. min_p_applied = true;
  6895. }
  6896. }
  6897. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  6898. if (!min_p_applied) {
  6899. // Sort the logits in descending order
  6900. if (!candidates->sorted) {
  6901. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6902. return a.logit > b.logit;
  6903. });
  6904. candidates->sorted = true;
  6905. }
  6906. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  6907. size_t i = 1; // first token always matches
  6908. for (; i < candidates->size; ++i) {
  6909. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  6910. break; // prob too small
  6911. }
  6912. }
  6913. // Resize the output vector to keep only the matching tokens
  6914. candidates->size = i;
  6915. }
  6916. if (ctx) {
  6917. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6918. }
  6919. }
  6920. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6921. if (z >= 1.0f || candidates->size <= 2) {
  6922. return;
  6923. }
  6924. llama_sample_softmax(nullptr, candidates);
  6925. const int64_t t_start_sample_us = ggml_time_us();
  6926. // Compute the first and second derivatives
  6927. std::vector<float> first_derivatives(candidates->size - 1);
  6928. std::vector<float> second_derivatives(candidates->size - 2);
  6929. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6930. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6931. }
  6932. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6933. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6934. }
  6935. // Calculate absolute value of second derivatives
  6936. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6937. second_derivatives[i] = std::abs(second_derivatives[i]);
  6938. }
  6939. // Normalize the second derivatives
  6940. {
  6941. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6942. if (second_derivatives_sum > 1e-6f) {
  6943. for (float & value : second_derivatives) {
  6944. value /= second_derivatives_sum;
  6945. }
  6946. } else {
  6947. for (float & value : second_derivatives) {
  6948. value = 1.0f / second_derivatives.size();
  6949. }
  6950. }
  6951. }
  6952. float cum_sum = 0.0f;
  6953. size_t last_idx = candidates->size;
  6954. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6955. cum_sum += second_derivatives[i];
  6956. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6957. if (cum_sum > z && i >= min_keep) {
  6958. last_idx = i;
  6959. break;
  6960. }
  6961. }
  6962. // Resize the output vector to keep only the tokens above the tail location
  6963. candidates->size = last_idx;
  6964. if (ctx) {
  6965. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6966. }
  6967. }
  6968. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6969. // Reference implementation:
  6970. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6971. if (p >= 1.0f) {
  6972. return;
  6973. }
  6974. // Compute the softmax of logits and calculate entropy
  6975. llama_sample_softmax(nullptr, candidates);
  6976. const int64_t t_start_sample_us = ggml_time_us();
  6977. float entropy = 0.0f;
  6978. for (size_t i = 0; i < candidates->size; ++i) {
  6979. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6980. }
  6981. // Compute the absolute difference between negative log probability and entropy for each candidate
  6982. std::vector<float> shifted_scores;
  6983. for (size_t i = 0; i < candidates->size; ++i) {
  6984. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6985. shifted_scores.push_back(shifted_score);
  6986. }
  6987. // Sort tokens based on the shifted_scores and their corresponding indices
  6988. std::vector<size_t> indices(candidates->size);
  6989. std::iota(indices.begin(), indices.end(), 0);
  6990. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6991. return shifted_scores[a] < shifted_scores[b];
  6992. });
  6993. // Compute the cumulative probabilities
  6994. float cum_sum = 0.0f;
  6995. size_t last_idx = indices.size();
  6996. for (size_t i = 0; i < indices.size(); ++i) {
  6997. size_t idx = indices[i];
  6998. cum_sum += candidates->data[idx].p;
  6999. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  7000. if (cum_sum > p && i >= min_keep - 1) {
  7001. last_idx = i + 1;
  7002. break;
  7003. }
  7004. }
  7005. // Resize the output vector to keep only the locally typical tokens
  7006. std::vector<llama_token_data> new_candidates;
  7007. for (size_t i = 0; i < last_idx; ++i) {
  7008. size_t idx = indices[i];
  7009. new_candidates.push_back(candidates->data[idx]);
  7010. }
  7011. // Replace the data in candidates with the new_candidates data
  7012. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  7013. candidates->size = new_candidates.size();
  7014. candidates->sorted = false;
  7015. if (ctx) {
  7016. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7017. }
  7018. }
  7019. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  7020. const int64_t t_start_sample_us = ggml_time_us();
  7021. // no need to do anything if there is only one (or zero) candidates
  7022. if(candidates_p->size <= 1) {
  7023. return;
  7024. }
  7025. // Calculate maximum possible entropy
  7026. float max_entropy = -logf(1.0f / candidates_p->size);
  7027. llama_sample_softmax(nullptr, candidates_p);
  7028. // Calculate entropy of the softmax probabilities
  7029. float entropy = 0.0f;
  7030. for (size_t i = 0; i < candidates_p->size; ++i) {
  7031. float prob = candidates_p->data[i].p;
  7032. if (prob > 0.0f) { // Ensure no log(0)
  7033. entropy -= prob * logf(prob);
  7034. }
  7035. }
  7036. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  7037. float normalized_entropy = entropy / max_entropy;
  7038. // Map the normalized entropy to the desired temperature range using the power function
  7039. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  7040. #ifdef DEBUG
  7041. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  7042. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  7043. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  7044. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  7045. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  7046. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  7047. #endif
  7048. // Apply the dynamically calculated temperature scaling
  7049. for (size_t i = 0; i < candidates_p->size; ++i) {
  7050. candidates_p->data[i].logit /= dyn_temp;
  7051. }
  7052. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  7053. double max_l_double = candidates_p->data[0].logit;
  7054. double cum_sum_double = 0.0;
  7055. for (size_t i = 0; i < candidates_p->size; ++i) {
  7056. double p = exp(candidates_p->data[i].logit - max_l_double);
  7057. candidates_p->data[i].p = p; // Store the scaled probability
  7058. cum_sum_double += p;
  7059. }
  7060. for (size_t i = 0; i < candidates_p->size; ++i) {
  7061. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  7062. }
  7063. #ifdef DEBUG
  7064. // Print the updated top 25 probabilities after temperature scaling
  7065. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  7066. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  7067. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  7068. }
  7069. #endif
  7070. if (ctx) {
  7071. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7072. }
  7073. }
  7074. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7075. const int64_t t_start_sample_us = ggml_time_us();
  7076. for (size_t i = 0; i < candidates_p->size; ++i) {
  7077. candidates_p->data[i].logit /= temp;
  7078. }
  7079. if (ctx) {
  7080. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7081. }
  7082. }
  7083. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7084. llama_sample_temp(ctx, candidates_p, temp);
  7085. }
  7086. void llama_sample_repetition_penalties(
  7087. struct llama_context * ctx,
  7088. llama_token_data_array * candidates,
  7089. const llama_token * last_tokens,
  7090. size_t penalty_last_n,
  7091. float penalty_repeat,
  7092. float penalty_freq,
  7093. float penalty_present) {
  7094. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  7095. return;
  7096. }
  7097. const int64_t t_start_sample_us = ggml_time_us();
  7098. // Create a frequency map to count occurrences of each token in last_tokens
  7099. std::unordered_map<llama_token, int> token_count;
  7100. for (size_t i = 0; i < penalty_last_n; ++i) {
  7101. token_count[last_tokens[i]]++;
  7102. }
  7103. // Apply frequency and presence penalties to the candidates
  7104. for (size_t i = 0; i < candidates->size; ++i) {
  7105. const auto token_iter = token_count.find(candidates->data[i].id);
  7106. if (token_iter == token_count.end()) {
  7107. continue;
  7108. }
  7109. const int count = token_iter->second;
  7110. // 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.
  7111. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  7112. if (candidates->data[i].logit <= 0) {
  7113. candidates->data[i].logit *= penalty_repeat;
  7114. } else {
  7115. candidates->data[i].logit /= penalty_repeat;
  7116. }
  7117. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  7118. }
  7119. candidates->sorted = false;
  7120. if (ctx) {
  7121. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7122. }
  7123. }
  7124. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  7125. GGML_ASSERT(ctx);
  7126. const int64_t t_start_sample_us = ggml_time_us();
  7127. bool allow_eos = false;
  7128. for (const auto & stack : grammar->stacks) {
  7129. if (stack.empty()) {
  7130. allow_eos = true;
  7131. break;
  7132. }
  7133. }
  7134. const llama_token eos = llama_token_eos(&ctx->model);
  7135. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  7136. candidates_decoded.reserve(candidates->size);
  7137. std::vector<llama_grammar_candidate> candidates_grammar;
  7138. candidates_grammar.reserve(candidates->size);
  7139. for (size_t i = 0; i < candidates->size; ++i) {
  7140. const llama_token id = candidates->data[i].id;
  7141. const std::string piece = llama_token_to_piece(ctx, id);
  7142. if (id == eos) {
  7143. if (!allow_eos) {
  7144. candidates->data[i].logit = -INFINITY;
  7145. }
  7146. } else if (piece.empty() || piece[0] == 0) {
  7147. candidates->data[i].logit = -INFINITY;
  7148. } else {
  7149. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  7150. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  7151. }
  7152. }
  7153. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  7154. for (const auto & reject : rejects) {
  7155. candidates->data[reject.index].logit = -INFINITY;
  7156. }
  7157. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7158. }
  7159. static void llama_log_softmax(float * array, size_t size) {
  7160. float max_l = *std::max_element(array, array + size);
  7161. float sum = 0.f;
  7162. for (size_t i = 0; i < size; ++i) {
  7163. float p = expf(array[i] - max_l);
  7164. sum += p;
  7165. array[i] = p;
  7166. }
  7167. for (size_t i = 0; i < size; ++i) {
  7168. array[i] = logf(array[i] / sum);
  7169. }
  7170. }
  7171. void llama_sample_apply_guidance(
  7172. struct llama_context * ctx,
  7173. float * logits,
  7174. float * logits_guidance,
  7175. float scale) {
  7176. GGML_ASSERT(ctx);
  7177. const auto t_start_sample_us = ggml_time_us();
  7178. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  7179. llama_log_softmax(logits, n_vocab);
  7180. llama_log_softmax(logits_guidance, n_vocab);
  7181. for (int i = 0; i < n_vocab; ++i) {
  7182. auto & l = logits[i];
  7183. const auto & g = logits_guidance[i];
  7184. l = scale * (l - g) + g;
  7185. }
  7186. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7187. }
  7188. void llama_sample_classifier_free_guidance(
  7189. struct llama_context * ctx,
  7190. llama_token_data_array * candidates,
  7191. struct llama_context * guidance_ctx,
  7192. float scale) {
  7193. GGML_ASSERT(ctx);
  7194. int64_t t_start_sample_us;
  7195. t_start_sample_us = ggml_time_us();
  7196. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  7197. GGML_ASSERT(n_vocab == candidates->size);
  7198. GGML_ASSERT(!candidates->sorted);
  7199. std::vector<float> logits_base(n_vocab);
  7200. for (size_t i = 0; i < n_vocab; ++i) {
  7201. logits_base[i] = candidates->data[i].logit;
  7202. }
  7203. float * logits_guidance = llama_get_logits(guidance_ctx);
  7204. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7205. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  7206. t_start_sample_us = ggml_time_us();
  7207. for (size_t i = 0; i < n_vocab; ++i) {
  7208. candidates->data[i].logit = logits_base[i];
  7209. }
  7210. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7211. }
  7212. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  7213. GGML_ASSERT(ctx);
  7214. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  7215. int64_t t_start_sample_us;
  7216. t_start_sample_us = ggml_time_us();
  7217. llama_sample_softmax(nullptr, candidates);
  7218. // Estimate s_hat using the most probable m tokens
  7219. float s_hat = 0.0;
  7220. float sum_ti_bi = 0.0;
  7221. float sum_ti_sq = 0.0;
  7222. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  7223. float t_i = logf(float(i + 2) / float(i + 1));
  7224. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  7225. sum_ti_bi += t_i * b_i;
  7226. sum_ti_sq += t_i * t_i;
  7227. }
  7228. s_hat = sum_ti_bi / sum_ti_sq;
  7229. // Compute k from the estimated s_hat and target surprise value
  7230. float epsilon_hat = s_hat - 1;
  7231. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  7232. // Sample the next word X using top-k sampling
  7233. llama_sample_top_k(nullptr, candidates, int(k), 1);
  7234. if (ctx) {
  7235. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7236. }
  7237. llama_token X = llama_sample_token(ctx, candidates);
  7238. t_start_sample_us = ggml_time_us();
  7239. // Compute error as the difference between observed surprise and target surprise value
  7240. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7241. return candidate.id == X;
  7242. }));
  7243. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7244. float e = observed_surprise - tau;
  7245. // Update mu using the learning rate and error
  7246. *mu = *mu - eta * e;
  7247. if (ctx) {
  7248. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7249. }
  7250. return X;
  7251. }
  7252. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  7253. int64_t t_start_sample_us;
  7254. t_start_sample_us = ggml_time_us();
  7255. llama_sample_softmax(ctx, candidates);
  7256. // Truncate the words with surprise values greater than mu
  7257. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7258. return -log2f(candidate.p) > *mu;
  7259. }));
  7260. if (candidates->size == 0) {
  7261. candidates->size = 1;
  7262. }
  7263. if (ctx) {
  7264. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7265. }
  7266. // Normalize the probabilities of the remaining words
  7267. llama_sample_softmax(ctx, candidates);
  7268. // Sample the next word X from the remaining words
  7269. llama_token X = llama_sample_token(ctx, candidates);
  7270. t_start_sample_us = ggml_time_us();
  7271. // Compute error as the difference between observed surprise and target surprise value
  7272. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7273. return candidate.id == X;
  7274. }));
  7275. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7276. float e = observed_surprise - tau;
  7277. // Update mu using the learning rate and error
  7278. *mu = *mu - eta * e;
  7279. if (ctx) {
  7280. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7281. }
  7282. return X;
  7283. }
  7284. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  7285. const int64_t t_start_sample_us = ggml_time_us();
  7286. // Find max element
  7287. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7288. return a.logit < b.logit;
  7289. });
  7290. llama_token result = max_iter->id;
  7291. if (ctx) {
  7292. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7293. ctx->n_sample++;
  7294. }
  7295. return result;
  7296. }
  7297. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  7298. GGML_ASSERT(ctx);
  7299. const int64_t t_start_sample_us = ggml_time_us();
  7300. llama_sample_softmax(nullptr, candidates);
  7301. std::vector<float> probs;
  7302. probs.reserve(candidates->size);
  7303. for (size_t i = 0; i < candidates->size; ++i) {
  7304. probs.push_back(candidates->data[i].p);
  7305. }
  7306. std::discrete_distribution<> dist(probs.begin(), probs.end());
  7307. auto & rng = ctx->rng;
  7308. int idx = dist(rng);
  7309. llama_token result = candidates->data[idx].id;
  7310. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7311. ctx->n_sample++;
  7312. return result;
  7313. }
  7314. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  7315. const int64_t t_start_sample_us = ggml_time_us();
  7316. if (token == llama_token_eos(&ctx->model)) {
  7317. for (const auto & stack : grammar->stacks) {
  7318. if (stack.empty()) {
  7319. return;
  7320. }
  7321. }
  7322. GGML_ASSERT(false);
  7323. }
  7324. const std::string piece = llama_token_to_piece(ctx, token);
  7325. // Note terminating 0 in decoded string
  7326. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  7327. const auto & code_points = decoded.first;
  7328. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  7329. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  7330. }
  7331. grammar->partial_utf8 = decoded.second;
  7332. GGML_ASSERT(!grammar->stacks.empty());
  7333. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7334. }
  7335. //
  7336. // Beam search
  7337. //
  7338. struct llama_beam {
  7339. std::vector<llama_token> tokens;
  7340. float p; // Cumulative beam probability (renormalized relative to all beams)
  7341. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  7342. // Sort beams by probability. In case of ties, prefer beams at eob.
  7343. bool operator<(const llama_beam & rhs) const {
  7344. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  7345. }
  7346. // Shift off first n tokens and discard them.
  7347. void shift_tokens(const size_t n) {
  7348. if (n) {
  7349. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  7350. tokens.resize(tokens.size() - n);
  7351. }
  7352. }
  7353. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  7354. };
  7355. // A struct for calculating logit-related info.
  7356. struct llama_logit_info {
  7357. const float * const logits;
  7358. const int n_vocab;
  7359. const float max_l;
  7360. const float normalizer;
  7361. struct sum_exp {
  7362. float max_l;
  7363. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  7364. };
  7365. llama_logit_info(llama_context * ctx)
  7366. : logits(llama_get_logits(ctx))
  7367. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  7368. , max_l(*std::max_element(logits, logits + n_vocab))
  7369. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  7370. { }
  7371. llama_token_data get_token_data(const llama_token token_id) const {
  7372. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  7373. return {token_id, logits[token_id], p};
  7374. }
  7375. // Return top k token_data by logit.
  7376. std::vector<llama_token_data> top_k(size_t k) {
  7377. std::vector<llama_token_data> min_heap; // min-heap by logit
  7378. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  7379. min_heap.reserve(k_min);
  7380. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  7381. min_heap.push_back(get_token_data(token_id));
  7382. }
  7383. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  7384. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  7385. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  7386. if (min_heap.front().logit < logits[token_id]) {
  7387. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  7388. min_heap.back().id = token_id;
  7389. min_heap.back().logit = logits[token_id];
  7390. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  7391. }
  7392. }
  7393. return min_heap;
  7394. }
  7395. float probability_from_logit(float logit) const {
  7396. return normalizer * std::exp(logit - max_l);
  7397. }
  7398. };
  7399. struct llama_beam_search_data {
  7400. llama_context * ctx;
  7401. size_t n_beams;
  7402. int n_past;
  7403. int n_predict;
  7404. std::vector<llama_beam> beams;
  7405. std::vector<llama_beam> next_beams;
  7406. // Re-calculated on each loop iteration
  7407. size_t common_prefix_length;
  7408. // Used to communicate to/from callback on beams state.
  7409. std::vector<llama_beam_view> beam_views;
  7410. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  7411. : ctx(ctx)
  7412. , n_beams(n_beams)
  7413. , n_past(n_past)
  7414. , n_predict(n_predict)
  7415. , beam_views(n_beams) {
  7416. beams.reserve(n_beams);
  7417. next_beams.reserve(n_beams);
  7418. }
  7419. // Collapse beams to a single beam given by index.
  7420. void collapse_beams(const size_t beam_idx) {
  7421. if (0u < beam_idx) {
  7422. std::swap(beams[0], beams[beam_idx]);
  7423. }
  7424. beams.resize(1);
  7425. }
  7426. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  7427. // The repetitive patterns below reflect the 2 stages of heaps:
  7428. // * Gather elements until the vector is full, then call std::make_heap() on it.
  7429. // * If the heap is full and a new element is found that should be included, pop the
  7430. // least element to the back(), replace it with the new, then push it into the heap.
  7431. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  7432. // Min-heaps use a greater-than comparator.
  7433. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  7434. if (beam.eob) {
  7435. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  7436. if (next_beams.size() < n_beams) {
  7437. next_beams.push_back(std::move(beam));
  7438. if (next_beams.size() == n_beams) {
  7439. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7440. }
  7441. } else if (next_beams.front().p < beam.p) {
  7442. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7443. next_beams.back() = std::move(beam);
  7444. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7445. }
  7446. } else {
  7447. // beam is not at end-of-sentence, so branch with next top_k tokens.
  7448. if (!beam.tokens.empty()) {
  7449. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  7450. }
  7451. llama_logit_info logit_info(ctx);
  7452. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  7453. size_t i=0;
  7454. if (next_beams.size() < n_beams) {
  7455. for (; next_beams.size() < n_beams ; ++i) {
  7456. llama_beam next_beam = beam;
  7457. next_beam.tokens.push_back(next_tokens[i].id);
  7458. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7459. next_beams.push_back(std::move(next_beam));
  7460. }
  7461. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7462. } else {
  7463. for (; next_beams.front().p == 0.0f ; ++i) {
  7464. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7465. next_beams.back() = beam;
  7466. next_beams.back().tokens.push_back(next_tokens[i].id);
  7467. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7468. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7469. }
  7470. }
  7471. for (; i < n_beams ; ++i) {
  7472. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  7473. if (next_beams.front().p < next_p) {
  7474. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7475. next_beams.back() = beam;
  7476. next_beams.back().tokens.push_back(next_tokens[i].id);
  7477. next_beams.back().p = next_p;
  7478. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7479. }
  7480. }
  7481. }
  7482. }
  7483. // Find common_prefix_length based on beams.
  7484. // Requires beams is not empty.
  7485. size_t find_common_prefix_length() {
  7486. size_t common_prefix_length = beams[0].tokens.size();
  7487. for (size_t i = 1 ; i < beams.size() ; ++i) {
  7488. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  7489. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  7490. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  7491. common_prefix_length = j;
  7492. break;
  7493. }
  7494. }
  7495. }
  7496. return common_prefix_length;
  7497. }
  7498. // Construct beams_state to send back to caller via the callback function.
  7499. // Side effect: set common_prefix_length = find_common_prefix_length();
  7500. llama_beams_state get_beams_state(const bool last_call) {
  7501. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7502. beam_views[i] = beams[i].view();
  7503. }
  7504. common_prefix_length = find_common_prefix_length();
  7505. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  7506. }
  7507. // Loop:
  7508. // * while i < n_predict, AND
  7509. // * any of the beams have not yet reached end-of-beam (eob), AND
  7510. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  7511. // (since all other beam probabilities can only decrease)
  7512. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  7513. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  7514. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  7515. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  7516. !beams[top_beam_index()].eob ; ++i) {
  7517. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  7518. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  7519. if (common_prefix_length) {
  7520. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  7521. n_past += common_prefix_length;
  7522. }
  7523. // Zero-out next_beam probabilities to place them last in following min-heap.
  7524. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  7525. for (llama_beam & beam : beams) {
  7526. beam.shift_tokens(common_prefix_length);
  7527. fill_next_beams_by_top_probabilities(beam);
  7528. }
  7529. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  7530. beams.swap(next_beams);
  7531. renormalize_beam_probabilities(beams);
  7532. }
  7533. collapse_beams(top_beam_index());
  7534. callback(callback_data, get_beams_state(true));
  7535. }
  7536. // As beams grow, the cumulative probabilities decrease.
  7537. // Renormalize them to avoid floating point underflow.
  7538. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  7539. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  7540. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  7541. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  7542. }
  7543. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  7544. size_t top_beam_index() {
  7545. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  7546. }
  7547. // Copy (p,eob) for each beam which may have been changed by the callback.
  7548. void update_beams_from_beam_views() {
  7549. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7550. beams[i].p = beam_views[i].p;
  7551. beams[i].eob = beam_views[i].eob;
  7552. }
  7553. }
  7554. };
  7555. void llama_beam_search(llama_context * ctx,
  7556. llama_beam_search_callback_fn_t callback, void * callback_data,
  7557. size_t n_beams, int n_past, int n_predict) {
  7558. assert(ctx);
  7559. const int64_t t_start_sample_us = ggml_time_us();
  7560. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  7561. beam_search_data.loop(callback, callback_data);
  7562. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7563. ctx->n_sample++;
  7564. }
  7565. //
  7566. // quantization
  7567. //
  7568. struct quantize_state_internal {
  7569. const llama_model & model;
  7570. const llama_model_quantize_params * params;
  7571. int n_attention_wv = 0;
  7572. int n_ffn_down = 0;
  7573. int n_ffn_gate = 0;
  7574. int n_ffn_up = 0;
  7575. int i_attention_wv = 0;
  7576. int i_ffn_down = 0;
  7577. int i_ffn_gate = 0;
  7578. int i_ffn_up = 0;
  7579. int n_k_quantized = 0;
  7580. int n_fallback = 0;
  7581. bool has_imatrix = false;
  7582. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  7583. : model(model)
  7584. , params(params)
  7585. {}
  7586. };
  7587. static void llama_convert_tensor_internal(
  7588. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  7589. const size_t nelements, const int nthread
  7590. ) {
  7591. if (output.size() < nelements) {
  7592. output.resize(nelements);
  7593. }
  7594. float * f32_output = (float *) output.data();
  7595. ggml_type_traits_t qtype;
  7596. if (ggml_is_quantized(tensor->type)) {
  7597. qtype = ggml_internal_get_type_traits(tensor->type);
  7598. if (qtype.to_float == NULL) {
  7599. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  7600. }
  7601. } else if (tensor->type != GGML_TYPE_F16) {
  7602. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  7603. }
  7604. if (nthread < 2) {
  7605. if (tensor->type == GGML_TYPE_F16) {
  7606. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  7607. } else if (ggml_is_quantized(tensor->type)) {
  7608. qtype.to_float(tensor->data, f32_output, nelements);
  7609. } else {
  7610. GGML_ASSERT(false); // unreachable
  7611. }
  7612. return;
  7613. }
  7614. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  7615. size_t block_size_bytes = ggml_type_size(tensor->type);
  7616. GGML_ASSERT(nelements % block_size == 0);
  7617. size_t nblocks = nelements / block_size;
  7618. size_t blocks_per_thread = nblocks / nthread;
  7619. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  7620. size_t in_buff_offs = 0;
  7621. size_t out_buff_offs = 0;
  7622. for (int tnum = 0; tnum < nthread; tnum++) {
  7623. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  7624. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  7625. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  7626. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  7627. if (typ == GGML_TYPE_F16) {
  7628. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  7629. } else {
  7630. qtype.to_float(inbuf, outbuf, nels);
  7631. }
  7632. };
  7633. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  7634. in_buff_offs += thr_block_bytes;
  7635. out_buff_offs += thr_elems;
  7636. }
  7637. for (auto & w : workers) { w.join(); }
  7638. workers.clear();
  7639. }
  7640. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  7641. const std::string name = ggml_get_name(tensor);
  7642. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7643. const llm_arch arch = qs.model.arch;
  7644. const auto tn = LLM_TN(arch);
  7645. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  7646. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  7647. };
  7648. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  7649. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  7650. if (n_expert > 1) {
  7651. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  7652. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  7653. // for getting the current layer as I initially thought, and we need to resort to parsing the
  7654. // tensor name.
  7655. n_layer /= n_expert;
  7656. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  7657. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  7658. }
  7659. if (i_layer < 0 || i_layer >= n_layer) {
  7660. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  7661. }
  7662. }
  7663. return std::make_pair(i_layer, n_layer);
  7664. };
  7665. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  7666. int nx = tensor->ne[0];
  7667. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  7668. new_type = GGML_TYPE_Q8_0;
  7669. }
  7670. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7671. new_type = GGML_TYPE_Q5_K;
  7672. }
  7673. else if (new_type != GGML_TYPE_Q8_0) {
  7674. new_type = GGML_TYPE_Q6_K;
  7675. }
  7676. } else if (name == "token_embd.weight") {
  7677. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7678. new_type = GGML_TYPE_Q2_K;
  7679. }
  7680. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  7681. new_type = GGML_TYPE_Q4_K;
  7682. }
  7683. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7684. if (name.find("attn_v.weight") != std::string::npos) {
  7685. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  7686. else new_type = GGML_TYPE_Q2_K;
  7687. ++qs.i_attention_wv;
  7688. }
  7689. else if (name.find("ffn_down") != std::string::npos) {
  7690. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  7691. ++qs.i_ffn_down;
  7692. }
  7693. } else if (name.find("attn_v.weight") != std::string::npos) {
  7694. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  7695. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  7696. }
  7697. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  7698. new_type = GGML_TYPE_Q4_K;
  7699. }
  7700. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && qs.model.hparams.n_gqa() >= 4) {
  7701. new_type = GGML_TYPE_Q4_K;
  7702. }
  7703. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7704. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7705. }
  7706. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7707. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  7708. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  7709. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  7710. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  7711. (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;
  7712. if (qs.model.type == MODEL_70B) {
  7713. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7714. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7715. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7716. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7717. }
  7718. if (qs.model.hparams.n_expert == 8) {
  7719. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7720. // TODO: explore better strategies
  7721. new_type = GGML_TYPE_Q8_0;
  7722. }
  7723. ++qs.i_attention_wv;
  7724. } else if (name.find("attn_k.weight") != std::string::npos) {
  7725. if (qs.model.hparams.n_expert == 8) {
  7726. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7727. // TODO: explore better strategies
  7728. new_type = GGML_TYPE_Q8_0;
  7729. }
  7730. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7731. new_type = GGML_TYPE_Q2_K;
  7732. }
  7733. } else if (name.find("ffn_down") != std::string::npos) {
  7734. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  7735. int i_layer = info.first, n_layer = info.second;
  7736. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7737. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7738. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  7739. }
  7740. //else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  7741. // if (i_layer < n_layer/8) new_type = GGML_TYPE_Q5_K;
  7742. //}
  7743. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7744. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  7745. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  7746. : GGML_TYPE_Q3_K;
  7747. }
  7748. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7749. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7750. }
  7751. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7752. if (arch == LLM_ARCH_FALCON) {
  7753. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  7754. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7755. } else {
  7756. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7757. }
  7758. }
  7759. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7760. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  7761. new_type = GGML_TYPE_Q5_K;
  7762. }
  7763. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  7764. && qs.has_imatrix && i_layer < n_layer/8) {
  7765. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  7766. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  7767. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  7768. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  7769. }
  7770. ++qs.i_ffn_down;
  7771. } else if (name.find("attn_output.weight") != std::string::npos) {
  7772. if (arch != LLM_ARCH_FALCON) {
  7773. if (qs.model.hparams.n_expert == 8) {
  7774. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  7775. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  7776. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7777. new_type = GGML_TYPE_Q5_K;
  7778. }
  7779. } else {
  7780. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7781. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_Q3_K;
  7782. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7783. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7784. }
  7785. } else {
  7786. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7787. }
  7788. }
  7789. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7790. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7791. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7792. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7793. }
  7794. else if (name.find("ffn_gate") != std::string::npos) {
  7795. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  7796. int i_layer = info.first, n_layer = info.second;
  7797. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7798. new_type = GGML_TYPE_Q2_K;
  7799. }
  7800. ++qs.i_ffn_gate;
  7801. }
  7802. else if (name.find("ffn_up") != std::string::npos) {
  7803. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  7804. int i_layer = info.first, n_layer = info.second;
  7805. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7806. new_type = GGML_TYPE_Q2_K;
  7807. }
  7808. ++qs.i_ffn_up;
  7809. }
  7810. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7811. //}
  7812. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7813. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7814. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7815. //}
  7816. // This can be used to reduce the size of the Q5_K_S model.
  7817. // The associated PPL increase is fully in line with the size reduction
  7818. //else {
  7819. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7820. //}
  7821. bool convert_incompatible_tensor = false;
  7822. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7823. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  7824. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS ||
  7825. new_type == GGML_TYPE_IQ3_XXS) {
  7826. int nx = tensor->ne[0];
  7827. int ny = tensor->ne[1];
  7828. if (nx % QK_K != 0) {
  7829. 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));
  7830. convert_incompatible_tensor = true;
  7831. } else {
  7832. ++qs.n_k_quantized;
  7833. }
  7834. }
  7835. if (convert_incompatible_tensor) {
  7836. switch (new_type) {
  7837. case GGML_TYPE_IQ2_XXS:
  7838. case GGML_TYPE_IQ2_XS:
  7839. case GGML_TYPE_IQ3_XXS:
  7840. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  7841. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  7842. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  7843. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  7844. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  7845. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  7846. }
  7847. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  7848. ++qs.n_fallback;
  7849. }
  7850. return new_type;
  7851. }
  7852. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  7853. ggml_type quantized_type;
  7854. llama_ftype ftype = params->ftype;
  7855. switch (params->ftype) {
  7856. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  7857. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  7858. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  7859. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  7860. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  7861. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  7862. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  7863. // K-quants
  7864. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  7865. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  7866. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  7867. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  7868. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  7869. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  7870. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  7871. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  7872. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  7873. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  7874. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  7875. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  7876. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  7877. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:quantized_type = GGML_TYPE_IQ3_XXS; break;
  7878. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  7879. }
  7880. int nthread = params->nthread;
  7881. if (nthread <= 0) {
  7882. nthread = std::thread::hardware_concurrency();
  7883. }
  7884. // mmap consistently increases speed Linux, and also increases speed on Windows with
  7885. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  7886. #if defined(__linux__) || defined(_WIN32)
  7887. constexpr bool use_mmap = true;
  7888. #else
  7889. constexpr bool use_mmap = false;
  7890. #endif
  7891. llama_model_loader ml(fname_inp, use_mmap, NULL);
  7892. ml.init_mapping(false); // no prefetching?
  7893. llama_model model;
  7894. llm_load_arch(ml, model);
  7895. llm_load_hparams(ml, model);
  7896. struct quantize_state_internal qs(model, params);
  7897. if (params->only_copy) {
  7898. ftype = model.ftype;
  7899. }
  7900. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  7901. if (params->imatrix) {
  7902. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  7903. if (imatrix_data) {
  7904. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  7905. qs.has_imatrix = true;
  7906. }
  7907. }
  7908. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  7909. struct gguf_context * ctx_out = gguf_init_empty();
  7910. // copy the KV pairs from the input file
  7911. gguf_set_kv (ctx_out, ml.ctx_gguf);
  7912. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  7913. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  7914. for (int i = 0; i < ml.n_tensors; ++i) {
  7915. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7916. const std::string name = ggml_get_name(meta);
  7917. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7918. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  7919. ++qs.n_attention_wv;
  7920. }
  7921. else if (name.find("ffn_down") != std::string::npos) {
  7922. ++qs.n_ffn_down;
  7923. }
  7924. else if (name.find("ffn_gate") != std::string::npos) {
  7925. ++qs.n_ffn_gate;
  7926. }
  7927. else if (name.find("ffn_up") != std::string::npos) {
  7928. ++qs.n_ffn_up;
  7929. }
  7930. }
  7931. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  7932. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  7933. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  7934. }
  7935. size_t total_size_org = 0;
  7936. size_t total_size_new = 0;
  7937. std::vector<int64_t> hist_all(1 << 4, 0);
  7938. std::vector<std::thread> workers;
  7939. workers.reserve(nthread);
  7940. std::mutex mutex;
  7941. int idx = 0;
  7942. std::vector<no_init<uint8_t>> read_data;
  7943. std::vector<no_init<uint8_t>> work;
  7944. std::vector<no_init<float>> f32_conv_buf;
  7945. // populate the original tensors so we get an initial meta data
  7946. for (int i = 0; i < ml.n_tensors; ++i) {
  7947. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7948. gguf_add_tensor(ctx_out, meta);
  7949. }
  7950. std::ofstream fout(fname_out, std::ios::binary);
  7951. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  7952. const size_t meta_size = gguf_get_meta_size(ctx_out);
  7953. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  7954. // placeholder for the meta data
  7955. ::zeros(fout, meta_size);
  7956. for (int i = 0; i < ml.n_tensors; ++i) {
  7957. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7958. const std::string name = ggml_get_name(tensor);
  7959. if (!ml.use_mmap) {
  7960. if (read_data.size() < ggml_nbytes(tensor)) {
  7961. read_data.resize(ggml_nbytes(tensor));
  7962. }
  7963. tensor->data = read_data.data();
  7964. }
  7965. ml.load_data_for(tensor);
  7966. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7967. ++idx, ml.n_tensors,
  7968. ggml_get_name(tensor),
  7969. llama_format_tensor_shape(tensor).c_str(),
  7970. ggml_type_name(tensor->type));
  7971. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7972. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7973. // quantize only 2D tensors
  7974. quantize &= (ggml_n_dims(tensor) == 2);
  7975. quantize &= params->quantize_output_tensor || name != "output.weight";
  7976. quantize &= !params->only_copy;
  7977. // do not quantize expert gating tensors
  7978. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7979. enum ggml_type new_type;
  7980. void * new_data;
  7981. size_t new_size;
  7982. if (quantize) {
  7983. new_type = quantized_type;
  7984. if (!params->pure) {
  7985. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7986. }
  7987. // If we've decided to quantize to the same type the tensor is already
  7988. // in then there's nothing to do.
  7989. quantize = tensor->type != new_type;
  7990. }
  7991. if (!quantize) {
  7992. new_type = tensor->type;
  7993. new_data = tensor->data;
  7994. new_size = ggml_nbytes(tensor);
  7995. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7996. } else {
  7997. const size_t nelements = ggml_nelements(tensor);
  7998. const float * imatrix = nullptr;
  7999. if (imatrix_data) {
  8000. auto it = imatrix_data->find(tensor->name);
  8001. if (it == imatrix_data->end()) {
  8002. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  8003. } else {
  8004. if (it->second.size() == (size_t)tensor->ne[0]) {
  8005. imatrix = it->second.data();
  8006. } else {
  8007. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  8008. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  8009. }
  8010. }
  8011. }
  8012. if ((new_type == GGML_TYPE_IQ2_XXS ||
  8013. new_type == GGML_TYPE_IQ2_XS ||
  8014. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  8015. LLAMA_LOG_ERROR("\n\n============================================================\n");
  8016. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  8017. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  8018. LLAMA_LOG_ERROR("============================================================\n\n");
  8019. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  8020. }
  8021. float * f32_data;
  8022. if (tensor->type == GGML_TYPE_F32) {
  8023. f32_data = (float *) tensor->data;
  8024. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  8025. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  8026. } else {
  8027. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  8028. f32_data = (float *) f32_conv_buf.data();
  8029. }
  8030. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  8031. fflush(stdout);
  8032. if (work.size() < nelements * 4) {
  8033. work.resize(nelements * 4); // upper bound on size
  8034. }
  8035. new_data = work.data();
  8036. std::array<int64_t, 1 << 4> hist_cur = {};
  8037. const int n_per_row = tensor->ne[0];
  8038. const int nrows = nelements / n_per_row;
  8039. static const int min_chunk_size = 32 * 512;
  8040. const int chunk_size = n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row);
  8041. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  8042. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  8043. if (nthread_use < 2) {
  8044. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  8045. } else {
  8046. int counter = 0;
  8047. new_size = 0;
  8048. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  8049. nrows, n_per_row, imatrix]() {
  8050. std::array<int64_t, 1 << 4> local_hist = {};
  8051. const int nrows_per_chunk = chunk_size / n_per_row;
  8052. size_t local_size = 0;
  8053. while (true) {
  8054. std::unique_lock<std::mutex> lock(mutex);
  8055. int first_row = counter; counter += nrows_per_chunk;
  8056. if (first_row >= nrows) {
  8057. if (local_size > 0) {
  8058. for (int j=0; j<int(local_hist.size()); ++j) {
  8059. hist_cur[j] += local_hist[j];
  8060. }
  8061. new_size += local_size;
  8062. }
  8063. break;
  8064. }
  8065. lock.unlock();
  8066. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  8067. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  8068. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  8069. }
  8070. };
  8071. for (int it = 0; it < nthread_use - 1; ++it) {
  8072. workers.emplace_back(compute);
  8073. }
  8074. compute();
  8075. for (auto & w : workers) { w.join(); }
  8076. workers.clear();
  8077. }
  8078. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  8079. int64_t tot_count = 0;
  8080. for (size_t i = 0; i < hist_cur.size(); i++) {
  8081. hist_all[i] += hist_cur[i];
  8082. tot_count += hist_cur[i];
  8083. }
  8084. if (tot_count > 0) {
  8085. LLAMA_LOG_INFO(" | hist: ");
  8086. for (size_t i = 0; i < hist_cur.size(); i++) {
  8087. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  8088. }
  8089. }
  8090. LLAMA_LOG_INFO("\n");
  8091. }
  8092. total_size_org += ggml_nbytes(tensor);
  8093. total_size_new += new_size;
  8094. // update the gguf meta data as we go
  8095. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  8096. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  8097. // write tensor data + padding
  8098. fout.write((const char *) new_data, new_size);
  8099. zeros(fout, GGML_PAD(new_size, align) - new_size);
  8100. }
  8101. // go back to beginning of file and write the updated meta data
  8102. {
  8103. fout.seekp(0);
  8104. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  8105. gguf_get_meta_data(ctx_out, data.data());
  8106. fout.write((const char *) data.data(), data.size());
  8107. }
  8108. fout.close();
  8109. gguf_free(ctx_out);
  8110. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  8111. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  8112. // print histogram for all tensors
  8113. {
  8114. int64_t sum_all = 0;
  8115. for (size_t i = 0; i < hist_all.size(); i++) {
  8116. sum_all += hist_all[i];
  8117. }
  8118. if (sum_all > 0) {
  8119. LLAMA_LOG_INFO("%s: hist: ", __func__);
  8120. for (size_t i = 0; i < hist_all.size(); i++) {
  8121. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  8122. }
  8123. LLAMA_LOG_INFO("\n");
  8124. }
  8125. }
  8126. if (qs.n_fallback > 0) {
  8127. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  8128. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  8129. }
  8130. }
  8131. static int llama_apply_lora_from_file_internal(
  8132. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  8133. ) {
  8134. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  8135. const int64_t t_start_lora_us = ggml_time_us();
  8136. llama_file fin(path_lora, "rb");
  8137. // verify magic and version
  8138. {
  8139. uint32_t magic = fin.read_u32();
  8140. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  8141. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  8142. return 1;
  8143. }
  8144. uint32_t format_version = fin.read_u32();
  8145. if (format_version != 1) {
  8146. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  8147. return 1;
  8148. }
  8149. }
  8150. int32_t lora_r = fin.read_u32();
  8151. int32_t lora_alpha = fin.read_u32();
  8152. float scaling = scale * (float)lora_alpha / (float)lora_r;
  8153. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  8154. // load base model
  8155. std::unique_ptr<llama_model_loader> ml;
  8156. if (path_base_model) {
  8157. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  8158. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  8159. ml->init_mapping(/*prefetch*/ false); // no prefetching
  8160. }
  8161. struct tensor_meta {
  8162. std::string name;
  8163. ggml_type type;
  8164. int32_t ne[2];
  8165. size_t offset;
  8166. };
  8167. std::map<std::string, tensor_meta> tensor_meta_map;
  8168. // load all tensor meta
  8169. while (true) {
  8170. if (fin.tell() == fin.size) {
  8171. // eof
  8172. break;
  8173. }
  8174. int32_t n_dims;
  8175. int32_t name_len;
  8176. int32_t ftype;
  8177. fin.read_raw(&n_dims, sizeof(n_dims));
  8178. fin.read_raw(&name_len, sizeof(name_len));
  8179. fin.read_raw(&ftype, sizeof(ftype));
  8180. if (n_dims != 1 && n_dims != 2) {
  8181. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  8182. return 1;
  8183. }
  8184. int32_t ne[2] = { 1, 1 };
  8185. for (int i = 0; i < n_dims; ++i) {
  8186. fin.read_raw(&ne[i], sizeof(ne[i]));
  8187. }
  8188. std::string name;
  8189. {
  8190. GGML_ASSERT(name_len < GGML_MAX_NAME);
  8191. char buf[GGML_MAX_NAME];
  8192. fin.read_raw(buf, name_len);
  8193. name = std::string(buf, name_len);
  8194. }
  8195. // check for lora suffix
  8196. std::string lora_suffix;
  8197. if (name.length() > 6) {
  8198. lora_suffix = name.substr(name.length() - 6);
  8199. }
  8200. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  8201. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  8202. return 1;
  8203. }
  8204. // tensor type
  8205. ggml_type wtype;
  8206. switch (ftype) {
  8207. case 0: wtype = GGML_TYPE_F32; break;
  8208. case 1: wtype = GGML_TYPE_F16; break;
  8209. default:
  8210. {
  8211. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  8212. __func__, ftype);
  8213. return false;
  8214. }
  8215. }
  8216. // data offset
  8217. size_t offset = fin.tell();
  8218. offset = (offset + 31) & -32;
  8219. // skip tensor data
  8220. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  8221. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  8222. }
  8223. bool warned = false;
  8224. int n_tensors = 0;
  8225. // apply
  8226. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  8227. if (backend_cpu == nullptr) {
  8228. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  8229. return 1;
  8230. }
  8231. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  8232. std::vector<no_init<uint8_t>> read_buf;
  8233. for (const auto & it : model.tensors_by_name) {
  8234. const std::string & base_name = it.first;
  8235. ggml_tensor * model_t = it.second;
  8236. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  8237. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  8238. continue;
  8239. }
  8240. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  8241. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  8242. ggml_init_params lora_init_params = {
  8243. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  8244. /* .mem_buffer */ nullptr,
  8245. /* .no_alloc */ true,
  8246. };
  8247. ggml_context * lora_ctx = ggml_init(lora_init_params);
  8248. if (lora_ctx == nullptr) {
  8249. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  8250. ggml_backend_free(backend_cpu);
  8251. return 1;
  8252. }
  8253. // create tensors
  8254. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  8255. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  8256. ggml_set_name(loraA, metaA.name.c_str());
  8257. ggml_set_name(loraB, metaB.name.c_str());
  8258. ggml_tensor * base_t;
  8259. if (ml) {
  8260. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  8261. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  8262. return 1;
  8263. }
  8264. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  8265. } else {
  8266. base_t = ggml_dup_tensor(lora_ctx, model_t);
  8267. }
  8268. ggml_set_name(base_t, base_name.c_str());
  8269. // allocate in backend buffer
  8270. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  8271. if (lora_buf == nullptr) {
  8272. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  8273. return 1;
  8274. }
  8275. // load tensor data
  8276. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  8277. read_buf.resize(ggml_nbytes(tensor));
  8278. fin.seek(tensor_meta.offset, SEEK_SET);
  8279. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  8280. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  8281. };
  8282. load_tensor(metaA, loraA);
  8283. load_tensor(metaB, loraB);
  8284. // load base model tensor data
  8285. if (ml) {
  8286. ml->load_data_for(base_t);
  8287. } else {
  8288. ggml_backend_tensor_copy(model_t, base_t);
  8289. }
  8290. if (ggml_is_quantized(base_t->type) && !warned) {
  8291. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  8292. "use a f16 or f32 base model with --lora-base\n", __func__);
  8293. warned = true;
  8294. }
  8295. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  8296. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  8297. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  8298. ggml_free(lora_ctx);
  8299. ggml_backend_buffer_free(lora_buf);
  8300. ggml_backend_free(backend_cpu);
  8301. return 1;
  8302. }
  8303. auto build_lora_graph = [&]() {
  8304. // w = w + BA*s
  8305. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  8306. ggml_set_name(BA, "BA");
  8307. if (scaling != 1.0f) {
  8308. BA = ggml_scale(lora_ctx, BA, scaling);
  8309. ggml_set_name(BA, "BA_scaled");
  8310. }
  8311. ggml_tensor * r;
  8312. r = ggml_add_inplace(lora_ctx, base_t, BA);
  8313. ggml_set_name(r, "r_add");
  8314. if (base_t->type != model_t->type) {
  8315. // convert the result to the model type
  8316. r = ggml_cast(lora_ctx, r, model_t->type);
  8317. ggml_set_name(r, "r_cast");
  8318. }
  8319. return r;
  8320. };
  8321. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  8322. ggml_tensor * r = build_lora_graph();
  8323. ggml_build_forward_expand(gf, r);
  8324. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  8325. if (graph_buf == nullptr) {
  8326. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  8327. ggml_free(lora_ctx);
  8328. ggml_backend_buffer_free(lora_buf);
  8329. ggml_backend_free(backend_cpu);
  8330. return 1;
  8331. }
  8332. ggml_backend_graph_compute(backend_cpu, gf);
  8333. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  8334. #if 0
  8335. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  8336. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  8337. // sched compute
  8338. ggml_build_forward_expand(gf, build_graph());
  8339. ggml_backend_sched_init_measure(sched, gf);
  8340. // create the graph again, since the previous one was destroyed by the measure
  8341. ggml_graph_clear(gf);
  8342. ggml_build_forward_expand(gf, build_graph());
  8343. ggml_backend_sched_graph_compute(sched, gf);
  8344. ggml_backend_sched_free(sched);
  8345. #endif
  8346. ggml_backend_buffer_free(lora_buf);
  8347. ggml_backend_buffer_free(graph_buf);
  8348. ggml_free(lora_ctx);
  8349. n_tensors++;
  8350. if (n_tensors % 4 == 0) {
  8351. LLAMA_LOG_INFO(".");
  8352. }
  8353. }
  8354. ggml_backend_free(backend_cpu);
  8355. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  8356. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  8357. return 0;
  8358. }
  8359. //
  8360. // interface implementation
  8361. //
  8362. struct llama_model_params llama_model_default_params() {
  8363. struct llama_model_params result = {
  8364. /*.n_gpu_layers =*/ 0,
  8365. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  8366. /*.main_gpu =*/ 0,
  8367. /*.tensor_split =*/ nullptr,
  8368. /*.progress_callback =*/ nullptr,
  8369. /*.progress_callback_user_data =*/ nullptr,
  8370. /*.kv_overrides =*/ nullptr,
  8371. /*.vocab_only =*/ false,
  8372. /*.use_mmap =*/ true,
  8373. /*.use_mlock =*/ false,
  8374. };
  8375. #ifdef GGML_USE_METAL
  8376. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  8377. result.n_gpu_layers = 999;
  8378. #endif
  8379. return result;
  8380. }
  8381. struct llama_context_params llama_context_default_params() {
  8382. struct llama_context_params result = {
  8383. /*.seed =*/ LLAMA_DEFAULT_SEED,
  8384. /*.n_ctx =*/ 512,
  8385. /*.n_batch =*/ 512,
  8386. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  8387. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  8388. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  8389. /*.rope_freq_base =*/ 0.0f,
  8390. /*.rope_freq_scale =*/ 0.0f,
  8391. /*.yarn_ext_factor =*/ -1.0f,
  8392. /*.yarn_attn_factor =*/ 1.0f,
  8393. /*.yarn_beta_fast =*/ 32.0f,
  8394. /*.yarn_beta_slow =*/ 1.0f,
  8395. /*.yarn_orig_ctx =*/ 0,
  8396. /*.cb_eval =*/ nullptr,
  8397. /*.cb_eval_user_data =*/ nullptr,
  8398. /*.type_k =*/ GGML_TYPE_F16,
  8399. /*.type_v =*/ GGML_TYPE_F16,
  8400. /*.mul_mat_q =*/ true,
  8401. /*.logits_all =*/ false,
  8402. /*.embedding =*/ false,
  8403. /*.offload_kqv =*/ true,
  8404. };
  8405. return result;
  8406. }
  8407. struct llama_model_quantize_params llama_model_quantize_default_params() {
  8408. struct llama_model_quantize_params result = {
  8409. /*.nthread =*/ 0,
  8410. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  8411. /*.allow_requantize =*/ false,
  8412. /*.quantize_output_tensor =*/ true,
  8413. /*.only_copy =*/ false,
  8414. /*.pure =*/ false,
  8415. /*.imatrix =*/ nullptr,
  8416. };
  8417. return result;
  8418. }
  8419. size_t llama_max_devices(void) {
  8420. #if defined(GGML_USE_METAL)
  8421. return 1;
  8422. #elif defined(GGML_USE_CUBLAS)
  8423. return GGML_CUDA_MAX_DEVICES;
  8424. #elif defined(GGML_USE_SYCL)
  8425. return GGML_SYCL_MAX_DEVICES;
  8426. #else
  8427. return 1;
  8428. #endif
  8429. }
  8430. bool llama_supports_mmap(void) {
  8431. return llama_mmap::SUPPORTED;
  8432. }
  8433. bool llama_supports_mlock(void) {
  8434. return llama_mlock::SUPPORTED;
  8435. }
  8436. bool llama_supports_gpu_offload(void) {
  8437. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  8438. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  8439. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  8440. return true;
  8441. #else
  8442. return false;
  8443. #endif
  8444. }
  8445. // deprecated:
  8446. bool llama_mmap_supported(void) {
  8447. return llama_supports_mmap();
  8448. }
  8449. bool llama_mlock_supported(void) {
  8450. return llama_supports_mlock();
  8451. }
  8452. void llama_backend_init(bool numa) {
  8453. ggml_time_init();
  8454. // needed to initialize f16 tables
  8455. {
  8456. struct ggml_init_params params = { 0, NULL, false };
  8457. struct ggml_context * ctx = ggml_init(params);
  8458. ggml_free(ctx);
  8459. }
  8460. if (numa) {
  8461. ggml_numa_init();
  8462. }
  8463. #ifdef GGML_USE_MPI
  8464. ggml_mpi_backend_init();
  8465. #endif
  8466. }
  8467. void llama_backend_free(void) {
  8468. #ifdef GGML_USE_MPI
  8469. ggml_mpi_backend_free();
  8470. #endif
  8471. ggml_quantize_free();
  8472. }
  8473. int64_t llama_time_us(void) {
  8474. return ggml_time_us();
  8475. }
  8476. struct llama_model * llama_load_model_from_file(
  8477. const char * path_model,
  8478. struct llama_model_params params) {
  8479. ggml_time_init();
  8480. llama_model * model = new llama_model;
  8481. unsigned cur_percentage = 0;
  8482. if (params.progress_callback == NULL) {
  8483. params.progress_callback_user_data = &cur_percentage;
  8484. params.progress_callback = [](float progress, void * ctx) {
  8485. unsigned * cur_percentage_p = (unsigned *) ctx;
  8486. unsigned percentage = (unsigned) (100 * progress);
  8487. while (percentage > *cur_percentage_p) {
  8488. *cur_percentage_p = percentage;
  8489. LLAMA_LOG_INFO(".");
  8490. if (percentage >= 100) {
  8491. LLAMA_LOG_INFO("\n");
  8492. }
  8493. }
  8494. return true;
  8495. };
  8496. }
  8497. int status = llama_model_load(path_model, *model, params);
  8498. GGML_ASSERT(status <= 0);
  8499. if (status < 0) {
  8500. if (status == -1) {
  8501. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  8502. } else if (status == -2) {
  8503. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  8504. }
  8505. delete model;
  8506. return nullptr;
  8507. }
  8508. return model;
  8509. }
  8510. void llama_free_model(struct llama_model * model) {
  8511. delete model;
  8512. }
  8513. struct llama_context * llama_new_context_with_model(
  8514. struct llama_model * model,
  8515. struct llama_context_params params) {
  8516. if (!model) {
  8517. return nullptr;
  8518. }
  8519. llama_context * ctx = new llama_context(*model);
  8520. const auto & hparams = model->hparams;
  8521. auto & cparams = ctx->cparams;
  8522. cparams.n_batch = params.n_batch;
  8523. cparams.n_threads = params.n_threads;
  8524. cparams.n_threads_batch = params.n_threads_batch;
  8525. cparams.yarn_ext_factor = params.yarn_ext_factor;
  8526. cparams.yarn_attn_factor = params.yarn_attn_factor;
  8527. cparams.yarn_beta_fast = params.yarn_beta_fast;
  8528. cparams.yarn_beta_slow = params.yarn_beta_slow;
  8529. cparams.mul_mat_q = params.mul_mat_q;
  8530. cparams.offload_kqv = params.offload_kqv;
  8531. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  8532. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  8533. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  8534. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  8535. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  8536. hparams.n_ctx_train;
  8537. cparams.cb_eval = params.cb_eval;
  8538. cparams.cb_eval_user_data = params.cb_eval_user_data;
  8539. auto rope_scaling_type = params.rope_scaling_type;
  8540. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  8541. rope_scaling_type = hparams.rope_scaling_type_train;
  8542. }
  8543. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  8544. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  8545. }
  8546. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  8547. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  8548. }
  8549. if (params.seed == LLAMA_DEFAULT_SEED) {
  8550. params.seed = time(NULL);
  8551. }
  8552. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  8553. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  8554. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  8555. ctx->rng = std::mt19937(params.seed);
  8556. ctx->logits_all = params.logits_all;
  8557. const ggml_type type_k = params.type_k;
  8558. const ggml_type type_v = params.type_v;
  8559. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  8560. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  8561. if (!hparams.vocab_only) {
  8562. // initialize backends
  8563. #ifdef GGML_USE_METAL
  8564. if (model->n_gpu_layers > 0) {
  8565. ctx->backend_metal = ggml_backend_metal_init();
  8566. if (ctx->backend_metal == nullptr) {
  8567. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  8568. llama_free(ctx);
  8569. return nullptr;
  8570. }
  8571. ctx->backends.push_back(ctx->backend_metal);
  8572. }
  8573. #elif defined(GGML_USE_CUBLAS)
  8574. if (model->n_gpu_layers > 0) {
  8575. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  8576. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  8577. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  8578. if (backend == nullptr) {
  8579. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  8580. llama_free(ctx);
  8581. return nullptr;
  8582. }
  8583. ctx->backends.push_back(backend);
  8584. } else {
  8585. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  8586. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  8587. ggml_backend_t backend = ggml_backend_cuda_init(device);
  8588. if (backend == nullptr) {
  8589. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  8590. llama_free(ctx);
  8591. return nullptr;
  8592. }
  8593. ctx->backends.push_back(backend);
  8594. }
  8595. }
  8596. }
  8597. #elif defined(GGML_USE_VULKAN)
  8598. if (model->n_gpu_layers > 0) {
  8599. ggml_backend_t backend = ggml_backend_vk_init();
  8600. if (backend == nullptr) {
  8601. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  8602. llama_free(ctx);
  8603. return nullptr;
  8604. }
  8605. ctx->backends.push_back(backend);
  8606. }
  8607. #elif defined(GGML_USE_SYCL)
  8608. if (model->n_gpu_layers > 0) {
  8609. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  8610. if (backend == nullptr) {
  8611. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  8612. llama_free(ctx);
  8613. return nullptr;
  8614. }
  8615. ctx->backends.push_back(backend);
  8616. }
  8617. #elif defined(GGML_USE_KOMPUTE)
  8618. if (model->n_gpu_layers > 0) {
  8619. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  8620. if (backend == nullptr) {
  8621. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  8622. llama_free(ctx);
  8623. return nullptr;
  8624. }
  8625. ctx->backends.push_back(backend);
  8626. }
  8627. #endif
  8628. ctx->backend_cpu = ggml_backend_cpu_init();
  8629. if (ctx->backend_cpu == nullptr) {
  8630. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  8631. llama_free(ctx);
  8632. return nullptr;
  8633. }
  8634. ctx->backends.push_back(ctx->backend_cpu);
  8635. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  8636. cparams.n_ctx, cparams.offload_kqv)) {
  8637. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  8638. llama_free(ctx);
  8639. return nullptr;
  8640. }
  8641. {
  8642. size_t memory_size_k = 0;
  8643. size_t memory_size_v = 0;
  8644. for (auto & k : ctx->kv_self.k_l) {
  8645. memory_size_k += ggml_nbytes(k);
  8646. }
  8647. for (auto & v : ctx->kv_self.v_l) {
  8648. memory_size_v += ggml_nbytes(v);
  8649. }
  8650. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  8651. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  8652. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  8653. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  8654. }
  8655. // resized during inference, reserve maximum
  8656. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  8657. if (params.embedding){
  8658. ctx->embedding.resize(hparams.n_embd);
  8659. }
  8660. // graph inputs
  8661. {
  8662. ggml_init_params init_params = {
  8663. /* .mem_size */ ggml_tensor_overhead()*5,
  8664. /* .mem_buffer */ nullptr,
  8665. /* .no_alloc */ true,
  8666. };
  8667. ctx->ctx_input = ggml_init(init_params);
  8668. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8669. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  8670. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8671. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  8672. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  8673. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  8674. ggml_set_name(ctx->inp_embd, "inp_embd");
  8675. ggml_set_name(ctx->inp_pos, "inp_pos");
  8676. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  8677. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  8678. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  8679. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  8680. ggml_backend_buffer_name(ctx->buf_input),
  8681. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  8682. }
  8683. // scheduler and compute buffers
  8684. {
  8685. // buffer types used for the compute buffer of each backend
  8686. std::vector<ggml_backend_buffer_type_t> backend_buft;
  8687. for (auto * backend : ctx->backends) {
  8688. if (ggml_backend_is_cpu(backend)) {
  8689. // use host buffers for the CPU backend compute buffer
  8690. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  8691. } else {
  8692. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  8693. }
  8694. }
  8695. // buffer used to store the computation graph and the tensor meta data
  8696. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  8697. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  8698. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8699. // build worst-case graph
  8700. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  8701. int n_past = cparams.n_ctx - n_tokens;
  8702. 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
  8703. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  8704. // initialize scheduler with the worst-case graph
  8705. ggml_backend_sched_init_measure(ctx->sched, gf);
  8706. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8707. for (ggml_backend_t backend : ctx->backends) {
  8708. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  8709. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  8710. ggml_backend_buffer_name(buf),
  8711. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8712. }
  8713. // note: the number of splits during measure is higher than during inference due to the kv shift
  8714. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  8715. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  8716. }
  8717. }
  8718. #ifdef GGML_USE_MPI
  8719. ctx->ctx_mpi = ggml_mpi_init();
  8720. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  8721. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  8722. // TODO: needs fix after #3228
  8723. GGML_ASSERT(false && "not implemented");
  8724. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  8725. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  8726. llama_backend_free();
  8727. exit(1);
  8728. }
  8729. #endif
  8730. return ctx;
  8731. }
  8732. void llama_free(struct llama_context * ctx) {
  8733. delete ctx;
  8734. }
  8735. const llama_model * llama_get_model(const struct llama_context * ctx) {
  8736. return &ctx->model;
  8737. }
  8738. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  8739. return ctx->cparams.n_ctx;
  8740. }
  8741. uint32_t llama_n_batch(const struct llama_context * ctx) {
  8742. return ctx->cparams.n_batch;
  8743. }
  8744. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  8745. return model->vocab.type;
  8746. }
  8747. int32_t llama_n_vocab(const struct llama_model * model) {
  8748. return model->vocab.id_to_token.size();
  8749. }
  8750. int32_t llama_n_ctx_train(const struct llama_model * model) {
  8751. return model->hparams.n_ctx_train;
  8752. }
  8753. int32_t llama_n_embd(const struct llama_model * model) {
  8754. return model->hparams.n_embd;
  8755. }
  8756. float llama_rope_freq_scale_train(const struct llama_model * model) {
  8757. return model->hparams.rope_freq_scale_train;
  8758. }
  8759. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  8760. const auto & it = model->gguf_kv.find(key);
  8761. if (it == model->gguf_kv.end()) {
  8762. if (buf_size > 0) {
  8763. buf[0] = '\0';
  8764. }
  8765. return -1;
  8766. }
  8767. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8768. }
  8769. int32_t llama_model_meta_count(const struct llama_model * model) {
  8770. return (int)model->gguf_kv.size();
  8771. }
  8772. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  8773. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8774. if (buf_size > 0) {
  8775. buf[0] = '\0';
  8776. }
  8777. return -1;
  8778. }
  8779. auto it = model->gguf_kv.begin();
  8780. std::advance(it, i);
  8781. return snprintf(buf, buf_size, "%s", it->first.c_str());
  8782. }
  8783. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  8784. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8785. if (buf_size > 0) {
  8786. buf[0] = '\0';
  8787. }
  8788. return -1;
  8789. }
  8790. auto it = model->gguf_kv.begin();
  8791. std::advance(it, i);
  8792. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8793. }
  8794. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  8795. return snprintf(buf, buf_size, "%s %s %s",
  8796. llama_model_arch_name(model->arch).c_str(),
  8797. llama_model_type_name(model->type),
  8798. llama_model_ftype_name(model->ftype).c_str());
  8799. }
  8800. uint64_t llama_model_size(const struct llama_model * model) {
  8801. uint64_t size = 0;
  8802. for (const auto & it : model->tensors_by_name) {
  8803. size += ggml_nbytes(it.second);
  8804. }
  8805. return size;
  8806. }
  8807. uint64_t llama_model_n_params(const struct llama_model * model) {
  8808. uint64_t nparams = 0;
  8809. for (const auto & it : model->tensors_by_name) {
  8810. nparams += ggml_nelements(it.second);
  8811. }
  8812. return nparams;
  8813. }
  8814. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  8815. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  8816. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  8817. return it.first == name;
  8818. });
  8819. if (it == model->tensors_by_name.end()) {
  8820. return nullptr;
  8821. }
  8822. return it->second;
  8823. }
  8824. uint32_t llama_model_quantize(
  8825. const char * fname_inp,
  8826. const char * fname_out,
  8827. const llama_model_quantize_params * params) {
  8828. try {
  8829. llama_model_quantize_internal(fname_inp, fname_out, params);
  8830. return 0;
  8831. } catch (const std::exception & err) {
  8832. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  8833. return 1;
  8834. }
  8835. }
  8836. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  8837. try {
  8838. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  8839. } catch (const std::exception & err) {
  8840. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8841. return 1;
  8842. }
  8843. }
  8844. int32_t llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  8845. try {
  8846. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  8847. } catch (const std::exception & err) {
  8848. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8849. return 1;
  8850. }
  8851. }
  8852. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  8853. struct llama_kv_cache_view result = {
  8854. /*.n_cells = */ 0,
  8855. /*.n_max_seq = */ n_max_seq,
  8856. /*.token_count = */ 0,
  8857. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  8858. /*.max_contiguous = */ 0,
  8859. /*.max_contiguous_idx = */ -1,
  8860. /*.cells = */ nullptr,
  8861. /*.cells_sequences = */ nullptr,
  8862. };
  8863. return result;
  8864. }
  8865. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  8866. if (view->cells != nullptr) {
  8867. free(view->cells);
  8868. view->cells = nullptr;
  8869. }
  8870. if (view->cells_sequences != nullptr) {
  8871. free(view->cells_sequences);
  8872. view->cells_sequences = nullptr;
  8873. }
  8874. }
  8875. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  8876. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  8877. view->n_cells = int32_t(ctx->kv_self.size);
  8878. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  8879. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  8880. view->cells = (struct llama_kv_cache_view_cell *)p;
  8881. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  8882. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  8883. view->cells_sequences = (llama_seq_id *)p;
  8884. }
  8885. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  8886. llama_kv_cache_view_cell * c_curr = view->cells;
  8887. llama_seq_id * cs_curr = view->cells_sequences;
  8888. int32_t used_cells = 0;
  8889. int32_t token_count = 0;
  8890. int32_t curr_contig_idx = -1;
  8891. uint32_t max_contig = 0;
  8892. int32_t max_contig_idx = -1;
  8893. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  8894. const size_t curr_size = kv_cells[i].seq_id.size();
  8895. token_count += curr_size;
  8896. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  8897. if (curr_size > 0) {
  8898. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  8899. max_contig = i - curr_contig_idx;
  8900. max_contig_idx = curr_contig_idx;
  8901. }
  8902. curr_contig_idx = -1;
  8903. } else if (curr_contig_idx < 0) {
  8904. curr_contig_idx = i;
  8905. }
  8906. int seq_idx = 0;
  8907. for (const llama_seq_id it : kv_cells[i].seq_id) {
  8908. if (seq_idx >= view->n_max_seq) {
  8909. break;
  8910. }
  8911. cs_curr[seq_idx] = it;
  8912. seq_idx++;
  8913. }
  8914. if (seq_idx != 0) {
  8915. used_cells++;
  8916. }
  8917. for (; seq_idx < view->n_max_seq; seq_idx++) {
  8918. cs_curr[seq_idx] = -1;
  8919. }
  8920. }
  8921. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  8922. max_contig_idx = curr_contig_idx;
  8923. max_contig = kv_cells.size() - curr_contig_idx;
  8924. }
  8925. view->max_contiguous = max_contig;
  8926. view->max_contiguous_idx = max_contig_idx;
  8927. view->token_count = token_count;
  8928. view->used_cells = used_cells;
  8929. if (uint32_t(used_cells) != ctx->kv_self.used) {
  8930. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  8931. __func__, ctx->kv_self.used, used_cells);
  8932. }
  8933. }
  8934. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  8935. int result = 0;
  8936. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  8937. result += ctx->kv_self.cells[i].seq_id.size();
  8938. }
  8939. return result;
  8940. }
  8941. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  8942. return ctx->kv_self.used;
  8943. }
  8944. void llama_kv_cache_clear(struct llama_context * ctx) {
  8945. llama_kv_cache_clear(ctx->kv_self);
  8946. }
  8947. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  8948. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  8949. }
  8950. 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) {
  8951. if (seq_id_src == seq_id_dst) {
  8952. return;
  8953. }
  8954. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  8955. }
  8956. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  8957. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  8958. }
  8959. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  8960. if (delta == 0) {
  8961. return;
  8962. }
  8963. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  8964. }
  8965. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  8966. if (d == 1) {
  8967. return;
  8968. }
  8969. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  8970. }
  8971. // Returns the *maximum* size of the state
  8972. size_t llama_get_state_size(const struct llama_context * ctx) {
  8973. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  8974. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  8975. const size_t s_rng_size = sizeof(size_t);
  8976. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  8977. const size_t s_logits_size = sizeof(size_t);
  8978. // assume worst case for logits although only currently set ones are serialized
  8979. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  8980. const size_t s_embedding_size = sizeof(size_t);
  8981. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  8982. const size_t s_kv_size = sizeof(size_t);
  8983. const size_t s_kv_ntok = sizeof(int);
  8984. const size_t s_kv = ctx->kv_self.total_size();
  8985. const size_t s_total = (
  8986. + s_rng_size
  8987. + s_rng
  8988. + s_logits_size
  8989. + s_logits
  8990. + s_embedding_size
  8991. + s_embedding
  8992. + s_kv_size
  8993. + s_kv_ntok
  8994. + s_kv
  8995. );
  8996. return s_total;
  8997. }
  8998. // llama_context_data
  8999. struct llama_data_context {
  9000. virtual void write(const void * src, size_t size) = 0;
  9001. virtual size_t get_size_written() = 0;
  9002. virtual ~llama_data_context() = default;
  9003. };
  9004. struct llama_data_buffer_context : llama_data_context {
  9005. uint8_t * ptr;
  9006. size_t size_written = 0;
  9007. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  9008. void write(const void * src, size_t size) override {
  9009. memcpy(ptr, src, size);
  9010. ptr += size;
  9011. size_written += size;
  9012. }
  9013. size_t get_size_written() override {
  9014. return size_written;
  9015. }
  9016. };
  9017. struct llama_data_file_context : llama_data_context {
  9018. llama_file * file;
  9019. size_t size_written = 0;
  9020. llama_data_file_context(llama_file * f) : file(f) {}
  9021. void write(const void * src, size_t size) override {
  9022. file->write_raw(src, size);
  9023. size_written += size;
  9024. }
  9025. size_t get_size_written() override {
  9026. return size_written;
  9027. }
  9028. };
  9029. /** copy state data into either a buffer or file depending on the passed in context
  9030. *
  9031. * file context:
  9032. * llama_file file("/path", "wb");
  9033. * llama_data_file_context data_ctx(&file);
  9034. * llama_copy_state_data(ctx, &data_ctx);
  9035. *
  9036. * buffer context:
  9037. * std::vector<uint8_t> buf(max_size, 0);
  9038. * llama_data_buffer_context data_ctx(&buf.data());
  9039. * llama_copy_state_data(ctx, &data_ctx);
  9040. *
  9041. */
  9042. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  9043. // copy rng
  9044. {
  9045. std::ostringstream rng_ss;
  9046. rng_ss << ctx->rng;
  9047. const std::string & rng_str = rng_ss.str();
  9048. const size_t rng_size = rng_str.size();
  9049. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  9050. data_ctx->write(&rng_size, sizeof(rng_size));
  9051. data_ctx->write(rng_str.data(), rng_size);
  9052. }
  9053. // copy logits
  9054. {
  9055. const size_t logits_size = ctx->logits.size();
  9056. data_ctx->write(&logits_size, sizeof(logits_size));
  9057. if (logits_size) {
  9058. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  9059. }
  9060. }
  9061. // copy embeddings
  9062. {
  9063. const size_t embedding_size = ctx->embedding.size();
  9064. data_ctx->write(&embedding_size, sizeof(embedding_size));
  9065. if (embedding_size) {
  9066. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  9067. }
  9068. }
  9069. // copy kv cache
  9070. {
  9071. const auto & kv_self = ctx->kv_self;
  9072. const auto & hparams = ctx->model.hparams;
  9073. const auto & cparams = ctx->cparams;
  9074. const auto n_layer = hparams.n_layer;
  9075. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  9076. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  9077. const auto n_ctx = cparams.n_ctx;
  9078. const size_t kv_buf_size = kv_self.total_size();
  9079. const uint32_t kv_head = kv_self.head;
  9080. const uint32_t kv_size = kv_self.size;
  9081. const uint32_t kv_used = kv_self.used;
  9082. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  9083. data_ctx->write(&kv_head, sizeof(kv_head));
  9084. data_ctx->write(&kv_size, sizeof(kv_size));
  9085. data_ctx->write(&kv_used, sizeof(kv_used));
  9086. if (kv_buf_size) {
  9087. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9088. std::vector<uint8_t> tmp_buf;
  9089. for (int il = 0; il < (int) n_layer; ++il) {
  9090. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  9091. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  9092. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9093. // v is not contiguous, copy row by row
  9094. tmp_buf.resize(elt_size*kv_head);
  9095. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9096. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  9097. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9098. }
  9099. }
  9100. }
  9101. for (uint32_t i = 0; i < kv_size; ++i) {
  9102. const auto & cell = kv_self.cells[i];
  9103. const llama_pos pos = cell.pos;
  9104. const size_t seq_id_size = cell.seq_id.size();
  9105. data_ctx->write(&pos, sizeof(pos));
  9106. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  9107. for (auto seq_id : cell.seq_id) {
  9108. data_ctx->write(&seq_id, sizeof(seq_id));
  9109. }
  9110. }
  9111. }
  9112. }
  9113. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  9114. llama_data_buffer_context data_ctx(dst);
  9115. llama_copy_state_data_internal(ctx, &data_ctx);
  9116. return data_ctx.get_size_written();
  9117. }
  9118. // Sets the state reading from the specified source address
  9119. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  9120. uint8_t * inp = src;
  9121. // set rng
  9122. {
  9123. size_t rng_size;
  9124. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  9125. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  9126. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  9127. std::istringstream rng_ss(rng_str);
  9128. rng_ss >> ctx->rng;
  9129. GGML_ASSERT(!rng_ss.fail());
  9130. }
  9131. // set logits
  9132. {
  9133. size_t logits_size;
  9134. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  9135. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  9136. if (logits_size) {
  9137. ctx->logits.resize(logits_size);
  9138. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  9139. inp += logits_size * sizeof(float);
  9140. }
  9141. }
  9142. // set embeddings
  9143. {
  9144. size_t embedding_size;
  9145. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  9146. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  9147. if (embedding_size) {
  9148. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  9149. inp += embedding_size * sizeof(float);
  9150. }
  9151. }
  9152. // set kv cache
  9153. {
  9154. const auto & kv_self = ctx->kv_self;
  9155. const auto & hparams = ctx->model.hparams;
  9156. const auto & cparams = ctx->cparams;
  9157. const int n_layer = hparams.n_layer;
  9158. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  9159. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  9160. const int n_ctx = cparams.n_ctx;
  9161. size_t kv_buf_size;
  9162. uint32_t kv_head;
  9163. uint32_t kv_size;
  9164. uint32_t kv_used;
  9165. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  9166. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  9167. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  9168. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  9169. if (kv_buf_size) {
  9170. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  9171. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9172. for (int il = 0; il < (int) n_layer; ++il) {
  9173. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  9174. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  9175. inp += k_size;
  9176. // v is not contiguous, copy row by row
  9177. size_t v_row_size = elt_size*kv_head;
  9178. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9179. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  9180. inp += v_row_size;
  9181. }
  9182. }
  9183. }
  9184. ctx->kv_self.head = kv_head;
  9185. ctx->kv_self.size = kv_size;
  9186. ctx->kv_self.used = kv_used;
  9187. ctx->kv_self.cells.resize(kv_size);
  9188. for (uint32_t i = 0; i < kv_size; ++i) {
  9189. llama_pos pos;
  9190. size_t seq_id_size;
  9191. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  9192. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  9193. ctx->kv_self.cells[i].pos = pos;
  9194. llama_seq_id seq_id;
  9195. for (size_t j = 0; j < seq_id_size; ++j) {
  9196. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  9197. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  9198. }
  9199. }
  9200. }
  9201. const size_t nread = inp - src;
  9202. const size_t max_size = llama_get_state_size(ctx);
  9203. GGML_ASSERT(nread <= max_size);
  9204. return nread;
  9205. }
  9206. 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) {
  9207. llama_file file(path_session, "rb");
  9208. // sanity checks
  9209. {
  9210. const uint32_t magic = file.read_u32();
  9211. const uint32_t version = file.read_u32();
  9212. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  9213. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  9214. return false;
  9215. }
  9216. llama_hparams session_hparams;
  9217. file.read_raw(&session_hparams, sizeof(llama_hparams));
  9218. if (session_hparams != ctx->model.hparams) {
  9219. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  9220. return false;
  9221. }
  9222. }
  9223. // load the prompt
  9224. {
  9225. const uint32_t n_token_count = file.read_u32();
  9226. if (n_token_count > n_token_capacity) {
  9227. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  9228. return false;
  9229. }
  9230. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  9231. *n_token_count_out = n_token_count;
  9232. }
  9233. // restore the context state
  9234. {
  9235. const size_t n_state_size_cur = file.size - file.tell();
  9236. const size_t n_state_size_max = llama_get_state_size(ctx);
  9237. if (n_state_size_cur > n_state_size_max) {
  9238. 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);
  9239. return false;
  9240. }
  9241. std::vector<uint8_t> state_data(n_state_size_max);
  9242. file.read_raw(state_data.data(), n_state_size_cur);
  9243. llama_set_state_data(ctx, state_data.data());
  9244. }
  9245. return true;
  9246. }
  9247. 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) {
  9248. try {
  9249. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  9250. } catch (const std::exception & err) {
  9251. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  9252. return false;
  9253. }
  9254. }
  9255. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  9256. llama_file file(path_session, "wb");
  9257. file.write_u32(LLAMA_SESSION_MAGIC);
  9258. file.write_u32(LLAMA_SESSION_VERSION);
  9259. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  9260. // save the prompt
  9261. file.write_u32((uint32_t) n_token_count);
  9262. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  9263. // save the context state using stream saving
  9264. llama_data_file_context data_ctx(&file);
  9265. llama_copy_state_data_internal(ctx, &data_ctx);
  9266. return true;
  9267. }
  9268. int llama_eval(
  9269. struct llama_context * ctx,
  9270. llama_token * tokens,
  9271. int32_t n_tokens,
  9272. int32_t n_past) {
  9273. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  9274. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  9275. if (ret < 0) {
  9276. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9277. }
  9278. return ret;
  9279. }
  9280. int llama_eval_embd(
  9281. struct llama_context * ctx,
  9282. float * embd,
  9283. int32_t n_tokens,
  9284. int32_t n_past) {
  9285. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  9286. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  9287. const int ret = llama_decode_internal(*ctx, batch);
  9288. if (ret < 0) {
  9289. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9290. }
  9291. return ret;
  9292. }
  9293. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  9294. ctx->cparams.n_threads = n_threads;
  9295. ctx->cparams.n_threads_batch = n_threads_batch;
  9296. }
  9297. struct llama_batch llama_batch_get_one(
  9298. llama_token * tokens,
  9299. int32_t n_tokens,
  9300. llama_pos pos_0,
  9301. llama_seq_id seq_id) {
  9302. return {
  9303. /*n_tokens =*/ n_tokens,
  9304. /*tokens =*/ tokens,
  9305. /*embd =*/ nullptr,
  9306. /*pos =*/ nullptr,
  9307. /*n_seq_id =*/ nullptr,
  9308. /*seq_id =*/ nullptr,
  9309. /*logits =*/ nullptr,
  9310. /*all_pos_0 =*/ pos_0,
  9311. /*all_pos_1 =*/ 1,
  9312. /*all_seq_id =*/ seq_id,
  9313. };
  9314. }
  9315. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  9316. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  9317. if (embd) {
  9318. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  9319. } else {
  9320. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  9321. }
  9322. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  9323. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  9324. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  9325. for (int i = 0; i < n_tokens; ++i) {
  9326. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  9327. }
  9328. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  9329. return batch;
  9330. }
  9331. void llama_batch_free(struct llama_batch batch) {
  9332. if (batch.token) free(batch.token);
  9333. if (batch.embd) free(batch.embd);
  9334. if (batch.pos) free(batch.pos);
  9335. if (batch.n_seq_id) free(batch.n_seq_id);
  9336. if (batch.seq_id) {
  9337. for (int i = 0; i < batch.n_tokens; ++i) {
  9338. free(batch.seq_id[i]);
  9339. }
  9340. free(batch.seq_id);
  9341. }
  9342. if (batch.logits) free(batch.logits);
  9343. }
  9344. int32_t llama_decode(
  9345. struct llama_context * ctx,
  9346. struct llama_batch batch) {
  9347. const int ret = llama_decode_internal(*ctx, batch);
  9348. if (ret < 0) {
  9349. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9350. }
  9351. return ret;
  9352. }
  9353. float * llama_get_logits(struct llama_context * ctx) {
  9354. return ctx->logits.data();
  9355. }
  9356. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  9357. assert(ctx->logits_valid.at(i));
  9358. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  9359. }
  9360. float * llama_get_embeddings(struct llama_context * ctx) {
  9361. return ctx->embedding.data();
  9362. }
  9363. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  9364. return model->vocab.id_to_token[token].text.c_str();
  9365. }
  9366. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  9367. return model->vocab.id_to_token[token].score;
  9368. }
  9369. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  9370. return model->vocab.id_to_token[token].type;
  9371. }
  9372. llama_token llama_token_bos(const struct llama_model * model) {
  9373. return model->vocab.special_bos_id;
  9374. }
  9375. llama_token llama_token_eos(const struct llama_model * model) {
  9376. return model->vocab.special_eos_id;
  9377. }
  9378. llama_token llama_token_nl(const struct llama_model * model) {
  9379. return model->vocab.linefeed_id;
  9380. }
  9381. int32_t llama_add_bos_token(const struct llama_model * model) {
  9382. return model->vocab.special_add_bos;
  9383. }
  9384. int32_t llama_add_eos_token(const struct llama_model * model) {
  9385. return model->vocab.special_add_eos;
  9386. }
  9387. llama_token llama_token_prefix(const struct llama_model * model) {
  9388. return model->vocab.special_prefix_id;
  9389. }
  9390. llama_token llama_token_middle(const struct llama_model * model) {
  9391. return model->vocab.special_middle_id;
  9392. }
  9393. llama_token llama_token_suffix(const struct llama_model * model) {
  9394. return model->vocab.special_suffix_id;
  9395. }
  9396. llama_token llama_token_eot(const struct llama_model * model) {
  9397. return model->vocab.special_eot_id;
  9398. }
  9399. int32_t llama_tokenize(
  9400. const struct llama_model * model,
  9401. const char * text,
  9402. int32_t text_len,
  9403. llama_token * tokens,
  9404. int32_t n_max_tokens,
  9405. bool add_bos,
  9406. bool special) {
  9407. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  9408. if (n_max_tokens < (int) res.size()) {
  9409. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  9410. return -((int) res.size());
  9411. }
  9412. for (size_t i = 0; i < res.size(); i++) {
  9413. tokens[i] = res[i];
  9414. }
  9415. return res.size();
  9416. }
  9417. static std::string llama_decode_text(const std::string & text) {
  9418. std::string decoded_text;
  9419. auto unicode_sequences = codepoints_from_utf8(text);
  9420. for (auto& unicode_sequence : unicode_sequences) {
  9421. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  9422. }
  9423. return decoded_text;
  9424. }
  9425. // does not write null-terminator to buf
  9426. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  9427. if (0 <= token && token < llama_n_vocab(model)) {
  9428. switch (llama_vocab_get_type(model->vocab)) {
  9429. case LLAMA_VOCAB_TYPE_SPM: {
  9430. // NOTE: we accept all unsupported token types,
  9431. // suppressing them like CONTROL tokens.
  9432. if (llama_is_normal_token(model->vocab, token)) {
  9433. std::string result = model->vocab.id_to_token[token].text;
  9434. llama_unescape_whitespace(result);
  9435. if (length < (int) result.length()) {
  9436. return -(int) result.length();
  9437. }
  9438. memcpy(buf, result.c_str(), result.length());
  9439. return result.length();
  9440. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9441. std::string result = model->vocab.id_to_token[token].text;
  9442. if (length < (int) result.length()) {
  9443. return -result.length();
  9444. }
  9445. memcpy(buf, result.c_str(), result.length());
  9446. return result.length();
  9447. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  9448. if (length < 3) {
  9449. return -3;
  9450. }
  9451. memcpy(buf, "\xe2\x96\x85", 3);
  9452. return 3;
  9453. } else if (llama_is_control_token(model->vocab, token)) {
  9454. ;
  9455. } else if (llama_is_byte_token(model->vocab, token)) {
  9456. if (length < 1) {
  9457. return -1;
  9458. }
  9459. buf[0] = llama_token_to_byte(model->vocab, token);
  9460. return 1;
  9461. }
  9462. break;
  9463. }
  9464. case LLAMA_VOCAB_TYPE_BPE: {
  9465. // NOTE: we accept all unsupported token types,
  9466. // suppressing them like CONTROL tokens.
  9467. if (llama_is_normal_token(model->vocab, token)) {
  9468. std::string result = model->vocab.id_to_token[token].text;
  9469. result = llama_decode_text(result);
  9470. if (length < (int) result.length()) {
  9471. return -(int) result.length();
  9472. }
  9473. memcpy(buf, result.c_str(), result.length());
  9474. return result.length();
  9475. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9476. std::string result = model->vocab.id_to_token[token].text;
  9477. if (length < (int) result.length()) {
  9478. return -result.length();
  9479. }
  9480. memcpy(buf, result.c_str(), result.length());
  9481. return result.length();
  9482. } else if (llama_is_control_token(model->vocab, token)) {
  9483. ;
  9484. }
  9485. break;
  9486. }
  9487. default:
  9488. GGML_ASSERT(false);
  9489. }
  9490. }
  9491. return 0;
  9492. }
  9493. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  9494. struct llama_timings result = {
  9495. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  9496. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  9497. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  9498. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  9499. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  9500. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  9501. /*.n_sample =*/ std::max(1, ctx->n_sample),
  9502. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  9503. /*.n_eval =*/ std::max(1, ctx->n_eval),
  9504. };
  9505. return result;
  9506. }
  9507. void llama_print_timings(struct llama_context * ctx) {
  9508. const llama_timings timings = llama_get_timings(ctx);
  9509. LLAMA_LOG_INFO("\n");
  9510. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  9511. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9512. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  9513. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  9514. __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);
  9515. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9516. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  9517. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (timings.t_end_ms - timings.t_start_ms), (timings.n_p_eval + timings.n_eval));
  9518. }
  9519. void llama_reset_timings(struct llama_context * ctx) {
  9520. ctx->t_start_us = ggml_time_us();
  9521. ctx->t_sample_us = ctx->n_sample = 0;
  9522. ctx->t_eval_us = ctx->n_eval = 0;
  9523. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  9524. }
  9525. const char * llama_print_system_info(void) {
  9526. static std::string s;
  9527. s = "";
  9528. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  9529. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  9530. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  9531. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  9532. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  9533. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  9534. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  9535. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  9536. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  9537. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  9538. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  9539. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  9540. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  9541. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  9542. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  9543. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  9544. return s.c_str();
  9545. }
  9546. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  9547. fprintf(stream, "\n");
  9548. fprintf(stream, "###########\n");
  9549. fprintf(stream, "# Timings #\n");
  9550. fprintf(stream, "###########\n");
  9551. fprintf(stream, "\n");
  9552. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  9553. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  9554. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  9555. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  9556. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  9557. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  9558. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  9559. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  9560. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  9561. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  9562. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  9563. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  9564. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  9565. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  9566. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  9567. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  9568. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  9569. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  9570. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  9571. }
  9572. // For internal test use
  9573. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  9574. struct llama_context * ctx
  9575. ) {
  9576. return ctx->model.tensors_by_name;
  9577. }
  9578. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  9579. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  9580. g_state.log_callback_user_data = user_data;
  9581. #ifdef GGML_USE_METAL
  9582. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  9583. #endif
  9584. }
  9585. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  9586. va_list args_copy;
  9587. va_copy(args_copy, args);
  9588. char buffer[128];
  9589. int len = vsnprintf(buffer, 128, format, args);
  9590. if (len < 128) {
  9591. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  9592. } else {
  9593. char* buffer2 = new char[len+1];
  9594. vsnprintf(buffer2, len+1, format, args_copy);
  9595. buffer2[len] = 0;
  9596. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  9597. delete[] buffer2;
  9598. }
  9599. va_end(args_copy);
  9600. }
  9601. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  9602. va_list args;
  9603. va_start(args, format);
  9604. llama_log_internal_v(level, format, args);
  9605. va_end(args);
  9606. }
  9607. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  9608. (void) level;
  9609. (void) user_data;
  9610. fputs(text, stderr);
  9611. fflush(stderr);
  9612. }