llama.cpp 531 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686
  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 <cwctype>
  65. #include <forward_list>
  66. #include <fstream>
  67. #include <functional>
  68. #include <initializer_list>
  69. #include <locale>
  70. #include <map>
  71. #include <memory>
  72. #include <mutex>
  73. #include <numeric>
  74. #include <queue>
  75. #include <random>
  76. #include <regex>
  77. #include <set>
  78. #include <sstream>
  79. #include <thread>
  80. #include <type_traits>
  81. #include <unordered_map>
  82. #if defined(_MSC_VER)
  83. #pragma warning(disable: 4244 4267) // possible loss of data
  84. #endif
  85. #ifdef __GNUC__
  86. #ifdef __MINGW32__
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  88. #else
  89. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  90. #endif
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...)
  93. #endif
  94. #define LLAMA_MAX_NODES 8192
  95. #define LLAMA_MAX_EXPERTS 8
  96. //
  97. // logging
  98. //
  99. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  100. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  101. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  102. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  103. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  104. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  105. //
  106. // helpers
  107. //
  108. static size_t utf8_len(char src) {
  109. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  110. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  111. return lookup[highbits];
  112. }
  113. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  114. std::string result;
  115. for (size_t pos = 0; ; pos += search.length()) {
  116. auto new_pos = s.find(search, pos);
  117. if (new_pos == std::string::npos) {
  118. result += s.substr(pos, s.size() - pos);
  119. break;
  120. }
  121. result += s.substr(pos, new_pos - pos) + replace;
  122. pos = new_pos;
  123. }
  124. s = std::move(result);
  125. }
  126. static bool is_float_close(float a, float b, float abs_tol) {
  127. // Check for non-negative tolerance
  128. if (abs_tol < 0.0) {
  129. throw std::invalid_argument("Tolerance must be non-negative");
  130. }
  131. // Exact equality check
  132. if (a == b) {
  133. return true;
  134. }
  135. // Check for infinities
  136. if (std::isinf(a) || std::isinf(b)) {
  137. return false;
  138. }
  139. // Regular comparison using the provided absolute tolerance
  140. return std::fabs(b - a) <= abs_tol;
  141. }
  142. static void zeros(std::ofstream & file, size_t n) {
  143. char zero = 0;
  144. for (size_t i = 0; i < n; ++i) {
  145. file.write(&zero, 1);
  146. }
  147. }
  148. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  149. static std::string format(const char * fmt, ...) {
  150. va_list ap;
  151. va_list ap2;
  152. va_start(ap, fmt);
  153. va_copy(ap2, ap);
  154. int size = vsnprintf(NULL, 0, fmt, ap);
  155. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  156. std::vector<char> buf(size + 1);
  157. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  158. GGML_ASSERT(size2 == size);
  159. va_end(ap2);
  160. va_end(ap);
  161. return std::string(buf.data(), size);
  162. }
  163. //
  164. // gguf constants (sync with gguf.py)
  165. //
  166. enum llm_arch {
  167. LLM_ARCH_LLAMA,
  168. LLM_ARCH_FALCON,
  169. LLM_ARCH_BAICHUAN,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_PERSIMMON,
  176. LLM_ARCH_REFACT,
  177. LLM_ARCH_BERT,
  178. LLM_ARCH_NOMIC_BERT,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_PHI2,
  184. LLM_ARCH_PLAMO,
  185. LLM_ARCH_CODESHELL,
  186. LLM_ARCH_ORION,
  187. LLM_ARCH_INTERNLM2,
  188. LLM_ARCH_MINICPM,
  189. LLM_ARCH_GEMMA,
  190. LLM_ARCH_STARCODER2,
  191. LLM_ARCH_UNKNOWN,
  192. };
  193. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  194. { LLM_ARCH_LLAMA, "llama" },
  195. { LLM_ARCH_FALCON, "falcon" },
  196. { LLM_ARCH_GPT2, "gpt2" },
  197. { LLM_ARCH_GPTJ, "gptj" },
  198. { LLM_ARCH_GPTNEOX, "gptneox" },
  199. { LLM_ARCH_MPT, "mpt" },
  200. { LLM_ARCH_BAICHUAN, "baichuan" },
  201. { LLM_ARCH_STARCODER, "starcoder" },
  202. { LLM_ARCH_PERSIMMON, "persimmon" },
  203. { LLM_ARCH_REFACT, "refact" },
  204. { LLM_ARCH_BERT, "bert" },
  205. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  206. { LLM_ARCH_BLOOM, "bloom" },
  207. { LLM_ARCH_STABLELM, "stablelm" },
  208. { LLM_ARCH_QWEN, "qwen" },
  209. { LLM_ARCH_QWEN2, "qwen2" },
  210. { LLM_ARCH_PHI2, "phi2" },
  211. { LLM_ARCH_PLAMO, "plamo" },
  212. { LLM_ARCH_CODESHELL, "codeshell" },
  213. { LLM_ARCH_ORION, "orion" },
  214. { LLM_ARCH_INTERNLM2, "internlm2" },
  215. { LLM_ARCH_MINICPM, "minicpm" },
  216. { LLM_ARCH_GEMMA, "gemma" },
  217. { LLM_ARCH_STARCODER2, "starcoder2" },
  218. { LLM_ARCH_UNKNOWN, "(unknown)" },
  219. };
  220. enum llm_kv {
  221. LLM_KV_GENERAL_ARCHITECTURE,
  222. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  223. LLM_KV_GENERAL_ALIGNMENT,
  224. LLM_KV_GENERAL_NAME,
  225. LLM_KV_GENERAL_AUTHOR,
  226. LLM_KV_GENERAL_URL,
  227. LLM_KV_GENERAL_DESCRIPTION,
  228. LLM_KV_GENERAL_LICENSE,
  229. LLM_KV_GENERAL_SOURCE_URL,
  230. LLM_KV_GENERAL_SOURCE_HF_REPO,
  231. LLM_KV_CONTEXT_LENGTH,
  232. LLM_KV_EMBEDDING_LENGTH,
  233. LLM_KV_BLOCK_COUNT,
  234. LLM_KV_FEED_FORWARD_LENGTH,
  235. LLM_KV_USE_PARALLEL_RESIDUAL,
  236. LLM_KV_TENSOR_DATA_LAYOUT,
  237. LLM_KV_EXPERT_COUNT,
  238. LLM_KV_EXPERT_USED_COUNT,
  239. LLM_KV_POOLING_TYPE,
  240. LLM_KV_ATTENTION_HEAD_COUNT,
  241. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  242. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  243. LLM_KV_ATTENTION_CLAMP_KQV,
  244. LLM_KV_ATTENTION_KEY_LENGTH,
  245. LLM_KV_ATTENTION_VALUE_LENGTH,
  246. LLM_KV_ATTENTION_LAYERNORM_EPS,
  247. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  248. LLM_KV_ATTENTION_CAUSAL,
  249. LLM_KV_ROPE_DIMENSION_COUNT,
  250. LLM_KV_ROPE_FREQ_BASE,
  251. LLM_KV_ROPE_SCALE_LINEAR,
  252. LLM_KV_ROPE_SCALING_TYPE,
  253. LLM_KV_ROPE_SCALING_FACTOR,
  254. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  255. LLM_KV_ROPE_SCALING_FINETUNED,
  256. LLM_KV_TOKENIZER_MODEL,
  257. LLM_KV_TOKENIZER_LIST,
  258. LLM_KV_TOKENIZER_TOKEN_TYPE,
  259. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  260. LLM_KV_TOKENIZER_SCORES,
  261. LLM_KV_TOKENIZER_MERGES,
  262. LLM_KV_TOKENIZER_BOS_ID,
  263. LLM_KV_TOKENIZER_EOS_ID,
  264. LLM_KV_TOKENIZER_UNK_ID,
  265. LLM_KV_TOKENIZER_SEP_ID,
  266. LLM_KV_TOKENIZER_PAD_ID,
  267. LLM_KV_TOKENIZER_ADD_BOS,
  268. LLM_KV_TOKENIZER_ADD_EOS,
  269. LLM_KV_TOKENIZER_ADD_PREFIX,
  270. LLM_KV_TOKENIZER_HF_JSON,
  271. LLM_KV_TOKENIZER_RWKV,
  272. };
  273. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  274. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  275. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  276. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  277. { LLM_KV_GENERAL_NAME, "general.name" },
  278. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  279. { LLM_KV_GENERAL_URL, "general.url" },
  280. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  281. { LLM_KV_GENERAL_LICENSE, "general.license" },
  282. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  283. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  284. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  285. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  286. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  287. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  288. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  289. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  290. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  291. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  292. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  293. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  294. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  295. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  296. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  297. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  298. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  299. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  300. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  301. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  302. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  303. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  304. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  305. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  306. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  307. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  308. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  309. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  310. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  311. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  312. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  313. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  314. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  315. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  316. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  317. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  318. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  319. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  320. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  321. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  322. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  323. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  324. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  325. };
  326. struct LLM_KV {
  327. LLM_KV(llm_arch arch) : arch(arch) {}
  328. llm_arch arch;
  329. std::string operator()(llm_kv kv) const {
  330. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  331. }
  332. };
  333. enum llm_tensor {
  334. LLM_TENSOR_TOKEN_EMBD,
  335. LLM_TENSOR_TOKEN_EMBD_NORM,
  336. LLM_TENSOR_TOKEN_TYPES,
  337. LLM_TENSOR_POS_EMBD,
  338. LLM_TENSOR_OUTPUT,
  339. LLM_TENSOR_OUTPUT_NORM,
  340. LLM_TENSOR_ROPE_FREQS,
  341. LLM_TENSOR_ATTN_Q,
  342. LLM_TENSOR_ATTN_K,
  343. LLM_TENSOR_ATTN_V,
  344. LLM_TENSOR_ATTN_QKV,
  345. LLM_TENSOR_ATTN_OUT,
  346. LLM_TENSOR_ATTN_NORM,
  347. LLM_TENSOR_ATTN_NORM_2,
  348. LLM_TENSOR_ATTN_OUT_NORM,
  349. LLM_TENSOR_ATTN_ROT_EMBD,
  350. LLM_TENSOR_FFN_GATE_INP,
  351. LLM_TENSOR_FFN_NORM,
  352. LLM_TENSOR_FFN_GATE,
  353. LLM_TENSOR_FFN_DOWN,
  354. LLM_TENSOR_FFN_UP,
  355. LLM_TENSOR_FFN_ACT,
  356. LLM_TENSOR_FFN_DOWN_EXP,
  357. LLM_TENSOR_FFN_GATE_EXP,
  358. LLM_TENSOR_FFN_UP_EXP,
  359. LLM_TENSOR_ATTN_Q_NORM,
  360. LLM_TENSOR_ATTN_K_NORM,
  361. LLM_TENSOR_LAYER_OUT_NORM,
  362. };
  363. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  364. {
  365. LLM_ARCH_LLAMA,
  366. {
  367. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  368. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  369. { LLM_TENSOR_OUTPUT, "output" },
  370. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  371. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  372. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  373. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  374. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  375. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  376. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  377. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  378. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  379. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  380. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  381. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  382. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  383. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  384. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  385. },
  386. },
  387. {
  388. LLM_ARCH_BAICHUAN,
  389. {
  390. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  391. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  392. { LLM_TENSOR_OUTPUT, "output" },
  393. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  394. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  395. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  396. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  397. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  398. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  399. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  400. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  401. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  402. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  403. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  404. },
  405. },
  406. {
  407. LLM_ARCH_FALCON,
  408. {
  409. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  410. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  411. { LLM_TENSOR_OUTPUT, "output" },
  412. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  413. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  414. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  415. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  416. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  417. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  418. },
  419. },
  420. {
  421. LLM_ARCH_GPT2,
  422. {
  423. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  424. { LLM_TENSOR_POS_EMBD, "position_embd" },
  425. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  426. { LLM_TENSOR_OUTPUT, "output" },
  427. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  428. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  429. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  430. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  431. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  432. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  433. },
  434. },
  435. {
  436. LLM_ARCH_GPTJ,
  437. {
  438. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  439. },
  440. },
  441. {
  442. LLM_ARCH_GPTNEOX,
  443. {
  444. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  445. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  446. { LLM_TENSOR_OUTPUT, "output" },
  447. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  448. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  449. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  450. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  451. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  452. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  453. },
  454. },
  455. {
  456. LLM_ARCH_PERSIMMON,
  457. {
  458. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  459. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  460. { LLM_TENSOR_OUTPUT, "output"},
  461. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  462. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  463. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  464. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  465. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  466. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  467. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  468. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  469. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  470. },
  471. },
  472. {
  473. LLM_ARCH_MPT,
  474. {
  475. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  476. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  477. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  478. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  479. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  480. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  481. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  482. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  483. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  484. },
  485. },
  486. {
  487. LLM_ARCH_STARCODER,
  488. {
  489. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  490. { LLM_TENSOR_POS_EMBD, "position_embd" },
  491. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  492. { LLM_TENSOR_OUTPUT, "output" },
  493. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  494. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  495. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  496. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  497. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  498. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  499. },
  500. },
  501. {
  502. LLM_ARCH_REFACT,
  503. {
  504. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  505. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  506. { LLM_TENSOR_OUTPUT, "output" },
  507. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  508. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  509. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  510. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  511. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  512. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  513. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  514. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  515. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  516. },
  517. },
  518. {
  519. LLM_ARCH_BERT,
  520. {
  521. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  522. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  523. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  524. { LLM_TENSOR_POS_EMBD, "position_embd" },
  525. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  526. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  527. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  528. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  529. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  530. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  531. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  532. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  533. },
  534. },
  535. {
  536. LLM_ARCH_NOMIC_BERT,
  537. {
  538. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  539. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  540. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  541. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  542. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  543. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  544. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  545. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  546. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  547. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  548. },
  549. },
  550. {
  551. LLM_ARCH_BLOOM,
  552. {
  553. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  554. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  555. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  556. { LLM_TENSOR_OUTPUT, "output" },
  557. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  558. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  559. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  560. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  561. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  562. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  563. },
  564. },
  565. {
  566. LLM_ARCH_STABLELM,
  567. {
  568. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  569. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  570. { LLM_TENSOR_OUTPUT, "output" },
  571. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  572. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  573. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  574. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  575. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  576. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  577. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  578. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  579. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  580. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  581. },
  582. },
  583. {
  584. LLM_ARCH_QWEN,
  585. {
  586. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  587. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  588. { LLM_TENSOR_OUTPUT, "output" },
  589. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  590. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  591. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  592. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  593. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  594. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  595. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  596. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  597. },
  598. },
  599. {
  600. LLM_ARCH_QWEN2,
  601. {
  602. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  603. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  604. { LLM_TENSOR_OUTPUT, "output" },
  605. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  606. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  607. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  608. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  609. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  610. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  611. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  612. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  613. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  614. },
  615. },
  616. {
  617. LLM_ARCH_PHI2,
  618. {
  619. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  620. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  621. { LLM_TENSOR_OUTPUT, "output" },
  622. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  623. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  624. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  625. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  626. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  627. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  628. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  629. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  630. },
  631. },
  632. {
  633. LLM_ARCH_PLAMO,
  634. {
  635. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  636. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  637. { LLM_TENSOR_OUTPUT, "output" },
  638. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  639. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  640. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  641. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  642. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  643. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  644. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  645. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  646. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  647. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  648. },
  649. },
  650. {
  651. LLM_ARCH_CODESHELL,
  652. {
  653. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  654. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  655. { LLM_TENSOR_OUTPUT, "output" },
  656. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  657. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  658. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  659. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  660. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  661. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  662. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  663. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  664. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  665. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  666. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  667. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  668. },
  669. },
  670. {
  671. LLM_ARCH_ORION,
  672. {
  673. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  674. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  675. { LLM_TENSOR_OUTPUT, "output" },
  676. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  677. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  678. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  679. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  680. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  681. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  682. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  683. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  684. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  685. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  686. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  687. },
  688. },
  689. {
  690. LLM_ARCH_INTERNLM2,
  691. {
  692. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  693. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  694. { LLM_TENSOR_OUTPUT, "output" },
  695. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  696. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  697. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  698. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  699. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  700. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  701. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  702. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  703. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  704. },
  705. },
  706. {
  707. LLM_ARCH_MINICPM,
  708. {
  709. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  710. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  711. { LLM_TENSOR_OUTPUT, "output" },
  712. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  713. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  714. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  715. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  716. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  717. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  718. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  719. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  720. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  721. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  722. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  723. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  724. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  725. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  726. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  727. },
  728. },
  729. {
  730. LLM_ARCH_GEMMA,
  731. {
  732. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  733. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  734. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  735. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  736. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  737. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  738. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  739. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  740. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  741. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  742. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  743. },
  744. },
  745. {
  746. LLM_ARCH_STARCODER2,
  747. {
  748. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  749. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  750. { LLM_TENSOR_OUTPUT, "output" },
  751. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  752. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  753. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  754. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  755. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  756. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  757. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  758. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  759. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  760. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  761. },
  762. },
  763. {
  764. LLM_ARCH_UNKNOWN,
  765. {
  766. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  767. },
  768. },
  769. };
  770. static llm_arch llm_arch_from_string(const std::string & name) {
  771. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  772. if (kv.second == name) {
  773. return kv.first;
  774. }
  775. }
  776. return LLM_ARCH_UNKNOWN;
  777. }
  778. // helper to handle gguf constants
  779. // usage:
  780. //
  781. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  782. //
  783. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  784. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  785. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  786. //
  787. struct LLM_TN {
  788. LLM_TN(llm_arch arch) : arch(arch) {}
  789. llm_arch arch;
  790. std::string operator()(llm_tensor tensor) const {
  791. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  792. return "__missing__";
  793. }
  794. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  795. }
  796. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  797. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  798. return "__missing__";
  799. }
  800. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  801. }
  802. std::string operator()(llm_tensor tensor, int bid) const {
  803. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  804. return "__missing__";
  805. }
  806. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  807. }
  808. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  809. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  810. return "__missing__";
  811. }
  812. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  813. }
  814. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  815. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  816. return "__missing__";
  817. }
  818. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  819. }
  820. };
  821. //
  822. // gguf helpers
  823. //
  824. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  825. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  826. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  827. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  828. };
  829. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  830. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  831. if (kv.second == name) {
  832. return (llama_rope_scaling_type) kv.first;
  833. }
  834. }
  835. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  836. }
  837. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  838. switch (type) {
  839. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  840. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  841. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  842. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  843. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  844. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  845. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  846. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  847. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  848. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  849. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  850. default: return format("unknown type %d", type);
  851. }
  852. }
  853. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  854. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  855. switch (type) {
  856. case GGUF_TYPE_STRING:
  857. return gguf_get_val_str(ctx_gguf, i);
  858. case GGUF_TYPE_ARRAY:
  859. {
  860. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  861. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  862. const void * data = gguf_get_arr_data(ctx_gguf, i);
  863. std::stringstream ss;
  864. ss << "[";
  865. for (int j = 0; j < arr_n; j++) {
  866. if (arr_type == GGUF_TYPE_STRING) {
  867. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  868. // escape quotes
  869. replace_all(val, "\\", "\\\\");
  870. replace_all(val, "\"", "\\\"");
  871. ss << '"' << val << '"';
  872. } else if (arr_type == GGUF_TYPE_ARRAY) {
  873. ss << "???";
  874. } else {
  875. ss << gguf_data_to_str(arr_type, data, j);
  876. }
  877. if (j < arr_n - 1) {
  878. ss << ", ";
  879. }
  880. }
  881. ss << "]";
  882. return ss.str();
  883. }
  884. default:
  885. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  886. }
  887. }
  888. //
  889. // ggml helpers
  890. //
  891. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  892. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  893. if (plan.work_size > 0) {
  894. buf.resize(plan.work_size);
  895. plan.work_data = buf.data();
  896. }
  897. ggml_graph_compute(graph, &plan);
  898. }
  899. //
  900. // llama helpers
  901. //
  902. #if defined(_WIN32)
  903. static std::string llama_format_win_err(DWORD err) {
  904. LPSTR buf;
  905. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  906. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  907. if (!size) {
  908. return "FormatMessageA failed";
  909. }
  910. std::string ret(buf, size);
  911. LocalFree(buf);
  912. return ret;
  913. }
  914. #endif
  915. template <typename T>
  916. struct no_init {
  917. T value;
  918. no_init() { /* do nothing */ }
  919. };
  920. struct llama_file {
  921. // use FILE * so we don't have to re-open the file to mmap
  922. FILE * fp;
  923. size_t size;
  924. llama_file(const char * fname, const char * mode) {
  925. fp = std::fopen(fname, mode);
  926. if (fp == NULL) {
  927. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  928. }
  929. seek(0, SEEK_END);
  930. size = tell();
  931. seek(0, SEEK_SET);
  932. }
  933. size_t tell() const {
  934. #ifdef _WIN32
  935. __int64 ret = _ftelli64(fp);
  936. #else
  937. long ret = std::ftell(fp);
  938. #endif
  939. GGML_ASSERT(ret != -1); // this really shouldn't fail
  940. return (size_t) ret;
  941. }
  942. void seek(size_t offset, int whence) const {
  943. #ifdef _WIN32
  944. int ret = _fseeki64(fp, (__int64) offset, whence);
  945. #else
  946. int ret = std::fseek(fp, (long) offset, whence);
  947. #endif
  948. GGML_ASSERT(ret == 0); // same
  949. }
  950. void read_raw(void * ptr, size_t len) const {
  951. if (len == 0) {
  952. return;
  953. }
  954. errno = 0;
  955. std::size_t ret = std::fread(ptr, len, 1, fp);
  956. if (ferror(fp)) {
  957. throw std::runtime_error(format("read error: %s", strerror(errno)));
  958. }
  959. if (ret != 1) {
  960. throw std::runtime_error("unexpectedly reached end of file");
  961. }
  962. }
  963. uint32_t read_u32() const {
  964. uint32_t ret;
  965. read_raw(&ret, sizeof(ret));
  966. return ret;
  967. }
  968. void write_raw(const void * ptr, size_t len) const {
  969. if (len == 0) {
  970. return;
  971. }
  972. errno = 0;
  973. size_t ret = std::fwrite(ptr, len, 1, fp);
  974. if (ret != 1) {
  975. throw std::runtime_error(format("write error: %s", strerror(errno)));
  976. }
  977. }
  978. void write_u32(std::uint32_t val) const {
  979. write_raw(&val, sizeof(val));
  980. }
  981. ~llama_file() {
  982. if (fp) {
  983. std::fclose(fp);
  984. }
  985. }
  986. };
  987. struct llama_mmap {
  988. void * addr;
  989. size_t size;
  990. llama_mmap(const llama_mmap &) = delete;
  991. #ifdef _POSIX_MAPPED_FILES
  992. static constexpr bool SUPPORTED = true;
  993. // list of mapped fragments (first_offset, last_offset)
  994. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  995. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  996. size = file->size;
  997. int fd = fileno(file->fp);
  998. int flags = MAP_SHARED;
  999. // prefetch/readahead impairs performance on NUMA systems
  1000. if (numa) { prefetch = 0; }
  1001. #ifdef __linux__
  1002. // advise the kernel to read the file sequentially (increases readahead)
  1003. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1004. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1005. strerror(errno));
  1006. }
  1007. if (prefetch) { flags |= MAP_POPULATE; }
  1008. #endif
  1009. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1010. if (addr == MAP_FAILED) { // NOLINT
  1011. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1012. }
  1013. if (prefetch > 0) {
  1014. // advise the kernel to preload the mapped memory
  1015. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1016. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1017. strerror(errno));
  1018. }
  1019. }
  1020. if (numa) {
  1021. // advise the kernel not to use readahead
  1022. // (because the next page might not belong on the same node)
  1023. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1024. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1025. strerror(errno));
  1026. }
  1027. }
  1028. // initialize list of mapped_fragments
  1029. mapped_fragments.emplace_back(0, file->size);
  1030. }
  1031. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1032. // align first to the next page
  1033. size_t offset_in_page = *first & (page_size - 1);
  1034. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1035. *first += offset_to_page;
  1036. // align last to the previous page
  1037. *last = *last & ~(page_size - 1);
  1038. if (*last <= *first) {
  1039. *last = *first;
  1040. }
  1041. }
  1042. // partially unmap the file in the range [first, last)
  1043. void unmap_fragment(size_t first, size_t last) {
  1044. // note: this function must not be called multiple times with overlapping ranges
  1045. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1046. int page_size = sysconf(_SC_PAGESIZE);
  1047. align_range(&first, &last, page_size);
  1048. size_t len = last - first;
  1049. if (len == 0) {
  1050. return;
  1051. }
  1052. GGML_ASSERT(first % page_size == 0);
  1053. GGML_ASSERT(last % page_size == 0);
  1054. GGML_ASSERT(last > first);
  1055. void * next_page_start = (uint8_t *) addr + first;
  1056. // unmap the range
  1057. if (munmap(next_page_start, len)) {
  1058. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1059. }
  1060. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1061. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1062. for (const auto & frag : mapped_fragments) {
  1063. if (frag.first < first && frag.second > last) {
  1064. // the range is in the middle of the fragment, split it
  1065. new_mapped_fragments.emplace_back(frag.first, first);
  1066. new_mapped_fragments.emplace_back(last, frag.second);
  1067. } else if (frag.first < first && frag.second > first) {
  1068. // the range starts in the middle of the fragment
  1069. new_mapped_fragments.emplace_back(frag.first, first);
  1070. } else if (frag.first < last && frag.second > last) {
  1071. // the range ends in the middle of the fragment
  1072. new_mapped_fragments.emplace_back(last, frag.second);
  1073. } else if (frag.first >= first && frag.second <= last) {
  1074. // the range covers the entire fragment
  1075. } else {
  1076. // the range is outside the fragment
  1077. new_mapped_fragments.push_back(frag);
  1078. }
  1079. }
  1080. mapped_fragments = std::move(new_mapped_fragments);
  1081. }
  1082. ~llama_mmap() {
  1083. for (const auto & frag : mapped_fragments) {
  1084. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1085. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1086. }
  1087. }
  1088. }
  1089. #elif defined(_WIN32)
  1090. static constexpr bool SUPPORTED = true;
  1091. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1092. GGML_UNUSED(numa);
  1093. size = file->size;
  1094. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1095. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1096. if (hMapping == NULL) {
  1097. DWORD error = GetLastError();
  1098. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1099. }
  1100. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1101. DWORD error = GetLastError();
  1102. CloseHandle(hMapping);
  1103. if (addr == NULL) {
  1104. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1105. }
  1106. if (prefetch > 0) {
  1107. #if _WIN32_WINNT >= 0x602
  1108. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1109. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1110. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1111. // may fail on pre-Windows 8 systems
  1112. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1113. if (pPrefetchVirtualMemory) {
  1114. // advise the kernel to preload the mapped memory
  1115. WIN32_MEMORY_RANGE_ENTRY range;
  1116. range.VirtualAddress = addr;
  1117. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1118. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1119. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1120. llama_format_win_err(GetLastError()).c_str());
  1121. }
  1122. }
  1123. #else
  1124. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1125. #endif
  1126. }
  1127. }
  1128. void unmap_fragment(size_t first, size_t last) {
  1129. // not supported
  1130. GGML_UNUSED(first);
  1131. GGML_UNUSED(last);
  1132. }
  1133. ~llama_mmap() {
  1134. if (!UnmapViewOfFile(addr)) {
  1135. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1136. llama_format_win_err(GetLastError()).c_str());
  1137. }
  1138. }
  1139. #else
  1140. static constexpr bool SUPPORTED = false;
  1141. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1142. GGML_UNUSED(file);
  1143. GGML_UNUSED(prefetch);
  1144. GGML_UNUSED(numa);
  1145. throw std::runtime_error("mmap not supported");
  1146. }
  1147. void unmap_fragment(size_t first, size_t last) {
  1148. GGML_UNUSED(first);
  1149. GGML_UNUSED(last);
  1150. throw std::runtime_error("mmap not supported");
  1151. }
  1152. #endif
  1153. };
  1154. // Represents some region of memory being locked using mlock or VirtualLock;
  1155. // will automatically unlock on destruction.
  1156. struct llama_mlock {
  1157. void * addr = NULL;
  1158. size_t size = 0;
  1159. bool failed_already = false;
  1160. llama_mlock() {}
  1161. llama_mlock(const llama_mlock &) = delete;
  1162. ~llama_mlock() {
  1163. if (size) {
  1164. raw_unlock(addr, size);
  1165. }
  1166. }
  1167. void init(void * ptr) {
  1168. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1169. addr = ptr;
  1170. }
  1171. void grow_to(size_t target_size) {
  1172. GGML_ASSERT(addr);
  1173. if (failed_already) {
  1174. return;
  1175. }
  1176. size_t granularity = lock_granularity();
  1177. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1178. if (target_size > size) {
  1179. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1180. size = target_size;
  1181. } else {
  1182. failed_already = true;
  1183. }
  1184. }
  1185. }
  1186. #ifdef _POSIX_MEMLOCK_RANGE
  1187. static constexpr bool SUPPORTED = true;
  1188. static size_t lock_granularity() {
  1189. return (size_t) sysconf(_SC_PAGESIZE);
  1190. }
  1191. #ifdef __APPLE__
  1192. #define MLOCK_SUGGESTION \
  1193. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1194. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1195. #else
  1196. #define MLOCK_SUGGESTION \
  1197. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1198. #endif
  1199. bool raw_lock(const void * addr, size_t size) const {
  1200. if (!mlock(addr, size)) {
  1201. return true;
  1202. }
  1203. char* errmsg = std::strerror(errno);
  1204. bool suggest = (errno == ENOMEM);
  1205. // Check if the resource limit is fine after all
  1206. struct rlimit lock_limit;
  1207. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1208. suggest = false;
  1209. }
  1210. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1211. suggest = false;
  1212. }
  1213. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1214. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1215. return false;
  1216. }
  1217. #undef MLOCK_SUGGESTION
  1218. static void raw_unlock(void * addr, size_t size) {
  1219. if (munlock(addr, size)) {
  1220. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1221. }
  1222. }
  1223. #elif defined(_WIN32)
  1224. static constexpr bool SUPPORTED = true;
  1225. static size_t lock_granularity() {
  1226. SYSTEM_INFO si;
  1227. GetSystemInfo(&si);
  1228. return (size_t) si.dwPageSize;
  1229. }
  1230. bool raw_lock(void * ptr, size_t len) const {
  1231. for (int tries = 1; ; tries++) {
  1232. if (VirtualLock(ptr, len)) {
  1233. return true;
  1234. }
  1235. if (tries == 2) {
  1236. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1237. len, size, llama_format_win_err(GetLastError()).c_str());
  1238. return false;
  1239. }
  1240. // It failed but this was only the first try; increase the working
  1241. // set size and try again.
  1242. SIZE_T min_ws_size, max_ws_size;
  1243. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1244. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1245. llama_format_win_err(GetLastError()).c_str());
  1246. return false;
  1247. }
  1248. // Per MSDN: "The maximum number of pages that a process can lock
  1249. // is equal to the number of pages in its minimum working set minus
  1250. // a small overhead."
  1251. // Hopefully a megabyte is enough overhead:
  1252. size_t increment = len + 1048576;
  1253. // The minimum must be <= the maximum, so we need to increase both:
  1254. min_ws_size += increment;
  1255. max_ws_size += increment;
  1256. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1257. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1258. llama_format_win_err(GetLastError()).c_str());
  1259. return false;
  1260. }
  1261. }
  1262. }
  1263. static void raw_unlock(void * ptr, size_t len) {
  1264. if (!VirtualUnlock(ptr, len)) {
  1265. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1266. llama_format_win_err(GetLastError()).c_str());
  1267. }
  1268. }
  1269. #else
  1270. static constexpr bool SUPPORTED = false;
  1271. static size_t lock_granularity() {
  1272. return (size_t) 65536;
  1273. }
  1274. bool raw_lock(const void * addr, size_t len) const {
  1275. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1276. return false;
  1277. }
  1278. static void raw_unlock(const void * addr, size_t len) {}
  1279. #endif
  1280. };
  1281. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1282. std::vector<char> result(8, 0);
  1283. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1284. if (n_tokens < 0) {
  1285. result.resize(-n_tokens);
  1286. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1287. GGML_ASSERT(check == -n_tokens);
  1288. }
  1289. else {
  1290. result.resize(n_tokens);
  1291. }
  1292. return std::string(result.data(), result.size());
  1293. }
  1294. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1295. ggml_backend_buffer_type_t buft = nullptr;
  1296. #if defined(GGML_USE_CUBLAS)
  1297. // host buffers should only be used when data is expected to be copied to/from the GPU
  1298. if (host_buffer) {
  1299. buft = ggml_backend_cuda_host_buffer_type();
  1300. }
  1301. #elif defined(GGML_USE_SYCL)
  1302. if (host_buffer) {
  1303. buft = ggml_backend_sycl_host_buffer_type();
  1304. }
  1305. #elif defined(GGML_USE_CPU_HBM)
  1306. buft = ggml_backend_cpu_hbm_buffer_type();
  1307. #elif defined(GGML_USE_VULKAN)
  1308. if (host_buffer) {
  1309. buft = ggml_backend_vk_host_buffer_type();
  1310. }
  1311. #endif
  1312. if (buft == nullptr) {
  1313. buft = ggml_backend_cpu_buffer_type();
  1314. }
  1315. return buft;
  1316. GGML_UNUSED(host_buffer);
  1317. }
  1318. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1319. ggml_backend_buffer_type_t buft = nullptr;
  1320. #ifdef GGML_USE_METAL
  1321. buft = ggml_backend_metal_buffer_type();
  1322. #elif defined(GGML_USE_CUBLAS)
  1323. buft = ggml_backend_cuda_buffer_type(gpu);
  1324. #elif defined(GGML_USE_VULKAN)
  1325. buft = ggml_backend_vk_buffer_type(gpu);
  1326. #elif defined(GGML_USE_SYCL)
  1327. buft = ggml_backend_sycl_buffer_type(gpu);
  1328. #elif defined(GGML_USE_CLBLAST)
  1329. buft = ggml_backend_opencl_buffer_type();
  1330. #elif defined(GGML_USE_KOMPUTE)
  1331. buft = ggml_backend_kompute_buffer_type(gpu);
  1332. if (buft == nullptr) {
  1333. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1334. }
  1335. #endif
  1336. if (buft == nullptr) {
  1337. buft = llama_default_buffer_type_cpu(true);
  1338. }
  1339. return buft;
  1340. GGML_UNUSED(gpu);
  1341. }
  1342. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1343. ggml_backend_buffer_type_t buft = nullptr;
  1344. #ifdef GGML_USE_CUBLAS
  1345. if (ggml_backend_cuda_get_device_count() > 1) {
  1346. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1347. }
  1348. #endif
  1349. #ifdef GGML_USE_SYCL
  1350. if (ggml_backend_sycl_get_device_count() > 1) {
  1351. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1352. }
  1353. #endif
  1354. if (buft == nullptr) {
  1355. buft = llama_default_buffer_type_offload(fallback_gpu);
  1356. }
  1357. return buft;
  1358. GGML_UNUSED(tensor_split);
  1359. }
  1360. static size_t llama_get_device_count() {
  1361. #if defined(GGML_USE_CUBLAS)
  1362. return ggml_backend_cuda_get_device_count();
  1363. #elif defined(GGML_USE_SYCL)
  1364. return ggml_backend_sycl_get_device_count();
  1365. #elif defined(GGML_USE_VULKAN)
  1366. return ggml_backend_vk_get_device_count();
  1367. #else
  1368. return 1;
  1369. #endif
  1370. }
  1371. static size_t llama_get_device_memory(int device) {
  1372. #if defined(GGML_USE_CUBLAS)
  1373. size_t total;
  1374. size_t free;
  1375. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1376. return free;
  1377. #elif defined(GGML_USE_SYCL)
  1378. size_t total;
  1379. size_t free;
  1380. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1381. return free;
  1382. #elif defined(GGML_USE_VULKAN)
  1383. size_t total;
  1384. size_t free;
  1385. ggml_backend_vk_get_device_memory(device, &total, &free);
  1386. return free;
  1387. #else
  1388. return 1;
  1389. GGML_UNUSED(device);
  1390. #endif
  1391. }
  1392. //
  1393. // globals
  1394. //
  1395. struct llama_state {
  1396. llama_state() {
  1397. #ifdef GGML_USE_METAL
  1398. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1399. #endif
  1400. }
  1401. // We save the log callback globally
  1402. ggml_log_callback log_callback = llama_log_callback_default;
  1403. void * log_callback_user_data = nullptr;
  1404. };
  1405. static llama_state g_state;
  1406. // available llama models
  1407. enum e_model {
  1408. MODEL_UNKNOWN,
  1409. MODEL_17M,
  1410. MODEL_22M,
  1411. MODEL_33M,
  1412. MODEL_109M,
  1413. MODEL_137M,
  1414. MODEL_335M,
  1415. MODEL_0_5B,
  1416. MODEL_1B,
  1417. MODEL_2B,
  1418. MODEL_3B,
  1419. MODEL_4B,
  1420. MODEL_7B,
  1421. MODEL_8B,
  1422. MODEL_13B,
  1423. MODEL_14B,
  1424. MODEL_15B,
  1425. MODEL_20B,
  1426. MODEL_30B,
  1427. MODEL_34B,
  1428. MODEL_40B,
  1429. MODEL_65B,
  1430. MODEL_70B,
  1431. MODEL_SMALL,
  1432. MODEL_MEDIUM,
  1433. MODEL_LARGE,
  1434. MODEL_XL,
  1435. };
  1436. static const size_t kiB = 1024;
  1437. static const size_t MiB = 1024*kiB;
  1438. static const size_t GiB = 1024*MiB;
  1439. struct llama_hparams {
  1440. bool vocab_only;
  1441. bool rope_finetuned;
  1442. uint32_t n_vocab;
  1443. uint32_t n_ctx_train; // context size the model was trained on
  1444. uint32_t n_embd;
  1445. uint32_t n_head;
  1446. uint32_t n_head_kv;
  1447. uint32_t n_layer;
  1448. uint32_t n_rot;
  1449. 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
  1450. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1451. uint32_t n_ff;
  1452. uint32_t n_expert = 0;
  1453. uint32_t n_expert_used = 0;
  1454. uint32_t n_vocab_type = 0; // for BERT-style token types
  1455. float f_norm_eps;
  1456. float f_norm_rms_eps;
  1457. float rope_freq_base_train;
  1458. float rope_freq_scale_train;
  1459. uint32_t n_yarn_orig_ctx;
  1460. float f_clamp_kqv = 0.0f;
  1461. float f_max_alibi_bias = 0.0f;
  1462. bool causal_attn = true;
  1463. bool need_kq_pos = false;
  1464. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1465. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1466. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1467. bool operator!=(const llama_hparams & other) const {
  1468. if (this->vocab_only != other.vocab_only) return true;
  1469. if (this->n_vocab != other.n_vocab) return true;
  1470. if (this->n_ctx_train != other.n_ctx_train) return true;
  1471. if (this->n_embd != other.n_embd) return true;
  1472. if (this->n_head != other.n_head) return true;
  1473. if (this->n_head_kv != other.n_head_kv) return true;
  1474. if (this->n_layer != other.n_layer) return true;
  1475. if (this->n_rot != other.n_rot) return true;
  1476. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1477. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1478. if (this->n_ff != other.n_ff) return true;
  1479. if (this->n_expert != other.n_expert) return true;
  1480. if (this->n_expert_used != other.n_expert_used) return true;
  1481. if (this->rope_finetuned != other.rope_finetuned) return true;
  1482. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1483. const float EPSILON = 1e-9f;
  1484. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1485. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1486. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1487. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1488. return false;
  1489. }
  1490. uint32_t n_gqa() const {
  1491. return n_head/n_head_kv;
  1492. }
  1493. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1494. return n_embd_head_k * n_head_kv;
  1495. }
  1496. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1497. return n_embd_head_v * n_head_kv;
  1498. }
  1499. };
  1500. struct llama_cparams {
  1501. uint32_t n_ctx; // context size used during inference
  1502. uint32_t n_batch;
  1503. uint32_t n_threads; // number of threads to use for generation
  1504. uint32_t n_threads_batch; // number of threads to use for batch processing
  1505. float rope_freq_base;
  1506. float rope_freq_scale;
  1507. uint32_t n_yarn_orig_ctx;
  1508. // These hyperparameters are not exposed in GGUF, because all
  1509. // existing YaRN models use the same values for them.
  1510. float yarn_ext_factor;
  1511. float yarn_attn_factor;
  1512. float yarn_beta_fast;
  1513. float yarn_beta_slow;
  1514. float defrag_thold;
  1515. bool embeddings;
  1516. bool offload_kqv;
  1517. enum llama_pooling_type pooling_type;
  1518. ggml_backend_sched_eval_callback cb_eval;
  1519. void * cb_eval_user_data;
  1520. };
  1521. struct llama_layer {
  1522. // normalization
  1523. struct ggml_tensor * attn_norm;
  1524. struct ggml_tensor * attn_norm_b;
  1525. struct ggml_tensor * attn_norm_2;
  1526. struct ggml_tensor * attn_norm_2_b;
  1527. struct ggml_tensor * attn_q_norm;
  1528. struct ggml_tensor * attn_q_norm_b;
  1529. struct ggml_tensor * attn_k_norm;
  1530. struct ggml_tensor * attn_k_norm_b;
  1531. struct ggml_tensor * attn_out_norm;
  1532. struct ggml_tensor * attn_out_norm_b;
  1533. // attention
  1534. struct ggml_tensor * wq;
  1535. struct ggml_tensor * wk;
  1536. struct ggml_tensor * wv;
  1537. struct ggml_tensor * wo;
  1538. struct ggml_tensor * wqkv;
  1539. // attention bias
  1540. struct ggml_tensor * bq;
  1541. struct ggml_tensor * bk;
  1542. struct ggml_tensor * bv;
  1543. struct ggml_tensor * bo;
  1544. struct ggml_tensor * bqkv;
  1545. // normalization
  1546. struct ggml_tensor * ffn_norm;
  1547. struct ggml_tensor * ffn_norm_b;
  1548. struct ggml_tensor * layer_out_norm;
  1549. struct ggml_tensor * layer_out_norm_b;
  1550. // ff
  1551. struct ggml_tensor * ffn_gate; // w1
  1552. struct ggml_tensor * ffn_down; // w2
  1553. struct ggml_tensor * ffn_up; // w3
  1554. // ff MoE
  1555. struct ggml_tensor * ffn_gate_inp;
  1556. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1557. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1558. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1559. // ff bias
  1560. struct ggml_tensor * ffn_down_b; // b2
  1561. struct ggml_tensor * ffn_up_b; // b3
  1562. struct ggml_tensor * ffn_act;
  1563. };
  1564. struct llama_kv_cell {
  1565. llama_pos pos = -1;
  1566. llama_pos delta = 0;
  1567. std::set<llama_seq_id> seq_id;
  1568. bool has_seq_id(const llama_seq_id & id) const {
  1569. return seq_id.find(id) != seq_id.end();
  1570. }
  1571. bool is_empty() const {
  1572. return seq_id.empty();
  1573. }
  1574. bool is_same_seq(const llama_kv_cell & other) const {
  1575. return seq_id == other.seq_id;
  1576. }
  1577. };
  1578. // ring-buffer of cached KV data
  1579. struct llama_kv_cache {
  1580. bool has_shift = false;
  1581. bool do_defrag = false;
  1582. // Note: The value of head isn't only used to optimize searching
  1583. // for a free KV slot. llama_decode_internal also uses it, so it
  1584. // cannot be freely changed after a slot has been allocated.
  1585. uint32_t head = 0;
  1586. uint32_t size = 0;
  1587. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1588. // computed before each graph build
  1589. uint32_t n = 0;
  1590. ggml_type type_k = GGML_TYPE_F16;
  1591. ggml_type type_v = GGML_TYPE_F16;
  1592. std::vector<llama_kv_cell> cells;
  1593. std::vector<struct ggml_tensor *> k_l; // per layer
  1594. std::vector<struct ggml_tensor *> v_l;
  1595. std::vector<struct ggml_context *> ctxs;
  1596. std::vector<ggml_backend_buffer_t> bufs;
  1597. size_t total_size() const {
  1598. size_t size = 0;
  1599. for (ggml_backend_buffer_t buf : bufs) {
  1600. size += ggml_backend_buffer_get_size(buf);
  1601. }
  1602. return size;
  1603. }
  1604. ~llama_kv_cache() {
  1605. for (struct ggml_context * ctx : ctxs) {
  1606. ggml_free(ctx);
  1607. }
  1608. for (ggml_backend_buffer_t buf : bufs) {
  1609. ggml_backend_buffer_free(buf);
  1610. }
  1611. }
  1612. };
  1613. struct llama_vocab {
  1614. using id = int32_t;
  1615. using token = std::string;
  1616. using ttype = llama_token_type;
  1617. struct token_data {
  1618. token text;
  1619. float score;
  1620. ttype type;
  1621. };
  1622. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1623. std::unordered_map<token, id> token_to_id;
  1624. std::vector<token_data> id_to_token;
  1625. std::unordered_map<token, id> special_tokens_cache;
  1626. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1627. // default LLaMA special tokens
  1628. id special_bos_id = 1;
  1629. id special_eos_id = 2;
  1630. id special_unk_id = 0;
  1631. id special_sep_id = -1;
  1632. id special_pad_id = -1;
  1633. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1634. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1635. id linefeed_id = 13;
  1636. id special_prefix_id = 32007;
  1637. id special_middle_id = 32009;
  1638. id special_suffix_id = 32008;
  1639. id special_eot_id = 32010;
  1640. bool add_space_prefix = true;
  1641. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1642. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1643. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1644. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1645. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1646. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1647. if (it == bpe_ranks.end()) {
  1648. return -1;
  1649. }
  1650. return it->second;
  1651. }
  1652. };
  1653. struct llama_model {
  1654. e_model type = MODEL_UNKNOWN;
  1655. llm_arch arch = LLM_ARCH_UNKNOWN;
  1656. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1657. std::string name = "n/a";
  1658. llama_hparams hparams = {};
  1659. llama_vocab vocab;
  1660. struct ggml_tensor * tok_embd;
  1661. struct ggml_tensor * type_embd;
  1662. struct ggml_tensor * pos_embd;
  1663. struct ggml_tensor * tok_norm;
  1664. struct ggml_tensor * tok_norm_b;
  1665. struct ggml_tensor * output_norm;
  1666. struct ggml_tensor * output_norm_b;
  1667. struct ggml_tensor * output;
  1668. struct ggml_tensor * output_b;
  1669. std::vector<llama_layer> layers;
  1670. llama_split_mode split_mode;
  1671. int main_gpu;
  1672. int n_gpu_layers;
  1673. // gguf metadata
  1674. std::unordered_map<std::string, std::string> gguf_kv;
  1675. // layer -> buffer type mapping
  1676. struct layer_buft {
  1677. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1678. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1679. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1680. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1681. ggml_backend_buffer_type_t buft; // everything else
  1682. };
  1683. layer_buft buft_input;
  1684. layer_buft buft_output;
  1685. std::vector<layer_buft> buft_layer;
  1686. // contexts where the model tensors metadata is stored
  1687. std::vector<struct ggml_context *> ctxs;
  1688. // the model memory buffers for the tensor data
  1689. std::vector<ggml_backend_buffer_t> bufs;
  1690. // model memory mapped file
  1691. std::unique_ptr<llama_mmap> mapping;
  1692. // objects representing data potentially being locked in memory
  1693. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1694. llama_mlock mlock_mmap;
  1695. // for quantize-stats only
  1696. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1697. int64_t t_load_us = 0;
  1698. int64_t t_start_us = 0;
  1699. ~llama_model() {
  1700. for (struct ggml_context * ctx : ctxs) {
  1701. ggml_free(ctx);
  1702. }
  1703. for (ggml_backend_buffer_t buf : bufs) {
  1704. ggml_backend_buffer_free(buf);
  1705. }
  1706. }
  1707. };
  1708. struct llama_context {
  1709. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1710. ~llama_context() {
  1711. ggml_backend_sched_free(sched);
  1712. for (ggml_backend_t backend : backends) {
  1713. ggml_backend_free(backend);
  1714. }
  1715. #ifdef GGML_USE_VULKAN
  1716. ggml_vk_free_cpu_assist();
  1717. #endif
  1718. ggml_backend_buffer_free(buf_input);
  1719. ggml_free(ctx_input);
  1720. }
  1721. llama_cparams cparams;
  1722. std::vector<ggml_backend_t> backends;
  1723. #ifdef GGML_USE_METAL
  1724. ggml_backend_t backend_metal = nullptr;
  1725. #endif
  1726. ggml_backend_t backend_cpu = nullptr;
  1727. const llama_model & model;
  1728. // key + value cache for the self attention
  1729. struct llama_kv_cache kv_self;
  1730. std::mt19937 rng;
  1731. bool has_evaluated_once = false;
  1732. int64_t t_start_us;
  1733. int64_t t_load_us;
  1734. int64_t t_sample_us = 0;
  1735. int64_t t_p_eval_us = 0;
  1736. int64_t t_eval_us = 0;
  1737. int32_t n_sample = 0; // number of tokens sampled
  1738. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1739. int32_t n_eval = 0; // number of eval calls
  1740. // logits output (2-dimensional array: [n_tokens][n_vocab])
  1741. std::vector<float> logits;
  1742. #ifndef NDEBUG
  1743. // guard against access to unset logits
  1744. std::vector<bool> logits_valid;
  1745. #endif
  1746. bool logits_all = false;
  1747. // embeddings output (2-dimensional array: [n_tokens][n_embd])
  1748. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1749. std::vector<float> embd;
  1750. // sequence embeddings output (map of [n_embd] vectors)
  1751. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1752. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1753. // memory buffers used to evaluate the model
  1754. std::vector<uint8_t> buf_compute_meta;
  1755. ggml_backend_sched_t sched = nullptr;
  1756. ggml_abort_callback abort_callback = nullptr;
  1757. void * abort_callback_data = nullptr;
  1758. // input tensors
  1759. ggml_backend_buffer_t buf_input = nullptr;
  1760. ggml_context * ctx_input = nullptr;
  1761. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1762. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1763. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1764. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1765. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1766. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1767. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1768. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1769. #ifdef GGML_USE_MPI
  1770. ggml_mpi_context * ctx_mpi = NULL;
  1771. #endif
  1772. };
  1773. //
  1774. // kv cache helpers
  1775. //
  1776. static bool llama_kv_cache_init(
  1777. struct llama_kv_cache & cache,
  1778. const llama_model & model,
  1779. ggml_type type_k,
  1780. ggml_type type_v,
  1781. uint32_t n_ctx,
  1782. bool offload) {
  1783. const struct llama_hparams & hparams = model.hparams;
  1784. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1785. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1786. const int64_t n_layer = hparams.n_layer;
  1787. cache.has_shift = false;
  1788. cache.head = 0;
  1789. cache.size = n_ctx;
  1790. cache.used = 0;
  1791. cache.type_k = type_k;
  1792. cache.type_v = type_v;
  1793. cache.cells.clear();
  1794. cache.cells.resize(n_ctx);
  1795. #ifdef GGML_USE_CLBLAST
  1796. offload = false;
  1797. #endif
  1798. // count used buffer types
  1799. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1800. if (offload) {
  1801. for (int64_t i = 0; i < n_layer; ++i) {
  1802. buft_layer_count[model.buft_layer[i].buft]++;
  1803. }
  1804. } else {
  1805. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1806. }
  1807. // create a context for each buffer type
  1808. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1809. for (auto & it : buft_layer_count) {
  1810. int n_layers = it.second;
  1811. struct ggml_init_params params = {
  1812. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1813. /*.mem_buffer =*/ NULL,
  1814. /*.no_alloc =*/ true,
  1815. };
  1816. ggml_context * ctx = ggml_init(params);
  1817. if (!ctx) {
  1818. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1819. return false;
  1820. }
  1821. ctx_map[it.first] = ctx;
  1822. cache.ctxs.push_back(ctx);
  1823. }
  1824. cache.k_l.reserve(n_layer);
  1825. cache.v_l.reserve(n_layer);
  1826. for (int i = 0; i < (int) n_layer; i++) {
  1827. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1828. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*n_ctx);
  1829. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*n_ctx);
  1830. ggml_format_name(k, "cache_k_l%d", i);
  1831. ggml_format_name(v, "cache_v_l%d", i);
  1832. cache.k_l.push_back(k);
  1833. cache.v_l.push_back(v);
  1834. }
  1835. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1836. for (auto it : ctx_map) {
  1837. ggml_backend_buffer_type_t buft = it.first;
  1838. ggml_context * ctx = it.second;
  1839. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1840. if (!buf) {
  1841. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1842. return false;
  1843. }
  1844. ggml_backend_buffer_clear(buf, 0);
  1845. 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);
  1846. cache.bufs.push_back(buf);
  1847. }
  1848. return true;
  1849. }
  1850. // find an empty slot of size "n_tokens" in the cache
  1851. // updates the cache head
  1852. // Note: On success, it's important that cache.head points
  1853. // to the first cell of the slot.
  1854. static bool llama_kv_cache_find_slot(
  1855. struct llama_kv_cache & cache,
  1856. const struct llama_batch & batch) {
  1857. const uint32_t n_ctx = cache.size;
  1858. const uint32_t n_tokens = batch.n_tokens;
  1859. if (n_tokens > n_ctx) {
  1860. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1861. return false;
  1862. }
  1863. uint32_t n_tested = 0;
  1864. while (true) {
  1865. if (cache.head + n_tokens > n_ctx) {
  1866. n_tested += n_ctx - cache.head;
  1867. cache.head = 0;
  1868. continue;
  1869. }
  1870. bool found = true;
  1871. for (uint32_t i = 0; i < n_tokens; i++) {
  1872. if (cache.cells[cache.head + i].pos >= 0) {
  1873. found = false;
  1874. cache.head += i + 1;
  1875. n_tested += i + 1;
  1876. break;
  1877. }
  1878. }
  1879. if (found) {
  1880. break;
  1881. }
  1882. if (n_tested >= n_ctx) {
  1883. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1884. return false;
  1885. }
  1886. }
  1887. for (uint32_t i = 0; i < n_tokens; i++) {
  1888. cache.cells[cache.head + i].pos = batch.pos[i];
  1889. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1890. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1891. }
  1892. }
  1893. cache.used += n_tokens;
  1894. return true;
  1895. }
  1896. // find how many cells are currently in use
  1897. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1898. for (uint32_t i = cache.size; i > 0; --i) {
  1899. const llama_kv_cell & cell = cache.cells[i - 1];
  1900. if (cell.pos >= 0 && !cell.is_empty()) {
  1901. return i;
  1902. }
  1903. }
  1904. return 0;
  1905. }
  1906. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1907. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1908. cache.cells[i].pos = -1;
  1909. cache.cells[i].seq_id.clear();
  1910. }
  1911. cache.head = 0;
  1912. cache.used = 0;
  1913. }
  1914. static void llama_kv_cache_seq_rm(
  1915. struct llama_kv_cache & cache,
  1916. llama_seq_id seq_id,
  1917. llama_pos p0,
  1918. llama_pos p1) {
  1919. uint32_t new_head = cache.size;
  1920. if (p0 < 0) p0 = 0;
  1921. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1922. for (uint32_t i = 0; i < cache.size; ++i) {
  1923. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1924. if (seq_id < 0) {
  1925. cache.cells[i].seq_id.clear();
  1926. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1927. cache.cells[i].seq_id.erase(seq_id);
  1928. } else {
  1929. continue;
  1930. }
  1931. if (cache.cells[i].is_empty()) {
  1932. // keep count of the number of used cells
  1933. if (cache.cells[i].pos >= 0) cache.used--;
  1934. cache.cells[i].pos = -1;
  1935. if (new_head == cache.size) new_head = i;
  1936. }
  1937. }
  1938. }
  1939. // If we freed up a slot, set head to it so searching can start there.
  1940. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1941. }
  1942. static void llama_kv_cache_seq_cp(
  1943. struct llama_kv_cache & cache,
  1944. llama_seq_id seq_id_src,
  1945. llama_seq_id seq_id_dst,
  1946. llama_pos p0,
  1947. llama_pos p1) {
  1948. if (p0 < 0) p0 = 0;
  1949. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1950. cache.head = 0;
  1951. for (uint32_t i = 0; i < cache.size; ++i) {
  1952. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1953. cache.cells[i].seq_id.insert(seq_id_dst);
  1954. }
  1955. }
  1956. }
  1957. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1958. uint32_t new_head = cache.size;
  1959. for (uint32_t i = 0; i < cache.size; ++i) {
  1960. if (!cache.cells[i].has_seq_id(seq_id)) {
  1961. if (cache.cells[i].pos >= 0) cache.used--;
  1962. cache.cells[i].pos = -1;
  1963. cache.cells[i].seq_id.clear();
  1964. if (new_head == cache.size) new_head = i;
  1965. } else {
  1966. cache.cells[i].seq_id.clear();
  1967. cache.cells[i].seq_id.insert(seq_id);
  1968. }
  1969. }
  1970. // If we freed up a slot, set head to it so searching can start there.
  1971. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1972. }
  1973. static void llama_kv_cache_seq_add(
  1974. struct llama_kv_cache & cache,
  1975. llama_seq_id seq_id,
  1976. llama_pos p0,
  1977. llama_pos p1,
  1978. llama_pos delta) {
  1979. uint32_t new_head = cache.size;
  1980. if (p0 < 0) p0 = 0;
  1981. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1982. for (uint32_t i = 0; i < cache.size; ++i) {
  1983. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1984. cache.has_shift = true;
  1985. cache.cells[i].pos += delta;
  1986. cache.cells[i].delta += delta;
  1987. if (cache.cells[i].pos < 0) {
  1988. if (!cache.cells[i].is_empty()) {
  1989. cache.used--;
  1990. }
  1991. cache.cells[i].pos = -1;
  1992. cache.cells[i].seq_id.clear();
  1993. if (new_head == cache.size) {
  1994. new_head = i;
  1995. }
  1996. }
  1997. }
  1998. }
  1999. // If we freed up a slot, set head to it so searching can start there.
  2000. // Otherwise we just start the next search from the beginning.
  2001. cache.head = new_head != cache.size ? new_head : 0;
  2002. }
  2003. static void llama_kv_cache_seq_div(
  2004. struct llama_kv_cache & cache,
  2005. llama_seq_id seq_id,
  2006. llama_pos p0,
  2007. llama_pos p1,
  2008. int d) {
  2009. if (p0 < 0) p0 = 0;
  2010. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2011. for (uint32_t i = 0; i < cache.size; ++i) {
  2012. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2013. cache.has_shift = true;
  2014. {
  2015. llama_pos p_old = cache.cells[i].pos;
  2016. cache.cells[i].pos /= d;
  2017. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2018. }
  2019. }
  2020. }
  2021. }
  2022. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2023. llama_pos result = 0;
  2024. for (uint32_t i = 0; i < cache.size; ++i) {
  2025. if (cache.cells[i].has_seq_id(seq_id)) {
  2026. result = std::max(result, cache.cells[i].pos);
  2027. }
  2028. }
  2029. return result;
  2030. }
  2031. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2032. cache.do_defrag = true;
  2033. }
  2034. //
  2035. // model loading and saving
  2036. //
  2037. enum llama_fver {
  2038. GGUF_FILE_VERSION_V1 = 1,
  2039. GGUF_FILE_VERSION_V2 = 2,
  2040. GGUF_FILE_VERSION_V3 = 3,
  2041. };
  2042. static const char * llama_file_version_name(llama_fver version) {
  2043. switch (version) {
  2044. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2045. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2046. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2047. }
  2048. return "unknown";
  2049. }
  2050. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2051. char buf[256];
  2052. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2053. for (size_t i = 1; i < ne.size(); i++) {
  2054. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2055. }
  2056. return buf;
  2057. }
  2058. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2059. char buf[256];
  2060. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2061. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2062. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2063. }
  2064. return buf;
  2065. }
  2066. namespace GGUFMeta {
  2067. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2068. struct GKV_Base_Type {
  2069. static constexpr gguf_type gt = gt_;
  2070. static T getter(const gguf_context * ctx, const int kid) {
  2071. return gfun(ctx, kid);
  2072. }
  2073. };
  2074. template<typename T> struct GKV_Base;
  2075. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2076. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2077. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2078. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2079. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2080. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2081. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2082. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2083. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2084. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2085. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2086. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2087. template<> struct GKV_Base<std::string> {
  2088. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2089. static std::string getter(const gguf_context * ctx, const int kid) {
  2090. return gguf_get_val_str(ctx, kid);
  2091. }
  2092. };
  2093. struct ArrayInfo {
  2094. const gguf_type gt;
  2095. const size_t length;
  2096. const void * data;
  2097. };
  2098. template<> struct GKV_Base<ArrayInfo> {
  2099. public:
  2100. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2101. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2102. return ArrayInfo {
  2103. gguf_get_arr_type(ctx, k),
  2104. size_t(gguf_get_arr_n(ctx, k)),
  2105. gguf_get_arr_data(ctx, k),
  2106. };
  2107. }
  2108. };
  2109. template<typename T>
  2110. class GKV : public GKV_Base<T> {
  2111. GKV() = delete;
  2112. public:
  2113. static T get_kv(const gguf_context * ctx, const int k) {
  2114. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2115. if (kt != GKV::gt) {
  2116. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2117. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2118. }
  2119. return GKV::getter(ctx, k);
  2120. }
  2121. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2122. switch (ty) {
  2123. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2124. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2125. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2126. }
  2127. return "unknown";
  2128. }
  2129. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2130. if (!ovrd) { return false; }
  2131. if (ovrd->tag == expected_type) {
  2132. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2133. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2134. switch (ovrd->tag) {
  2135. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2136. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2137. } break;
  2138. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2139. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2140. } break;
  2141. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2142. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2143. } break;
  2144. default:
  2145. // Shouldn't be possible to end up here, but just in case...
  2146. throw std::runtime_error(
  2147. format("Unsupported attempt to override %s type for metadata key %s\n",
  2148. override_type_to_str(ovrd->tag), ovrd->key));
  2149. }
  2150. return true;
  2151. }
  2152. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2153. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2154. return false;
  2155. }
  2156. template<typename OT>
  2157. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2158. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2159. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2160. target = ovrd->bool_value;
  2161. return true;
  2162. }
  2163. return false;
  2164. }
  2165. template<typename OT>
  2166. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2167. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2168. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2169. target = ovrd->int_value;
  2170. return true;
  2171. }
  2172. return false;
  2173. }
  2174. template<typename OT>
  2175. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2176. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2177. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2178. target = ovrd->float_value;
  2179. return true;
  2180. }
  2181. return false;
  2182. }
  2183. template<typename OT>
  2184. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2185. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2186. (void)target;
  2187. (void)ovrd;
  2188. if (!ovrd) { return false; }
  2189. // Currently, we should never end up here so it would be a bug if we do.
  2190. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2191. ovrd ? ovrd->key : "NULL"));
  2192. }
  2193. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2194. if (try_override<T>(target, ovrd)) {
  2195. return true;
  2196. }
  2197. if (k < 0) { return false; }
  2198. target = get_kv(ctx, k);
  2199. return true;
  2200. }
  2201. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2202. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2203. }
  2204. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2205. return set(ctx, key.c_str(), target, ovrd);
  2206. }
  2207. };
  2208. }
  2209. struct llama_model_loader {
  2210. int n_kv = 0;
  2211. int n_tensors = 0;
  2212. int n_created = 0;
  2213. int64_t n_elements = 0;
  2214. size_t n_bytes = 0;
  2215. bool use_mmap = false;
  2216. llama_file file;
  2217. llama_ftype ftype;
  2218. llama_fver fver;
  2219. std::unique_ptr<llama_mmap> mapping;
  2220. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2221. struct gguf_context * ctx_gguf = NULL;
  2222. struct ggml_context * ctx_meta = NULL;
  2223. std::string arch_name;
  2224. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2225. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2226. int trace = 0;
  2227. if (getenv("LLAMA_TRACE")) {
  2228. trace = atoi(getenv("LLAMA_TRACE"));
  2229. }
  2230. struct gguf_init_params params = {
  2231. /*.no_alloc = */ true,
  2232. /*.ctx = */ &ctx_meta,
  2233. };
  2234. if (param_overrides_p != nullptr) {
  2235. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2236. kv_overrides.insert({std::string(p->key), *p});
  2237. }
  2238. }
  2239. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2240. if (!ctx_gguf) {
  2241. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2242. }
  2243. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2244. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2245. n_kv = gguf_get_n_kv(ctx_gguf);
  2246. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2247. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2248. for (int i = 0; i < n_tensors; i++) {
  2249. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2250. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2251. n_elements += ggml_nelements(t);
  2252. n_bytes += ggml_nbytes(t);
  2253. }
  2254. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2255. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2256. // determine file type based on the number of tensors for each quantization and print meta data
  2257. // TODO: make optional
  2258. {
  2259. std::map<enum ggml_type, uint32_t> n_type;
  2260. uint32_t n_type_max = 0;
  2261. enum ggml_type type_max = GGML_TYPE_F32;
  2262. for (int i = 0; i < n_tensors; i++) {
  2263. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2264. n_type[type]++;
  2265. if (n_type_max < n_type[type]) {
  2266. n_type_max = n_type[type];
  2267. type_max = type;
  2268. }
  2269. if (trace > 0) {
  2270. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2271. 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());
  2272. }
  2273. }
  2274. switch (type_max) {
  2275. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2276. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2277. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2278. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2279. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2280. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2281. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2282. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2283. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2284. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2285. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2286. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2287. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2288. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2289. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2290. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2291. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2292. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2293. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2294. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2295. default:
  2296. {
  2297. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2298. ftype = LLAMA_FTYPE_ALL_F32;
  2299. } break;
  2300. }
  2301. // this is a way to mark that we have "guessed" the file type
  2302. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2303. {
  2304. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2305. if (kid >= 0) {
  2306. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2307. }
  2308. }
  2309. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2310. for (int i = 0; i < n_kv; i++) {
  2311. const char * name = gguf_get_key(ctx_gguf, i);
  2312. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2313. const std::string type_name =
  2314. type == GGUF_TYPE_ARRAY
  2315. ? 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))
  2316. : gguf_type_name(type);
  2317. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2318. const size_t MAX_VALUE_LEN = 40;
  2319. if (value.size() > MAX_VALUE_LEN) {
  2320. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2321. }
  2322. replace_all(value, "\n", "\\n");
  2323. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2324. }
  2325. // print type counts
  2326. for (auto & kv : n_type) {
  2327. if (kv.second == 0) {
  2328. continue;
  2329. }
  2330. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2331. }
  2332. }
  2333. if (!llama_mmap::SUPPORTED) {
  2334. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2335. use_mmap = false;
  2336. }
  2337. this->use_mmap = use_mmap;
  2338. }
  2339. ~llama_model_loader() {
  2340. if (ctx_gguf) {
  2341. gguf_free(ctx_gguf);
  2342. }
  2343. if (ctx_meta) {
  2344. ggml_free(ctx_meta);
  2345. }
  2346. }
  2347. template<typename T>
  2348. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2349. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2350. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2351. if (kid < 0) {
  2352. if (required) {
  2353. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2354. }
  2355. return false;
  2356. }
  2357. struct GGUFMeta::ArrayInfo arr_info =
  2358. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2359. result = arr_info.length;
  2360. return true;
  2361. }
  2362. template<typename T>
  2363. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2364. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2365. return get_arr_n(llm_kv(kid), result, required);
  2366. }
  2367. template<typename T>
  2368. bool get_key(const std::string & key, T & result, const bool required = true) {
  2369. auto it = kv_overrides.find(key);
  2370. const struct llama_model_kv_override * override =
  2371. it != kv_overrides.end() ? &it->second : nullptr;
  2372. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2373. if (required && !found) {
  2374. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2375. }
  2376. return found;
  2377. }
  2378. template<typename T>
  2379. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2380. return get_key(llm_kv(kid), result, required);
  2381. }
  2382. std::string get_arch_name() const {
  2383. return arch_name;
  2384. }
  2385. enum llm_arch get_arch() const {
  2386. return llm_kv.arch;
  2387. }
  2388. const char * get_tensor_name(int i) const {
  2389. return gguf_get_tensor_name(ctx_gguf, i);
  2390. }
  2391. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2392. return ggml_get_tensor(ctx_meta, name);
  2393. }
  2394. struct ggml_tensor * get_tensor_meta(int i) const {
  2395. return get_tensor_meta(get_tensor_name(i));
  2396. }
  2397. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2398. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2399. ggml_set_name(tensor, ggml_get_name(meta));
  2400. n_created++;
  2401. return tensor;
  2402. }
  2403. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2404. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2405. if (cur == NULL) {
  2406. if (!required) {
  2407. return NULL;
  2408. }
  2409. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2410. }
  2411. {
  2412. bool is_ok = true;
  2413. for (size_t i = 0; i < ne.size(); ++i) {
  2414. if (ne[i] != cur->ne[i]) {
  2415. is_ok = false;
  2416. break;
  2417. }
  2418. }
  2419. if (!is_ok) {
  2420. throw std::runtime_error(
  2421. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2422. __func__, name.c_str(),
  2423. llama_format_tensor_shape(ne).c_str(),
  2424. llama_format_tensor_shape(cur).c_str()));
  2425. }
  2426. }
  2427. return create_tensor_for(ctx, cur);
  2428. }
  2429. void done_getting_tensors() const {
  2430. if (n_created != n_tensors) {
  2431. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2432. }
  2433. }
  2434. size_t file_offset(const char * name) const {
  2435. const int idx = gguf_find_tensor(ctx_gguf, name);
  2436. if (idx < 0) {
  2437. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2438. }
  2439. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2440. }
  2441. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2442. // prefetch the whole file - all the data is needed anyway
  2443. if (use_mmap) {
  2444. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2445. }
  2446. // compute the total size of all tensors for progress reporting
  2447. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2448. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2449. size_data += ggml_nbytes(cur);
  2450. }
  2451. if (use_mmap && mapping) {
  2452. if (lmlock) {
  2453. lmlock->init(mapping->addr);
  2454. }
  2455. mmap_used_first = mapping->size;
  2456. }
  2457. }
  2458. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2459. GGML_ASSERT(mapping);
  2460. *first = mapping->size;
  2461. *last = 0;
  2462. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2463. const size_t offs = file_offset(ggml_get_name(tensor));
  2464. *first = std::min(*first, offs);
  2465. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2466. }
  2467. }
  2468. // for backwards compatibility, does not support ggml-backend
  2469. void load_data_for(struct ggml_tensor * cur) const {
  2470. const size_t offs = file_offset(ggml_get_name(cur));
  2471. if (use_mmap && mapping) {
  2472. if (cur->data == nullptr) {
  2473. cur->data = (uint8_t *)mapping->addr + offs;
  2474. } else {
  2475. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2476. }
  2477. } else {
  2478. GGML_ASSERT(cur->data != nullptr);
  2479. file.seek(offs, SEEK_SET);
  2480. file.read_raw(cur->data, ggml_nbytes(cur));
  2481. }
  2482. }
  2483. size_t size_done = 0;
  2484. size_t size_data = 0;
  2485. size_t mmap_used_first = -1;
  2486. size_t mmap_used_last = 0;
  2487. // Returns false if cancelled by progress_callback
  2488. 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) {
  2489. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2490. std::vector<no_init<uint8_t>> read_buf;
  2491. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2492. if (progress_callback) {
  2493. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2494. return false;
  2495. }
  2496. }
  2497. const size_t offs = file_offset(ggml_get_name(cur));
  2498. if (use_mmap && mapping) {
  2499. if (buf_mmap && cur->data == nullptr) {
  2500. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2501. if (lmlock) {
  2502. lmlock->grow_to(offs + ggml_nbytes(cur));
  2503. }
  2504. mmap_used_first = std::min(mmap_used_first, offs);
  2505. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2506. } else {
  2507. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2508. }
  2509. } else {
  2510. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2511. file.seek(offs, SEEK_SET);
  2512. file.read_raw(cur->data, ggml_nbytes(cur));
  2513. } else {
  2514. read_buf.resize(ggml_nbytes(cur));
  2515. file.seek(offs, SEEK_SET);
  2516. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2517. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2518. }
  2519. }
  2520. size_done += ggml_nbytes(cur);
  2521. }
  2522. // check if this is the last call and do final cleanup
  2523. if (size_done >= size_data) {
  2524. // unmap offloaded tensors and metadata
  2525. if (use_mmap && mapping) {
  2526. mapping->unmap_fragment(0, mmap_used_first);
  2527. if (mmap_used_last != 0) {
  2528. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2529. }
  2530. }
  2531. if (progress_callback) {
  2532. // Even though the model is done loading, we still honor
  2533. // cancellation since we need to free allocations.
  2534. return progress_callback(1.0f, progress_callback_user_data);
  2535. }
  2536. }
  2537. return true;
  2538. }
  2539. };
  2540. template<>
  2541. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2542. uint32_t tmp;
  2543. const bool found = get_key(kid, tmp, required);
  2544. if (found) {
  2545. result = (enum llama_pooling_type) tmp;
  2546. } else {
  2547. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2548. }
  2549. return found;
  2550. }
  2551. //
  2552. // load LLaMA models
  2553. //
  2554. static const char * llama_model_arch_name(llm_arch arch) {
  2555. auto it = LLM_ARCH_NAMES.find(arch);
  2556. if (it == LLM_ARCH_NAMES.end()) {
  2557. return "unknown";
  2558. }
  2559. return it->second;
  2560. }
  2561. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2562. if (ftype & LLAMA_FTYPE_GUESSED) {
  2563. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2564. }
  2565. switch (ftype) {
  2566. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2567. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2568. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2569. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2570. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2571. return "Q4_1, some F16";
  2572. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2573. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2574. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2575. // K-quants
  2576. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2577. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2578. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2579. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2580. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2581. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2582. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2583. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2584. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2585. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2586. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2587. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2588. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2589. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2590. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2591. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2592. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2593. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2594. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2595. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2596. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2597. default: return "unknown, may not work";
  2598. }
  2599. }
  2600. static const char * llama_model_type_name(e_model type) {
  2601. switch (type) {
  2602. case MODEL_22M: return "22M";
  2603. case MODEL_33M: return "33M";
  2604. case MODEL_109M: return "109M";
  2605. case MODEL_137M: return "137M";
  2606. case MODEL_0_5B: return "0.5B";
  2607. case MODEL_1B: return "1B";
  2608. case MODEL_2B: return "2B";
  2609. case MODEL_3B: return "3B";
  2610. case MODEL_7B: return "7B";
  2611. case MODEL_8B: return "8B";
  2612. case MODEL_13B: return "13B";
  2613. case MODEL_14B: return "14B";
  2614. case MODEL_15B: return "15B";
  2615. case MODEL_20B: return "20B";
  2616. case MODEL_30B: return "30B";
  2617. case MODEL_34B: return "34B";
  2618. case MODEL_40B: return "40B";
  2619. case MODEL_65B: return "65B";
  2620. case MODEL_70B: return "70B";
  2621. case MODEL_SMALL: return "0.1B";
  2622. case MODEL_MEDIUM: return "0.4B";
  2623. case MODEL_LARGE: return "0.8B";
  2624. case MODEL_XL: return "1.5B";
  2625. default: return "?B";
  2626. }
  2627. }
  2628. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2629. switch (type) {
  2630. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2631. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2632. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2633. default: return "unknown";
  2634. }
  2635. }
  2636. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2637. model.arch = ml.get_arch();
  2638. if (model.arch == LLM_ARCH_UNKNOWN) {
  2639. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2640. }
  2641. }
  2642. static void llm_load_hparams(
  2643. llama_model_loader & ml,
  2644. llama_model & model) {
  2645. auto & hparams = model.hparams;
  2646. const gguf_context * ctx = ml.ctx_gguf;
  2647. // get metadata as string
  2648. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2649. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2650. if (type == GGUF_TYPE_ARRAY) {
  2651. continue;
  2652. }
  2653. const char * name = gguf_get_key(ctx, i);
  2654. const std::string value = gguf_kv_to_str(ctx, i);
  2655. model.gguf_kv.emplace(name, value);
  2656. }
  2657. // get general kv
  2658. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2659. // get hparams kv
  2660. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2661. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2662. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2663. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2664. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2665. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2666. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2667. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2668. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2669. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2670. if (hparams.n_expert > 0) {
  2671. GGML_ASSERT(hparams.n_expert_used > 0);
  2672. } else {
  2673. GGML_ASSERT(hparams.n_expert_used == 0);
  2674. }
  2675. // n_head_kv is optional, default to n_head
  2676. hparams.n_head_kv = hparams.n_head;
  2677. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2678. bool rope_finetuned = false;
  2679. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2680. hparams.rope_finetuned = rope_finetuned;
  2681. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2682. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2683. // rope_freq_base (optional)
  2684. hparams.rope_freq_base_train = 10000.0f;
  2685. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2686. std::string rope_scaling("linear");
  2687. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2688. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2689. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2690. // rope_freq_scale (inverse of the kv) is optional
  2691. float ropescale = 0.0f;
  2692. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2693. // try the old key name
  2694. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2695. }
  2696. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2697. // sanity check for n_rot (optional)
  2698. {
  2699. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2700. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2701. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2702. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2703. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2704. }
  2705. }
  2706. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2707. // gpt-j n_rot = rotary_dim
  2708. }
  2709. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2710. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2711. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2712. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2713. // arch-specific KVs
  2714. switch (model.arch) {
  2715. case LLM_ARCH_LLAMA:
  2716. {
  2717. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2718. switch (hparams.n_layer) {
  2719. case 22: model.type = e_model::MODEL_1B; break;
  2720. case 26: model.type = e_model::MODEL_3B; break;
  2721. case 32: model.type = e_model::MODEL_7B; break;
  2722. case 40: model.type = e_model::MODEL_13B; break;
  2723. case 48: model.type = e_model::MODEL_34B; break;
  2724. case 60: model.type = e_model::MODEL_30B; break;
  2725. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2726. default: model.type = e_model::MODEL_UNKNOWN;
  2727. }
  2728. } break;
  2729. case LLM_ARCH_MINICPM:
  2730. {
  2731. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2732. switch (hparams.n_layer) {
  2733. case 40: model.type = e_model::MODEL_2B; break;
  2734. default: model.type = e_model::MODEL_UNKNOWN;
  2735. }
  2736. } break;
  2737. case LLM_ARCH_FALCON:
  2738. {
  2739. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2740. switch (hparams.n_layer) {
  2741. case 32: model.type = e_model::MODEL_7B; break;
  2742. case 60: model.type = e_model::MODEL_40B; break;
  2743. default: model.type = e_model::MODEL_UNKNOWN;
  2744. }
  2745. } break;
  2746. case LLM_ARCH_BAICHUAN:
  2747. {
  2748. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2749. switch (hparams.n_layer) {
  2750. case 32: model.type = e_model::MODEL_7B; break;
  2751. case 40: model.type = e_model::MODEL_13B; break;
  2752. default: model.type = e_model::MODEL_UNKNOWN;
  2753. }
  2754. if (model.type == e_model::MODEL_13B) {
  2755. // TODO: become GGUF KV parameter
  2756. hparams.f_max_alibi_bias = 8.0f;
  2757. }
  2758. } break;
  2759. case LLM_ARCH_STARCODER:
  2760. {
  2761. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2762. switch (hparams.n_layer) {
  2763. case 24: model.type = e_model::MODEL_1B; break;
  2764. case 36: model.type = e_model::MODEL_3B; break;
  2765. case 42: model.type = e_model::MODEL_7B; break;
  2766. case 40: model.type = e_model::MODEL_15B; break;
  2767. default: model.type = e_model::MODEL_UNKNOWN;
  2768. }
  2769. } break;
  2770. case LLM_ARCH_PERSIMMON:
  2771. {
  2772. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2773. switch (hparams.n_layer) {
  2774. case 36: model.type = e_model::MODEL_8B; break;
  2775. default: model.type = e_model::MODEL_UNKNOWN;
  2776. }
  2777. } break;
  2778. case LLM_ARCH_REFACT:
  2779. {
  2780. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2781. switch (hparams.n_layer) {
  2782. case 32: model.type = e_model::MODEL_1B; break;
  2783. default: model.type = e_model::MODEL_UNKNOWN;
  2784. }
  2785. // TODO: become GGUF KV parameter
  2786. hparams.f_max_alibi_bias = 8.0f;
  2787. } break;
  2788. case LLM_ARCH_BERT:
  2789. {
  2790. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2791. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2792. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2793. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  2794. switch (hparams.n_layer) {
  2795. case 3:
  2796. model.type = e_model::MODEL_17M; break; // bge-micro
  2797. case 6:
  2798. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2799. case 12:
  2800. switch (hparams.n_embd) {
  2801. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2802. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2803. } break;
  2804. case 24:
  2805. model.type = e_model::MODEL_335M; break; // bge-large
  2806. }
  2807. } break;
  2808. case LLM_ARCH_NOMIC_BERT:
  2809. {
  2810. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2811. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2812. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2813. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2814. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2815. model.type = e_model::MODEL_137M;
  2816. }
  2817. } break;
  2818. case LLM_ARCH_BLOOM:
  2819. {
  2820. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2821. switch (hparams.n_layer) {
  2822. case 24: model.type = e_model::MODEL_1B; break;
  2823. case 30:
  2824. switch (hparams.n_embd) {
  2825. case 2560: model.type = e_model::MODEL_3B; break;
  2826. case 4096: model.type = e_model::MODEL_7B; break;
  2827. } break;
  2828. }
  2829. // TODO: become GGUF KV parameter
  2830. hparams.f_max_alibi_bias = 8.0f;
  2831. } break;
  2832. case LLM_ARCH_MPT:
  2833. {
  2834. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2835. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2836. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2837. switch (hparams.n_layer) {
  2838. case 32: model.type = e_model::MODEL_7B; break;
  2839. case 48: model.type = e_model::MODEL_30B; break;
  2840. default: model.type = e_model::MODEL_UNKNOWN;
  2841. }
  2842. } break;
  2843. case LLM_ARCH_STABLELM:
  2844. {
  2845. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2846. switch (hparams.n_layer) {
  2847. case 24: model.type = e_model::MODEL_1B; break;
  2848. case 32: model.type = e_model::MODEL_3B; break;
  2849. default: model.type = e_model::MODEL_UNKNOWN;
  2850. }
  2851. } break;
  2852. case LLM_ARCH_QWEN:
  2853. {
  2854. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2855. switch (hparams.n_layer) {
  2856. case 32: model.type = e_model::MODEL_7B; break;
  2857. case 40: model.type = e_model::MODEL_13B; break;
  2858. default: model.type = e_model::MODEL_UNKNOWN;
  2859. }
  2860. } break;
  2861. case LLM_ARCH_QWEN2:
  2862. {
  2863. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2864. switch (hparams.n_layer) {
  2865. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2866. case 32: model.type = e_model::MODEL_7B; break;
  2867. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2868. case 80: model.type = e_model::MODEL_70B; break;
  2869. default: model.type = e_model::MODEL_UNKNOWN;
  2870. }
  2871. } break;
  2872. case LLM_ARCH_PHI2:
  2873. {
  2874. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2875. switch (hparams.n_layer) {
  2876. case 24: model.type = e_model::MODEL_1B; break;
  2877. case 32: model.type = e_model::MODEL_3B; break;
  2878. default: model.type = e_model::MODEL_UNKNOWN;
  2879. }
  2880. } break;
  2881. case LLM_ARCH_PLAMO:
  2882. {
  2883. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2884. switch (hparams.n_layer) {
  2885. case 40: model.type = e_model::MODEL_13B; break;
  2886. default: model.type = e_model::MODEL_UNKNOWN;
  2887. }
  2888. } break;
  2889. case LLM_ARCH_GPT2:
  2890. {
  2891. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2892. switch (hparams.n_layer) {
  2893. case 12: model.type = e_model::MODEL_SMALL; break;
  2894. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2895. case 36: model.type = e_model::MODEL_LARGE; break;
  2896. case 48: model.type = e_model::MODEL_XL; break;
  2897. default: model.type = e_model::MODEL_UNKNOWN;
  2898. }
  2899. } break;
  2900. case LLM_ARCH_CODESHELL:
  2901. {
  2902. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2903. switch (hparams.n_layer) {
  2904. case 42: model.type = e_model::MODEL_SMALL; break;
  2905. default: model.type = e_model::MODEL_UNKNOWN;
  2906. }
  2907. } break;
  2908. case LLM_ARCH_ORION:
  2909. {
  2910. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2911. switch (hparams.n_layer) {
  2912. case 40: model.type = e_model::MODEL_14B; break;
  2913. default: model.type = e_model::MODEL_UNKNOWN;
  2914. }
  2915. } break;
  2916. case LLM_ARCH_INTERNLM2:
  2917. {
  2918. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2919. switch (hparams.n_layer) {
  2920. case 32: model.type = e_model::MODEL_7B; break;
  2921. case 48: model.type = e_model::MODEL_20B; break;
  2922. default: model.type = e_model::MODEL_UNKNOWN;
  2923. }
  2924. } break;
  2925. case LLM_ARCH_GEMMA:
  2926. {
  2927. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2928. switch (hparams.n_layer) {
  2929. case 18: model.type = e_model::MODEL_2B; break;
  2930. case 28: model.type = e_model::MODEL_7B; break;
  2931. default: model.type = e_model::MODEL_UNKNOWN;
  2932. }
  2933. } break;
  2934. case LLM_ARCH_STARCODER2:
  2935. {
  2936. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2937. switch (hparams.n_layer) {
  2938. case 30: model.type = e_model::MODEL_3B; break;
  2939. case 32: model.type = e_model::MODEL_7B; break;
  2940. case 40: model.type = e_model::MODEL_15B; break;
  2941. default: model.type = e_model::MODEL_UNKNOWN;
  2942. }
  2943. } break;
  2944. default: (void)0;
  2945. }
  2946. model.ftype = ml.ftype;
  2947. if (hparams.f_max_alibi_bias > 0.0f) {
  2948. hparams.need_kq_pos = true;
  2949. }
  2950. hparams.rope_type = llama_rope_type(&model);
  2951. }
  2952. // TODO: This should probably be in llama.h
  2953. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2954. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2955. static void llm_load_vocab(
  2956. llama_model_loader & ml,
  2957. llama_model & model) {
  2958. auto & vocab = model.vocab;
  2959. struct gguf_context * ctx = ml.ctx_gguf;
  2960. const auto kv = LLM_KV(model.arch);
  2961. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2962. if (token_idx == -1) {
  2963. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2964. }
  2965. const float * scores = nullptr;
  2966. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2967. if (score_idx != -1) {
  2968. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2969. }
  2970. const int * toktypes = nullptr;
  2971. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2972. if (toktype_idx != -1) {
  2973. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2974. }
  2975. // determine vocab type
  2976. {
  2977. std::string tokenizer_name;
  2978. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2979. if (tokenizer_name == "llama") {
  2980. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2981. // default special tokens
  2982. vocab.special_bos_id = 1;
  2983. vocab.special_eos_id = 2;
  2984. vocab.special_unk_id = 0;
  2985. vocab.special_sep_id = -1;
  2986. vocab.special_pad_id = -1;
  2987. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2988. if (add_space_prefix_keyidx != -1) {
  2989. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2990. } // The default value of add_space_prefix is true.
  2991. } else if (tokenizer_name == "gpt2") {
  2992. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2993. // read bpe merges and populate bpe ranks
  2994. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2995. if (merges_keyidx == -1) {
  2996. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2997. }
  2998. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2999. for (int i = 0; i < n_merges; i++) {
  3000. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3001. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  3002. std::string first;
  3003. std::string second;
  3004. const size_t pos = word.find(' ', 1);
  3005. if (pos != std::string::npos) {
  3006. first = word.substr(0, pos);
  3007. second = word.substr(pos + 1);
  3008. }
  3009. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3010. }
  3011. // default special tokens
  3012. vocab.special_bos_id = 11;
  3013. vocab.special_eos_id = 11;
  3014. vocab.special_unk_id = -1;
  3015. vocab.special_sep_id = -1;
  3016. vocab.special_pad_id = -1;
  3017. } else if (tokenizer_name == "bert") {
  3018. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3019. // default special tokens
  3020. vocab.special_bos_id = 101;
  3021. vocab.special_eos_id = 102;
  3022. vocab.special_unk_id = 100;
  3023. vocab.special_sep_id = -1;
  3024. vocab.special_pad_id = -1;
  3025. vocab.add_space_prefix = false;
  3026. } else {
  3027. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3028. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3029. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3030. }
  3031. }
  3032. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3033. vocab.id_to_token.resize(n_vocab);
  3034. for (uint32_t i = 0; i < n_vocab; i++) {
  3035. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3036. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  3037. vocab.token_to_id[word] = i;
  3038. auto & token_data = vocab.id_to_token[i];
  3039. token_data.text = std::move(word);
  3040. token_data.score = scores ? scores[i] : 0.0f;
  3041. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3042. }
  3043. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3044. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3045. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3046. try {
  3047. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3048. } catch (const std::exception & e) {
  3049. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3050. vocab.linefeed_id = vocab.special_pad_id;
  3051. }
  3052. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3053. vocab.linefeed_id = vocab.special_pad_id;
  3054. } else {
  3055. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3056. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3057. vocab.linefeed_id = ids[0];
  3058. }
  3059. // special tokens
  3060. {
  3061. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3062. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3063. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3064. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3065. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3066. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3067. };
  3068. for (const auto & it : special_token_types) {
  3069. const std::string & key = kv(std::get<0>(it));
  3070. int32_t & id = std::get<1>(it);
  3071. uint32_t new_id;
  3072. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3073. continue;
  3074. }
  3075. if (new_id >= vocab.id_to_token.size()) {
  3076. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3077. __func__, key.c_str(), new_id, id);
  3078. } else {
  3079. id = new_id;
  3080. }
  3081. }
  3082. // Handle add_bos_token and add_eos_token
  3083. {
  3084. bool temp = true;
  3085. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3086. vocab.special_add_bos = int(temp);
  3087. }
  3088. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3089. vocab.special_add_eos = int(temp);
  3090. }
  3091. }
  3092. }
  3093. // build special tokens cache
  3094. {
  3095. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3096. // and will always be correctly labeled in 'added_tokens.json' etc.
  3097. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3098. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3099. // are special tokens.
  3100. // From testing, this appears to correlate 1:1 with special tokens.
  3101. //
  3102. // Counting special tokens and verifying in only one direction
  3103. // is sufficient to detect difference in those two sets.
  3104. //
  3105. uint32_t special_tokens_count_by_type = 0;
  3106. uint32_t special_tokens_count_from_verification = 0;
  3107. bool special_tokens_definition_mismatch = false;
  3108. for (const auto & t : vocab.token_to_id) {
  3109. const auto & token = t.first;
  3110. const auto & id = t.second;
  3111. // Count all non-normal tokens in the vocab while iterating
  3112. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3113. special_tokens_count_by_type++;
  3114. }
  3115. // Skip single character tokens
  3116. if (token.length() > 1) {
  3117. bool is_tokenizable = false;
  3118. // Split token string representation in two, in all possible ways
  3119. // and check if both halves can be matched to a valid token
  3120. for (unsigned i = 1; i < token.length();) {
  3121. const auto left = token.substr(0, i);
  3122. const auto right = token.substr(i);
  3123. // check if we didnt partition in the middle of a utf sequence
  3124. auto utf = utf8_len(left.at(left.length() - 1));
  3125. if (utf == 1) {
  3126. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3127. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3128. is_tokenizable = true;
  3129. break;
  3130. }
  3131. i++;
  3132. } else {
  3133. // skip over the rest of multibyte utf sequence
  3134. i += utf - 1;
  3135. }
  3136. }
  3137. if (!is_tokenizable) {
  3138. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3139. // it's faster to re-filter them here, since there are way less candidates now
  3140. // Calculate a total "utf" length of a token string representation
  3141. size_t utf8_str_len = 0;
  3142. for (unsigned i = 0; i < token.length();) {
  3143. utf8_str_len++;
  3144. i += utf8_len(token.at(i));
  3145. }
  3146. // And skip the ones which are one character
  3147. if (utf8_str_len > 1) {
  3148. // At this point what we have left are special tokens only
  3149. vocab.special_tokens_cache[token] = id;
  3150. // Count manually found special tokens
  3151. special_tokens_count_from_verification++;
  3152. // If this manually found special token is not marked as such, flag a mismatch
  3153. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3154. special_tokens_definition_mismatch = true;
  3155. }
  3156. }
  3157. }
  3158. }
  3159. }
  3160. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3161. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3162. __func__,
  3163. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3164. special_tokens_count_by_type, vocab.id_to_token.size()
  3165. );
  3166. } else {
  3167. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3168. __func__,
  3169. special_tokens_count_from_verification, vocab.id_to_token.size()
  3170. );
  3171. }
  3172. }
  3173. }
  3174. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3175. const auto & hparams = model.hparams;
  3176. const auto & vocab = model.vocab;
  3177. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3178. // hparams
  3179. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3180. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3181. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3182. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3183. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3184. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3185. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3186. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3187. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3188. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3189. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3190. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3191. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3192. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3193. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3194. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3195. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3196. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3197. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3198. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3199. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3200. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3201. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3202. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3203. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3204. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3205. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3206. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3207. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3208. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3209. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3210. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3211. if (ml.n_elements >= 1e12) {
  3212. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3213. } else if (ml.n_elements >= 1e9) {
  3214. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3215. } else if (ml.n_elements >= 1e6) {
  3216. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3217. } else {
  3218. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3219. }
  3220. if (ml.n_bytes < GiB) {
  3221. 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);
  3222. } else {
  3223. 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);
  3224. }
  3225. // general kv
  3226. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3227. // special tokens
  3228. 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() ); }
  3229. 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() ); }
  3230. 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() ); }
  3231. 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() ); }
  3232. 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() ); }
  3233. 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() ); }
  3234. }
  3235. // Returns false if cancelled by progress_callback
  3236. static bool llm_load_tensors(
  3237. llama_model_loader & ml,
  3238. llama_model & model,
  3239. int n_gpu_layers,
  3240. enum llama_split_mode split_mode,
  3241. int main_gpu,
  3242. const float * tensor_split,
  3243. bool use_mlock,
  3244. llama_progress_callback progress_callback,
  3245. void * progress_callback_user_data) {
  3246. model.t_start_us = ggml_time_us();
  3247. auto & hparams = model.hparams;
  3248. model.split_mode = split_mode;
  3249. model.main_gpu = main_gpu;
  3250. model.n_gpu_layers = n_gpu_layers;
  3251. const int64_t n_layer = hparams.n_layer;
  3252. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3253. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3254. model.buft_input = llama_default_buffer_type_cpu(true);
  3255. model.buft_layer.resize(n_layer);
  3256. // assign cpu layers
  3257. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3258. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3259. }
  3260. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3261. // calculate the split points
  3262. int device_count = llama_get_device_count();
  3263. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3264. std::vector<float> splits(device_count);
  3265. if (all_zero) {
  3266. // default split, by free memory
  3267. for (int i = 0; i < device_count; ++i) {
  3268. splits[i] = llama_get_device_memory(i);
  3269. }
  3270. } else {
  3271. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3272. }
  3273. // sum and normalize the splits to get the split points
  3274. float split_sum = 0.0f;
  3275. for (int i = 0; i < device_count; ++i) {
  3276. split_sum += splits[i];
  3277. splits[i] = split_sum;
  3278. }
  3279. for (int i = 0; i < device_count; ++i) {
  3280. splits[i] /= split_sum;
  3281. }
  3282. // assign the repeating layers to the devices according to the splits
  3283. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3284. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3285. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3286. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3287. }
  3288. // assign the output layer
  3289. if (n_gpu_layers > n_layer) {
  3290. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3291. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3292. } else {
  3293. model.buft_output = llama_default_buffer_type_cpu(true);
  3294. }
  3295. } else {
  3296. ggml_backend_buffer_type_t split_buft;
  3297. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3298. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3299. } else {
  3300. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3301. split_buft = llama_default_buffer_type_offload(main_gpu);
  3302. }
  3303. // assign the repeating layers
  3304. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3305. model.buft_layer[i] = {
  3306. split_buft,
  3307. llama_default_buffer_type_offload(main_gpu)
  3308. };
  3309. }
  3310. // assign the output layer
  3311. if (n_gpu_layers > n_layer) {
  3312. model.buft_output = {
  3313. split_buft,
  3314. llama_default_buffer_type_offload(main_gpu)
  3315. };
  3316. } else {
  3317. model.buft_output = llama_default_buffer_type_cpu(true);
  3318. }
  3319. }
  3320. // count used buffer types
  3321. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3322. buft_layer_count[model.buft_input.buft]++;
  3323. buft_layer_count[model.buft_input.buft_matrix]++;
  3324. buft_layer_count[model.buft_output.buft]++;
  3325. buft_layer_count[model.buft_output.buft_matrix]++;
  3326. for (int64_t i = 0; i < n_layer; ++i) {
  3327. buft_layer_count[model.buft_layer[i].buft]++;
  3328. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3329. }
  3330. // create one context per buffer type
  3331. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3332. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3333. for (auto & it : buft_layer_count) {
  3334. struct ggml_init_params params = {
  3335. /*.mem_size =*/ ctx_size,
  3336. /*.mem_buffer =*/ NULL,
  3337. /*.no_alloc =*/ true,
  3338. };
  3339. ggml_context * ctx = ggml_init(params);
  3340. if (!ctx) {
  3341. throw std::runtime_error(format("failed to create context"));
  3342. }
  3343. ctx_map[it.first] = ctx;
  3344. model.ctxs.push_back(ctx);
  3345. }
  3346. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3347. // create tensors for the weights
  3348. {
  3349. const int64_t n_embd = hparams.n_embd;
  3350. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3351. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3352. const int64_t n_embd_gqa = n_embd_v_gqa;
  3353. const int64_t n_vocab = hparams.n_vocab;
  3354. const int64_t n_vocab_type = hparams.n_vocab_type;
  3355. const int64_t n_ff = hparams.n_ff;
  3356. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3357. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3358. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3359. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3360. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3361. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3362. model.layers.resize(n_layer);
  3363. const auto tn = LLM_TN(model.arch);
  3364. switch (model.arch) {
  3365. case LLM_ARCH_LLAMA:
  3366. case LLM_ARCH_REFACT:
  3367. case LLM_ARCH_MINICPM:
  3368. {
  3369. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3370. // output
  3371. {
  3372. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3373. if (model.arch != LLM_ARCH_MINICPM){
  3374. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3375. }
  3376. }
  3377. for (int i = 0; i < n_layer; ++i) {
  3378. ggml_context * ctx_layer = ctx_for_layer(i);
  3379. ggml_context * ctx_split = ctx_for_layer_split(i);
  3380. auto & layer = model.layers[i];
  3381. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3382. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3383. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3384. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3385. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3386. // optional bias tensors
  3387. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3388. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3389. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3390. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3391. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3392. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3393. if (layer.ffn_gate_inp == nullptr) {
  3394. GGML_ASSERT(hparams.n_expert == 0);
  3395. GGML_ASSERT(hparams.n_expert_used == 0);
  3396. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3397. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3398. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3399. } else {
  3400. GGML_ASSERT(hparams.n_expert > 0);
  3401. GGML_ASSERT(hparams.n_expert_used > 0);
  3402. // MoE branch
  3403. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3404. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3405. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3406. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3407. }
  3408. }
  3409. }
  3410. } break;
  3411. case LLM_ARCH_BAICHUAN:
  3412. {
  3413. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3414. {
  3415. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3416. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3417. }
  3418. for (int i = 0; i < n_layer; ++i) {
  3419. ggml_context * ctx_layer = ctx_for_layer(i);
  3420. ggml_context * ctx_split = ctx_for_layer_split(i);
  3421. auto & layer = model.layers[i];
  3422. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3423. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3424. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3425. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3426. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3427. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3428. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3429. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3430. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3431. }
  3432. } break;
  3433. case LLM_ARCH_FALCON:
  3434. {
  3435. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3436. // output
  3437. {
  3438. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3439. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3440. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3441. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3442. } else {
  3443. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3444. ml.n_created--; // artificial tensor
  3445. ml.size_data += ggml_nbytes(model.output);
  3446. }
  3447. }
  3448. for (int i = 0; i < n_layer; ++i) {
  3449. ggml_context * ctx_layer = ctx_for_layer(i);
  3450. ggml_context * ctx_split = ctx_for_layer_split(i);
  3451. auto & layer = model.layers[i];
  3452. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3453. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3454. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3455. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3456. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3457. }
  3458. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3459. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3460. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3461. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3462. }
  3463. } break;
  3464. case LLM_ARCH_STARCODER:
  3465. {
  3466. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3467. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3468. // output
  3469. {
  3470. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3471. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3472. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3473. }
  3474. for (int i = 0; i < n_layer; ++i) {
  3475. ggml_context * ctx_layer = ctx_for_layer(i);
  3476. ggml_context * ctx_split = ctx_for_layer_split(i);
  3477. auto & layer = model.layers[i];
  3478. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3479. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3480. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3481. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3482. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3483. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3484. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3485. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3486. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3487. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3488. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3489. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3490. }
  3491. } break;
  3492. case LLM_ARCH_PERSIMMON:
  3493. {
  3494. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3495. {
  3496. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3497. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3498. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3499. }
  3500. for (int i = 0; i < n_layer; ++i) {
  3501. ggml_context * ctx_layer = ctx_for_layer(i);
  3502. ggml_context * ctx_split = ctx_for_layer_split(i);
  3503. auto & layer = model.layers[i];
  3504. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3505. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3506. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3507. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3508. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3509. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3510. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3511. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3512. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3513. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3514. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3515. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3516. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3517. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3518. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3519. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3520. }
  3521. } break;
  3522. case LLM_ARCH_BERT:
  3523. case LLM_ARCH_NOMIC_BERT:
  3524. {
  3525. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3526. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3527. if (model.arch == LLM_ARCH_BERT) {
  3528. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3529. }
  3530. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3531. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3532. for (int i = 0; i < n_layer; ++i) {
  3533. ggml_context * ctx_layer = ctx_for_layer(i);
  3534. ggml_context * ctx_split = ctx_for_layer_split(i);
  3535. auto & layer = model.layers[i];
  3536. if (model.arch == LLM_ARCH_BERT) {
  3537. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3538. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3539. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3540. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3541. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3542. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3543. } else {
  3544. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3545. }
  3546. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3547. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3548. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3549. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3550. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3551. if (model.arch == LLM_ARCH_BERT) {
  3552. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3553. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3554. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3555. } else {
  3556. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3557. }
  3558. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3559. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3560. }
  3561. } break;
  3562. case LLM_ARCH_BLOOM:
  3563. {
  3564. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3565. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3566. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3567. // output
  3568. {
  3569. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3570. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3571. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3572. }
  3573. for (int i = 0; i < n_layer; ++i) {
  3574. ggml_context * ctx_layer = ctx_for_layer(i);
  3575. ggml_context * ctx_split = ctx_for_layer_split(i);
  3576. auto & layer = model.layers[i];
  3577. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3578. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3579. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3580. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3581. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3582. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3583. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3584. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3585. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3586. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3587. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3588. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3589. }
  3590. } break;
  3591. case LLM_ARCH_MPT:
  3592. {
  3593. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3594. // output
  3595. {
  3596. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3597. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3598. // same as tok_embd, duplicated to allow offloading
  3599. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3600. ml.n_created--; // artificial tensor
  3601. ml.size_data += ggml_nbytes(model.output);
  3602. }
  3603. for (int i = 0; i < n_layer; ++i) {
  3604. ggml_context * ctx_layer = ctx_for_layer(i);
  3605. ggml_context * ctx_split = ctx_for_layer_split(i);
  3606. auto & layer = model.layers[i];
  3607. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3608. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3609. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3610. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3611. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3612. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3613. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3614. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3615. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3616. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3617. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3618. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3619. // AWQ ScaleActivation layer
  3620. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3621. }
  3622. } break;
  3623. case LLM_ARCH_STABLELM:
  3624. {
  3625. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3626. // output
  3627. {
  3628. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3629. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3630. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3631. }
  3632. for (int i = 0; i < n_layer; ++i) {
  3633. ggml_context * ctx_layer = ctx_for_layer(i);
  3634. ggml_context * ctx_split = ctx_for_layer_split(i);
  3635. auto & layer = model.layers[i];
  3636. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3637. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3638. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3639. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3640. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3641. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3642. // optional bias tensors, present in Stable LM 2 1.6B
  3643. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3644. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3645. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3646. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3647. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3648. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3649. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3650. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3651. }
  3652. } break;
  3653. case LLM_ARCH_QWEN:
  3654. {
  3655. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3656. // output
  3657. {
  3658. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3659. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3660. }
  3661. for (int i = 0; i < n_layer; ++i) {
  3662. ggml_context * ctx_layer = ctx_for_layer(i);
  3663. ggml_context * ctx_split = ctx_for_layer_split(i);
  3664. auto & layer = model.layers[i];
  3665. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3666. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3667. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3668. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3669. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3670. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3671. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3672. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3673. }
  3674. } break;
  3675. case LLM_ARCH_QWEN2:
  3676. {
  3677. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3678. // output
  3679. {
  3680. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3681. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3682. }
  3683. for (int i = 0; i < n_layer; ++i) {
  3684. ggml_context * ctx_layer = ctx_for_layer(i);
  3685. ggml_context * ctx_split = ctx_for_layer_split(i);
  3686. auto & layer = model.layers[i];
  3687. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3688. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3689. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3690. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3691. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3692. // optional bias tensors
  3693. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3694. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3695. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3696. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3697. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3698. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3699. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3700. }
  3701. } break;
  3702. case LLM_ARCH_PHI2:
  3703. {
  3704. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3705. // output
  3706. {
  3707. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3708. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3709. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3710. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3711. }
  3712. for (int i = 0; i < n_layer; ++i) {
  3713. ggml_context * ctx_layer = ctx_for_layer(i);
  3714. ggml_context * ctx_split = ctx_for_layer_split(i);
  3715. auto & layer = model.layers[i];
  3716. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3717. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3718. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3719. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3720. if (layer.wqkv == nullptr) {
  3721. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3722. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3723. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3724. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3725. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3726. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3727. }
  3728. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3729. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3730. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3731. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3732. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3733. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3734. }
  3735. } break;
  3736. case LLM_ARCH_PLAMO:
  3737. {
  3738. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3739. // output
  3740. {
  3741. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3742. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3743. }
  3744. for (int i = 0; i < n_layer; ++i) {
  3745. ggml_context * ctx_layer = ctx_for_layer(i);
  3746. ggml_context * ctx_split = ctx_for_layer_split(i);
  3747. auto & layer = model.layers[i];
  3748. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3749. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3750. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3751. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3752. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3753. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3754. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3755. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3756. }
  3757. } break;
  3758. case LLM_ARCH_GPT2:
  3759. {
  3760. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3761. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3762. // output
  3763. {
  3764. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3765. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3766. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3767. }
  3768. for (int i = 0; i < n_layer; ++i) {
  3769. ggml_context * ctx_layer = ctx_for_layer(i);
  3770. ggml_context * ctx_split = ctx_for_layer_split(i);
  3771. auto & layer = model.layers[i];
  3772. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3773. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3774. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3775. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3776. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3777. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3778. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3779. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3780. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3781. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3782. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3783. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3784. }
  3785. } break;
  3786. case LLM_ARCH_CODESHELL:
  3787. {
  3788. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3789. // output
  3790. {
  3791. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3792. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3793. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3794. }
  3795. for (int i = 0; i < n_layer; ++i) {
  3796. ggml_context * ctx_layer = ctx_for_layer(i);
  3797. ggml_context * ctx_split = ctx_for_layer_split(i);
  3798. auto & layer = model.layers[i];
  3799. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3800. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3801. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3802. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3803. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3804. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3805. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3806. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3807. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3808. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3809. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3810. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3811. }
  3812. } break;
  3813. case LLM_ARCH_ORION:
  3814. {
  3815. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3816. {
  3817. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3818. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3819. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3820. }
  3821. for (int i = 0; i < n_layer; ++i) {
  3822. ggml_context * ctx_layer = ctx_for_layer(i);
  3823. ggml_context * ctx_split = ctx_for_layer_split(i);
  3824. auto & layer = model.layers[i];
  3825. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3826. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3827. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3828. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3829. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3830. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3831. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3832. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3833. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3834. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3835. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3836. }
  3837. } break;
  3838. case LLM_ARCH_INTERNLM2:
  3839. {
  3840. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3841. // output
  3842. {
  3843. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3844. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3845. }
  3846. for (int i = 0; i < n_layer; ++i) {
  3847. ggml_context * ctx_layer = ctx_for_layer(i);
  3848. ggml_context * ctx_split = ctx_for_layer_split(i);
  3849. auto & layer = model.layers[i];
  3850. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3851. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3852. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3853. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3854. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3855. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3856. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3857. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3858. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3859. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3860. }
  3861. } break;
  3862. case LLM_ARCH_GEMMA:
  3863. {
  3864. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3865. // output
  3866. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3867. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // same as tok_embd, duplicated to allow offloading
  3868. ml.n_created--; // artificial tensor
  3869. ml.size_data += ggml_nbytes(model.output);
  3870. const int64_t n_ff = hparams.n_ff;
  3871. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3872. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3873. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3874. for (uint32_t i = 0; i < n_layer; ++i) {
  3875. ggml_context * ctx_layer = ctx_for_layer(i);
  3876. ggml_context * ctx_split = ctx_for_layer_split(i);
  3877. auto & layer = model.layers[i];
  3878. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3879. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3880. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3881. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3882. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3883. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3884. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3885. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3886. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3887. }
  3888. } break;
  3889. case LLM_ARCH_STARCODER2:
  3890. {
  3891. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3892. // output
  3893. {
  3894. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3895. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3896. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3897. // if output is NULL, init from the input tok embed
  3898. if (model.output == NULL) {
  3899. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3900. ml.n_created--; // artificial tensor
  3901. ml.size_data += ggml_nbytes(model.output);
  3902. }
  3903. }
  3904. for (int i = 0; i < n_layer; ++i) {
  3905. ggml_context * ctx_layer = ctx_for_layer(i);
  3906. ggml_context * ctx_split = ctx_for_layer_split(i);
  3907. auto & layer = model.layers[i];
  3908. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3909. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3910. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3911. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3912. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3913. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3914. // optional bias tensors
  3915. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3916. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3917. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3918. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3919. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3920. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3921. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3922. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3923. // optional bias tensors
  3924. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3925. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  3926. }
  3927. } break;
  3928. default:
  3929. throw std::runtime_error("unknown architecture");
  3930. }
  3931. }
  3932. ml.done_getting_tensors();
  3933. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3934. // create the backend buffers
  3935. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3936. for (auto & it : ctx_map) {
  3937. ggml_backend_buffer_type_t buft = it.first;
  3938. ggml_context * ctx = it.second;
  3939. ggml_backend_buffer_t buf = nullptr;
  3940. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3941. // 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
  3942. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3943. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3944. size_t first, last;
  3945. ml.get_mapping_range(&first, &last, ctx);
  3946. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3947. }
  3948. #ifdef GGML_USE_METAL
  3949. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3950. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3951. size_t first, last;
  3952. ml.get_mapping_range(&first, &last, ctx);
  3953. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3954. }
  3955. #endif
  3956. else {
  3957. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3958. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3959. model.mlock_bufs.emplace_back(new llama_mlock);
  3960. auto & mlock_buf = model.mlock_bufs.back();
  3961. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3962. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3963. }
  3964. }
  3965. if (buf == nullptr) {
  3966. throw std::runtime_error("failed to allocate buffer");
  3967. }
  3968. // indicate that this buffer contains weights
  3969. // 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
  3970. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3971. model.bufs.push_back(buf);
  3972. ctx_bufs.emplace_back(ctx, buf);
  3973. }
  3974. if (llama_supports_gpu_offload()) {
  3975. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3976. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3977. if (n_gpu_layers > (int) hparams.n_layer) {
  3978. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3979. }
  3980. const int max_backend_supported_layers = hparams.n_layer + 1;
  3981. const int max_offloadable_layers = hparams.n_layer + 1;
  3982. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3983. }
  3984. // print memory requirements
  3985. for (ggml_backend_buffer_t buf : model.bufs) {
  3986. 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);
  3987. }
  3988. // populate tensors_by_name
  3989. for (ggml_context * ctx : model.ctxs) {
  3990. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3991. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3992. }
  3993. }
  3994. // load tensor data
  3995. for (auto & it : ctx_bufs) {
  3996. ggml_context * ctx = it.first;
  3997. ggml_backend_buffer_t buf = it.second;
  3998. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3999. return false;
  4000. }
  4001. }
  4002. model.mapping = std::move(ml.mapping);
  4003. // loading time will be recalculate after the first eval, so
  4004. // we take page faults deferred by mmap() into consideration
  4005. model.t_load_us = ggml_time_us() - model.t_start_us;
  4006. return true;
  4007. }
  4008. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4009. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4010. try {
  4011. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4012. model.hparams.vocab_only = params.vocab_only;
  4013. try {
  4014. llm_load_arch(ml, model);
  4015. } catch(const std::exception & e) {
  4016. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4017. }
  4018. try {
  4019. llm_load_hparams(ml, model);
  4020. } catch(const std::exception & e) {
  4021. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4022. }
  4023. try {
  4024. llm_load_vocab(ml, model);
  4025. } catch(const std::exception & e) {
  4026. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4027. }
  4028. llm_load_print_meta(ml, model);
  4029. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4030. throw std::runtime_error("vocab size mismatch");
  4031. }
  4032. if (params.vocab_only) {
  4033. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4034. return 0;
  4035. }
  4036. #ifdef GGML_USE_KOMPUTE
  4037. if (params.n_gpu_layers > 0 && (
  4038. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4039. || !(
  4040. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4041. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4042. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4043. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4044. )
  4045. )) {
  4046. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4047. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4048. params.n_gpu_layers = 0;
  4049. }
  4050. #endif
  4051. if (!llm_load_tensors(
  4052. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4053. params.progress_callback, params.progress_callback_user_data
  4054. )) {
  4055. return -2;
  4056. }
  4057. } catch (const std::exception & err) {
  4058. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4059. return -1;
  4060. }
  4061. return 0;
  4062. }
  4063. //
  4064. // llm_build
  4065. //
  4066. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4067. enum llm_ffn_op_type {
  4068. LLM_FFN_SILU,
  4069. LLM_FFN_GELU,
  4070. LLM_FFN_RELU,
  4071. LLM_FFN_RELU_SQR,
  4072. };
  4073. enum llm_ffn_gate_type {
  4074. LLM_FFN_SEQ,
  4075. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4076. };
  4077. enum llm_norm_type {
  4078. LLM_NORM,
  4079. LLM_NORM_RMS,
  4080. };
  4081. static struct ggml_tensor * llm_build_inp_embd(
  4082. struct ggml_context * ctx,
  4083. const llama_hparams & hparams,
  4084. const llama_batch & batch,
  4085. struct ggml_tensor * tok_embd,
  4086. struct ggml_tensor * inp_tokens,
  4087. struct ggml_tensor * inp_embd,
  4088. const llm_build_cb & cb) {
  4089. const int64_t n_embd = hparams.n_embd;
  4090. struct ggml_tensor * inpL;
  4091. if (batch.token) {
  4092. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  4093. cb(inp_tokens, "inp_tokens", -1);
  4094. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  4095. } else {
  4096. #ifdef GGML_USE_MPI
  4097. GGML_ASSERT(false && "not implemented");
  4098. #endif
  4099. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  4100. }
  4101. return inpL;
  4102. }
  4103. static void llm_build_kv_store(
  4104. struct ggml_context * ctx,
  4105. const llama_hparams & hparams,
  4106. const llama_kv_cache & kv,
  4107. struct ggml_cgraph * graph,
  4108. struct ggml_tensor * k_cur,
  4109. struct ggml_tensor * v_cur,
  4110. int64_t n_ctx,
  4111. int32_t n_tokens,
  4112. int32_t kv_head,
  4113. const llm_build_cb & cb,
  4114. int64_t il) {
  4115. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4116. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4117. // compute the transposed [n_tokens, n_embd] V matrix
  4118. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4119. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4120. cb(v_cur_t, "v_cur_t", il);
  4121. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4122. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4123. cb(k_cache_view, "k_cache_view", il);
  4124. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4125. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4126. (kv_head)*ggml_element_size(kv.v_l[il]));
  4127. cb(v_cache_view, "v_cache_view", il);
  4128. // important: storing RoPE-ed version of K in the KV cache!
  4129. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4130. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4131. }
  4132. static struct ggml_tensor * llm_build_norm(
  4133. struct ggml_context * ctx,
  4134. struct ggml_tensor * cur,
  4135. const llama_hparams & hparams,
  4136. struct ggml_tensor * mw,
  4137. struct ggml_tensor * mb,
  4138. llm_norm_type type,
  4139. const llm_build_cb & cb,
  4140. int il) {
  4141. switch (type) {
  4142. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4143. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4144. }
  4145. if (mw || mb) {
  4146. cb(cur, "norm", il);
  4147. }
  4148. if (mw) {
  4149. cur = ggml_mul(ctx, cur, mw);
  4150. if (mb) {
  4151. cb(cur, "norm_w", il);
  4152. }
  4153. }
  4154. if (mb) {
  4155. cur = ggml_add(ctx, cur, mb);
  4156. }
  4157. return cur;
  4158. }
  4159. static struct ggml_tensor * llm_build_ffn(
  4160. struct ggml_context * ctx,
  4161. struct ggml_tensor * cur,
  4162. struct ggml_tensor * up,
  4163. struct ggml_tensor * up_b,
  4164. struct ggml_tensor * gate,
  4165. struct ggml_tensor * gate_b,
  4166. struct ggml_tensor * down,
  4167. struct ggml_tensor * down_b,
  4168. struct ggml_tensor * act_scales,
  4169. llm_ffn_op_type type_op,
  4170. llm_ffn_gate_type type_gate,
  4171. const llm_build_cb & cb,
  4172. int il) {
  4173. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4174. cb(tmp, "ffn_up", il);
  4175. if (up_b) {
  4176. tmp = ggml_add(ctx, tmp, up_b);
  4177. cb(tmp, "ffn_up_b", il);
  4178. }
  4179. if (gate) {
  4180. switch (type_gate) {
  4181. case LLM_FFN_SEQ:
  4182. {
  4183. cur = ggml_mul_mat(ctx, gate, tmp);
  4184. cb(cur, "ffn_gate", il);
  4185. } break;
  4186. case LLM_FFN_PAR:
  4187. {
  4188. cur = ggml_mul_mat(ctx, gate, cur);
  4189. cb(cur, "ffn_gate", il);
  4190. } break;
  4191. }
  4192. if (gate_b) {
  4193. cur = ggml_add(ctx, cur, gate_b);
  4194. cb(cur, "ffn_gate_b", il);
  4195. }
  4196. } else {
  4197. cur = tmp;
  4198. }
  4199. switch (type_op) {
  4200. case LLM_FFN_SILU:
  4201. {
  4202. cur = ggml_silu(ctx, cur);
  4203. cb(cur, "ffn_silu", il);
  4204. } break;
  4205. case LLM_FFN_GELU:
  4206. {
  4207. cur = ggml_gelu(ctx, cur);
  4208. cb(cur, "ffn_gelu", il);
  4209. if (act_scales != NULL) {
  4210. cur = ggml_div(ctx, cur, act_scales);
  4211. cb(cur, "ffn_act", il);
  4212. }
  4213. } break;
  4214. case LLM_FFN_RELU:
  4215. {
  4216. cur = ggml_relu(ctx, cur);
  4217. cb(cur, "ffn_relu", il);
  4218. } break;
  4219. case LLM_FFN_RELU_SQR:
  4220. {
  4221. cur = ggml_relu(ctx, cur);
  4222. cb(cur, "ffn_relu", il);
  4223. cur = ggml_sqr(ctx, cur);
  4224. cb(cur, "ffn_sqr(relu)", il);
  4225. } break;
  4226. }
  4227. if (type_gate == LLM_FFN_PAR) {
  4228. cur = ggml_mul(ctx, cur, tmp);
  4229. cb(cur, "ffn_gate_par", il);
  4230. }
  4231. cur = ggml_mul_mat(ctx, down, cur);
  4232. if (down_b) {
  4233. cb(cur, "ffn_down", il);
  4234. }
  4235. if (down_b) {
  4236. cur = ggml_add(ctx, cur, down_b);
  4237. }
  4238. return cur;
  4239. }
  4240. // if max_alibi_bias > 0 then apply ALiBi
  4241. static struct ggml_tensor * llm_build_kqv(
  4242. struct ggml_context * ctx,
  4243. const llama_model & model,
  4244. const llama_hparams & hparams,
  4245. const llama_kv_cache & kv,
  4246. struct ggml_cgraph * graph,
  4247. struct ggml_tensor * wo,
  4248. struct ggml_tensor * wo_b,
  4249. struct ggml_tensor * q_cur,
  4250. struct ggml_tensor * kq_mask,
  4251. struct ggml_tensor * kq_pos,
  4252. int64_t n_ctx,
  4253. int32_t n_tokens,
  4254. int32_t n_kv,
  4255. float kq_scale,
  4256. const llm_build_cb & cb,
  4257. int il) {
  4258. const int64_t n_head = hparams.n_head;
  4259. const int64_t n_head_kv = hparams.n_head_kv;
  4260. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4261. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4262. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4263. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4264. cb(q, "q", il);
  4265. struct ggml_tensor * k =
  4266. ggml_view_3d(ctx, kv.k_l[il],
  4267. n_embd_head_k, n_kv, n_head_kv,
  4268. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4269. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4270. 0);
  4271. cb(k, "k", il);
  4272. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4273. cb(kq, "kq", il);
  4274. if (model.arch == LLM_ARCH_PHI2) {
  4275. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4276. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4277. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4278. }
  4279. #if defined(GGML_USE_VULKAN) || defined(GGML_USE_KOMPUTE)
  4280. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Vulkan, and Kompute")
  4281. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4282. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4283. if (hparams.f_max_alibi_bias > 0.0f) {
  4284. kq = ggml_scale(ctx, kq, kq_scale);
  4285. cb(kq, "kq_scaled", il);
  4286. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4287. cb(kq, "kq_scaled_alibi", il);
  4288. kq = ggml_add(ctx, kq, kq_mask);
  4289. cb(kq, "kq_masked", il);
  4290. kq = ggml_soft_max(ctx, kq);
  4291. cb(kq, "kq_soft_max", il);
  4292. } else
  4293. #endif
  4294. {
  4295. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4296. cb(kq, "kq_soft_max_ext", il);
  4297. }
  4298. // split cached v into n_head heads
  4299. struct ggml_tensor * v =
  4300. ggml_view_3d(ctx, kv.v_l[il],
  4301. n_kv, n_embd_head_v, n_head_kv,
  4302. ggml_element_size(kv.v_l[il])*n_ctx,
  4303. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4304. 0);
  4305. cb(v, "v", il);
  4306. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4307. cb(kqv, "kqv", il);
  4308. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4309. cb(kqv_merged, "kqv_merged", il);
  4310. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4311. cb(cur, "kqv_merged_cont", il);
  4312. ggml_build_forward_expand(graph, cur);
  4313. cur = ggml_mul_mat(ctx, wo, cur);
  4314. if (wo_b) {
  4315. cb(cur, "kqv_wo", il);
  4316. }
  4317. if (wo_b) {
  4318. cur = ggml_add(ctx, cur, wo_b);
  4319. }
  4320. return cur;
  4321. }
  4322. static struct ggml_tensor * llm_build_kv(
  4323. struct ggml_context * ctx,
  4324. const llama_model & model,
  4325. const llama_hparams & hparams,
  4326. const llama_kv_cache & kv,
  4327. struct ggml_cgraph * graph,
  4328. struct ggml_tensor * wo,
  4329. struct ggml_tensor * wo_b,
  4330. struct ggml_tensor * k_cur,
  4331. struct ggml_tensor * v_cur,
  4332. struct ggml_tensor * q_cur,
  4333. struct ggml_tensor * kq_mask,
  4334. struct ggml_tensor * kq_pos,
  4335. int64_t n_ctx,
  4336. int32_t n_tokens,
  4337. int32_t kv_head,
  4338. int32_t n_kv,
  4339. float kq_scale,
  4340. const llm_build_cb & cb,
  4341. int il) {
  4342. // these nodes are added to the graph together so that they are not reordered
  4343. // by doing so, the number of splits in the graph is reduced
  4344. ggml_build_forward_expand(graph, q_cur);
  4345. ggml_build_forward_expand(graph, k_cur);
  4346. ggml_build_forward_expand(graph, v_cur);
  4347. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4348. struct ggml_tensor * cur;
  4349. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4350. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4351. cb(cur, "kqv_out", il);
  4352. return cur;
  4353. }
  4354. struct llm_build_context {
  4355. const llama_model & model;
  4356. const llama_context & lctx;
  4357. const llama_hparams & hparams;
  4358. const llama_cparams & cparams;
  4359. const llama_batch & batch;
  4360. const llama_kv_cache & kv_self;
  4361. const int64_t n_embd;
  4362. const int64_t n_layer;
  4363. const int64_t n_rot;
  4364. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4365. const int64_t n_head;
  4366. const int64_t n_head_kv;
  4367. const int64_t n_embd_head_k;
  4368. const int64_t n_embd_k_gqa;
  4369. const int64_t n_embd_head_v;
  4370. const int64_t n_embd_v_gqa;
  4371. const int64_t n_expert;
  4372. const int64_t n_expert_used;
  4373. const float freq_base;
  4374. const float freq_scale;
  4375. const float ext_factor;
  4376. const float attn_factor;
  4377. const float beta_fast;
  4378. const float beta_slow;
  4379. const float norm_eps;
  4380. const float norm_rms_eps;
  4381. const int32_t n_tokens;
  4382. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4383. const int32_t kv_head; // index of where we store new KV data in the cache
  4384. const int32_t n_orig_ctx;
  4385. const enum llama_pooling_type pooling_type;
  4386. const enum llama_rope_type rope_type;
  4387. const llm_build_cb & cb;
  4388. std::vector<uint8_t> & buf_compute_meta;
  4389. struct ggml_context * ctx0 = nullptr;
  4390. // TODO: consider making the entire interface noexcept
  4391. llm_build_context(
  4392. llama_context & lctx,
  4393. const llama_batch & batch,
  4394. const llm_build_cb & cb,
  4395. bool worst_case) :
  4396. model (lctx.model),
  4397. lctx (lctx),
  4398. hparams (model.hparams),
  4399. cparams (lctx.cparams),
  4400. batch (batch),
  4401. kv_self (lctx.kv_self),
  4402. n_embd (hparams.n_embd),
  4403. n_layer (hparams.n_layer),
  4404. n_rot (hparams.n_rot),
  4405. n_ctx (cparams.n_ctx),
  4406. n_head (hparams.n_head),
  4407. n_head_kv (hparams.n_head_kv),
  4408. n_embd_head_k (hparams.n_embd_head_k),
  4409. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4410. n_embd_head_v (hparams.n_embd_head_v),
  4411. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4412. n_expert (hparams.n_expert),
  4413. n_expert_used (hparams.n_expert_used),
  4414. freq_base (cparams.rope_freq_base),
  4415. freq_scale (cparams.rope_freq_scale),
  4416. ext_factor (cparams.yarn_ext_factor),
  4417. attn_factor (cparams.yarn_attn_factor),
  4418. beta_fast (cparams.yarn_beta_fast),
  4419. beta_slow (cparams.yarn_beta_slow),
  4420. norm_eps (hparams.f_norm_eps),
  4421. norm_rms_eps (hparams.f_norm_rms_eps),
  4422. n_tokens (batch.n_tokens),
  4423. n_kv (worst_case ? n_ctx : kv_self.n),
  4424. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4425. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4426. pooling_type (cparams.pooling_type),
  4427. rope_type (hparams.rope_type),
  4428. cb (cb),
  4429. buf_compute_meta (lctx.buf_compute_meta) {
  4430. // all initializations should be done in init()
  4431. }
  4432. void init() {
  4433. struct ggml_init_params params = {
  4434. /*.mem_size =*/ buf_compute_meta.size(),
  4435. /*.mem_buffer =*/ buf_compute_meta.data(),
  4436. /*.no_alloc =*/ true,
  4437. };
  4438. ctx0 = ggml_init(params);
  4439. }
  4440. void free() {
  4441. if (ctx0) {
  4442. ggml_free(ctx0);
  4443. ctx0 = nullptr;
  4444. }
  4445. }
  4446. struct ggml_cgraph * build_k_shift() {
  4447. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4448. for (int il = 0; il < n_layer; ++il) {
  4449. struct ggml_tensor * tmp =
  4450. // we rotate only the first n_rot dimensions
  4451. ggml_rope_custom_inplace(ctx0,
  4452. ggml_view_3d(ctx0, kv_self.k_l[il],
  4453. n_embd_head_k, n_head_kv, n_ctx,
  4454. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  4455. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4456. 0),
  4457. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4458. ext_factor, attn_factor, beta_fast, beta_slow);
  4459. cb(tmp, "K_shifted", il);
  4460. ggml_build_forward_expand(gf, tmp);
  4461. }
  4462. return gf;
  4463. }
  4464. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  4465. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4466. for (uint32_t i = 0; i < ids.size(); ++i) {
  4467. const uint32_t id = ids[i];
  4468. if (i == id || id == ids.size()) {
  4469. continue;
  4470. }
  4471. uint32_t nm = 1;
  4472. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  4473. nm++;
  4474. }
  4475. for (int il = 0; il < n_layer; ++il) {
  4476. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  4477. n_embd_k_gqa, nm,
  4478. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4479. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  4480. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  4481. n_embd_k_gqa, nm,
  4482. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4483. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  4484. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  4485. nm, n_embd_v_gqa,
  4486. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4487. ggml_row_size(kv_self.v_l[il]->type, i));
  4488. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  4489. nm, n_embd_v_gqa,
  4490. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4491. ggml_row_size(kv_self.v_l[il]->type, id));
  4492. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  4493. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  4494. }
  4495. i += nm - 1;
  4496. }
  4497. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  4498. return gf;
  4499. }
  4500. struct ggml_cgraph * build_llama() {
  4501. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4502. const int64_t n_embd_head = hparams.n_embd_head_v;
  4503. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4504. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4505. struct ggml_tensor * cur;
  4506. struct ggml_tensor * inpL;
  4507. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4508. cb(inpL, "inp_embd", -1);
  4509. // inp_pos - contains the positions
  4510. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4511. cb(inp_pos, "inp_pos", -1);
  4512. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4513. 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);
  4514. cb(KQ_mask, "KQ_mask", -1);
  4515. for (int il = 0; il < n_layer; ++il) {
  4516. struct ggml_tensor * inpSA = inpL;
  4517. // norm
  4518. cur = llm_build_norm(ctx0, inpL, hparams,
  4519. model.layers[il].attn_norm, NULL,
  4520. LLM_NORM_RMS, cb, il);
  4521. cb(cur, "attn_norm", il);
  4522. // self-attention
  4523. {
  4524. // compute Q and K and RoPE them
  4525. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4526. cb(Qcur, "Qcur", il);
  4527. if (model.layers[il].bq) {
  4528. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4529. cb(Qcur, "Qcur", il);
  4530. }
  4531. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4532. cb(Kcur, "Kcur", il);
  4533. if (model.layers[il].bk) {
  4534. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4535. cb(Kcur, "Kcur", il);
  4536. }
  4537. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4538. cb(Vcur, "Vcur", il);
  4539. if (model.layers[il].bv) {
  4540. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4541. cb(Vcur, "Vcur", il);
  4542. }
  4543. Qcur = ggml_rope_custom(
  4544. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4545. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4546. ext_factor, attn_factor, beta_fast, beta_slow
  4547. );
  4548. cb(Qcur, "Qcur", il);
  4549. Kcur = ggml_rope_custom(
  4550. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4551. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4552. ext_factor, attn_factor, beta_fast, beta_slow
  4553. );
  4554. cb(Kcur, "Kcur", il);
  4555. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4556. model.layers[il].wo, model.layers[il].bo,
  4557. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4558. cb(cur, "kqv_out", il);
  4559. }
  4560. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4561. cb(ffn_inp, "ffn_inp", il);
  4562. // feed-forward network
  4563. if (model.layers[il].ffn_gate_inp == nullptr) {
  4564. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4565. model.layers[il].ffn_norm, NULL,
  4566. LLM_NORM_RMS, cb, il);
  4567. cb(cur, "ffn_norm", il);
  4568. cur = llm_build_ffn(ctx0, cur,
  4569. model.layers[il].ffn_up, NULL,
  4570. model.layers[il].ffn_gate, NULL,
  4571. model.layers[il].ffn_down, NULL,
  4572. NULL,
  4573. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4574. cb(cur, "ffn_out", il);
  4575. } else {
  4576. // MoE branch
  4577. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4578. model.layers[il].ffn_norm, NULL,
  4579. LLM_NORM_RMS, cb, il);
  4580. cb(cur, "ffn_norm", il);
  4581. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4582. cb(logits, "ffn_moe_logits", il);
  4583. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4584. cb(probs, "ffn_moe_probs", il);
  4585. // select experts
  4586. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4587. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4588. ggml_tensor * weights = ggml_get_rows(ctx0,
  4589. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4590. cb(weights, "ffn_moe_weights", il);
  4591. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4592. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4593. cb(weights_sum, "ffn_moe_weights_sum", il);
  4594. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4595. cb(weights, "ffn_moe_weights_norm", il);
  4596. // compute expert outputs
  4597. ggml_tensor * moe_out = nullptr;
  4598. for (int i = 0; i < n_expert_used; ++i) {
  4599. ggml_tensor * cur_expert;
  4600. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4601. cb(cur_up, "ffn_moe_up", il);
  4602. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4603. cb(cur_gate, "ffn_moe_gate", il);
  4604. cur_gate = ggml_silu(ctx0, cur_gate);
  4605. cb(cur_gate, "ffn_moe_silu", il);
  4606. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4607. cb(cur_expert, "ffn_moe_gate_par", il);
  4608. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4609. cb(cur_expert, "ffn_moe_down", il);
  4610. cur_expert = ggml_mul(ctx0, cur_expert,
  4611. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4612. cb(cur_expert, "ffn_moe_weighted", il);
  4613. if (i == 0) {
  4614. moe_out = cur_expert;
  4615. } else {
  4616. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4617. cb(moe_out, "ffn_moe_out", il);
  4618. }
  4619. }
  4620. cur = moe_out;
  4621. }
  4622. cur = ggml_add(ctx0, cur, ffn_inp);
  4623. cb(cur, "l_out", il);
  4624. // input for next layer
  4625. inpL = cur;
  4626. }
  4627. cur = inpL;
  4628. cur = llm_build_norm(ctx0, cur, hparams,
  4629. model.output_norm, NULL,
  4630. LLM_NORM_RMS, cb, -1);
  4631. cb(cur, "result_norm", -1);
  4632. // lm_head
  4633. cur = ggml_mul_mat(ctx0, model.output, cur);
  4634. cb(cur, "result_output", -1);
  4635. ggml_build_forward_expand(gf, cur);
  4636. return gf;
  4637. }
  4638. struct ggml_cgraph * build_baichuan() {
  4639. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4640. const int64_t n_embd_head = hparams.n_embd_head_v;
  4641. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4642. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4643. struct ggml_tensor * cur;
  4644. struct ggml_tensor * inpL;
  4645. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4646. cb(inpL, "inp_embd", -1);
  4647. // inp_pos - contains the positions
  4648. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4649. cb(inp_pos, "inp_pos", -1);
  4650. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4651. 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);
  4652. cb(KQ_mask, "KQ_mask", -1);
  4653. // positions of the tokens in the KV cache
  4654. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4655. cb(KQ_pos, "KQ_pos", -1);
  4656. for (int il = 0; il < n_layer; ++il) {
  4657. struct ggml_tensor * inpSA = inpL;
  4658. cur = llm_build_norm(ctx0, inpL, hparams,
  4659. model.layers[il].attn_norm, NULL,
  4660. LLM_NORM_RMS, cb, il);
  4661. cb(cur, "attn_norm", il);
  4662. // self-attention
  4663. {
  4664. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4665. cb(Qcur, "Qcur", il);
  4666. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4667. cb(Kcur, "Kcur", il);
  4668. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4669. cb(Vcur, "Vcur", il);
  4670. switch (model.type) {
  4671. case MODEL_7B:
  4672. Qcur = ggml_rope_custom(
  4673. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4674. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4675. ext_factor, attn_factor, beta_fast, beta_slow
  4676. );
  4677. Kcur = ggml_rope_custom(
  4678. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4679. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4680. ext_factor, attn_factor, beta_fast, beta_slow
  4681. );
  4682. break;
  4683. case MODEL_13B:
  4684. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4685. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4686. break;
  4687. default:
  4688. GGML_ASSERT(false);
  4689. }
  4690. cb(Qcur, "Qcur", il);
  4691. cb(Kcur, "Kcur", il);
  4692. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4693. model.layers[il].wo, NULL,
  4694. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4695. cb(cur, "kqv_out", il);
  4696. }
  4697. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4698. cb(ffn_inp, "ffn_inp", il);
  4699. // feed-forward network
  4700. {
  4701. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4702. model.layers[il].ffn_norm, NULL,
  4703. LLM_NORM_RMS, cb, il);
  4704. cb(cur, "ffn_norm", il);
  4705. cur = llm_build_ffn(ctx0, cur,
  4706. model.layers[il].ffn_up, NULL,
  4707. model.layers[il].ffn_gate, NULL,
  4708. model.layers[il].ffn_down, NULL,
  4709. NULL,
  4710. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4711. cb(cur, "ffn_out", il);
  4712. }
  4713. cur = ggml_add(ctx0, cur, ffn_inp);
  4714. cb(cur, "l_out", il);
  4715. // input for next layer
  4716. inpL = cur;
  4717. }
  4718. cur = inpL;
  4719. cur = llm_build_norm(ctx0, cur, hparams,
  4720. model.output_norm, NULL,
  4721. LLM_NORM_RMS, cb, -1);
  4722. cb(cur, "result_norm", -1);
  4723. // lm_head
  4724. cur = ggml_mul_mat(ctx0, model.output, cur);
  4725. cb(cur, "result_output", -1);
  4726. ggml_build_forward_expand(gf, cur);
  4727. return gf;
  4728. }
  4729. struct ggml_cgraph * build_falcon() {
  4730. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4731. const int64_t n_embd_head = hparams.n_embd_head_v;
  4732. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4733. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4734. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4735. struct ggml_tensor * cur;
  4736. struct ggml_tensor * inpL;
  4737. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4738. cb(inpL, "inp_embd", -1);
  4739. // inp_pos - contains the positions
  4740. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4741. cb(inp_pos, "inp_pos", -1);
  4742. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4743. 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);
  4744. cb(KQ_mask, "KQ_mask", -1);
  4745. for (int il = 0; il < n_layer; ++il) {
  4746. struct ggml_tensor * attn_norm;
  4747. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4748. model.layers[il].attn_norm,
  4749. model.layers[il].attn_norm_b,
  4750. LLM_NORM, cb, il);
  4751. cb(attn_norm, "attn_norm", il);
  4752. // self-attention
  4753. {
  4754. if (model.layers[il].attn_norm_2) {
  4755. // Falcon-40B
  4756. cur = llm_build_norm(ctx0, inpL, hparams,
  4757. model.layers[il].attn_norm_2,
  4758. model.layers[il].attn_norm_2_b,
  4759. LLM_NORM, cb, il);
  4760. cb(cur, "attn_norm_2", il);
  4761. } else {
  4762. cur = attn_norm;
  4763. }
  4764. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4765. cb(cur, "wqkv", il);
  4766. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4767. 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)));
  4768. 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)));
  4769. cb(Qcur, "Qcur", il);
  4770. cb(Kcur, "Kcur", il);
  4771. cb(Vcur, "Vcur", il);
  4772. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4773. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4774. // using mode = 2 for neox mode
  4775. Qcur = ggml_rope_custom(
  4776. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4777. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4778. );
  4779. cb(Qcur, "Qcur", il);
  4780. Kcur = ggml_rope_custom(
  4781. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4782. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4783. );
  4784. cb(Kcur, "Kcur", il);
  4785. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4786. model.layers[il].wo, NULL,
  4787. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4788. cb(cur, "kqv_out", il);
  4789. }
  4790. struct ggml_tensor * ffn_inp = cur;
  4791. // feed forward
  4792. {
  4793. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4794. model.layers[il].ffn_up, NULL,
  4795. NULL, NULL,
  4796. model.layers[il].ffn_down, NULL,
  4797. NULL,
  4798. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4799. cb(cur, "ffn_out", il);
  4800. }
  4801. cur = ggml_add(ctx0, cur, ffn_inp);
  4802. cb(cur, "l_out", il);
  4803. cur = ggml_add(ctx0, cur, inpL);
  4804. cb(cur, "l_out", il);
  4805. // input for next layer
  4806. inpL = cur;
  4807. }
  4808. cur = inpL;
  4809. // norm
  4810. cur = llm_build_norm(ctx0, cur, hparams,
  4811. model.output_norm,
  4812. model.output_norm_b,
  4813. LLM_NORM, cb, -1);
  4814. cb(cur, "result_norm", -1);
  4815. cur = ggml_mul_mat(ctx0, model.output, cur);
  4816. cb(cur, "result_output", -1);
  4817. ggml_build_forward_expand(gf, cur);
  4818. return gf;
  4819. }
  4820. struct ggml_cgraph * build_starcoder() {
  4821. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4822. const int64_t n_embd_head = hparams.n_embd_head_v;
  4823. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4824. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4825. struct ggml_tensor * cur;
  4826. struct ggml_tensor * pos;
  4827. struct ggml_tensor * inpL;
  4828. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4829. cb(inpL, "inp_embd", -1);
  4830. // inp_pos - contains the positions
  4831. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4832. cb(inp_pos, "inp_pos", -1);
  4833. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4834. 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);
  4835. cb(KQ_mask, "KQ_mask", -1);
  4836. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4837. cb(pos, "pos_embd", -1);
  4838. inpL = ggml_add(ctx0, inpL, pos);
  4839. cb(inpL, "inpL", -1);
  4840. for (int il = 0; il < n_layer; ++il) {
  4841. cur = llm_build_norm(ctx0, inpL, hparams,
  4842. model.layers[il].attn_norm,
  4843. model.layers[il].attn_norm_b,
  4844. LLM_NORM, cb, il);
  4845. cb(cur, "attn_norm", il);
  4846. // self-attention
  4847. {
  4848. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4849. cb(cur, "wqkv", il);
  4850. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4851. cb(cur, "bqkv", il);
  4852. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4853. 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)));
  4854. 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)));
  4855. cb(Qcur, "Qcur", il);
  4856. cb(Kcur, "Kcur", il);
  4857. cb(Vcur, "Vcur", il);
  4858. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4859. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4860. model.layers[il].wo, model.layers[il].bo,
  4861. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4862. cb(cur, "kqv_out", il);
  4863. }
  4864. // add the input
  4865. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4866. cb(ffn_inp, "ffn_inp", il);
  4867. // FF
  4868. {
  4869. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4870. model.layers[il].ffn_norm,
  4871. model.layers[il].ffn_norm_b,
  4872. LLM_NORM, cb, il);
  4873. cb(cur, "ffn_norm", il);
  4874. cur = llm_build_ffn(ctx0, cur,
  4875. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4876. NULL, NULL,
  4877. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4878. NULL,
  4879. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4880. cb(cur, "ffn_out", il);
  4881. }
  4882. inpL = ggml_add(ctx0, cur, ffn_inp);
  4883. cb(inpL, "l_out", il);
  4884. }
  4885. cur = llm_build_norm(ctx0, inpL, hparams,
  4886. model.output_norm,
  4887. model.output_norm_b,
  4888. LLM_NORM, cb, -1);
  4889. cb(cur, "result_norm", -1);
  4890. cur = ggml_mul_mat(ctx0, model.output, cur);
  4891. cb(cur, "result_output", -1);
  4892. ggml_build_forward_expand(gf, cur);
  4893. return gf;
  4894. }
  4895. struct ggml_cgraph * build_persimmon() {
  4896. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4897. const int64_t n_embd_head = hparams.n_embd_head_v;
  4898. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4899. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4900. struct ggml_tensor * cur;
  4901. struct ggml_tensor * inpL;
  4902. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4903. cb(inpL, "inp_embd", -1);
  4904. // inp_pos - contains the positions
  4905. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4906. cb(inp_pos, "inp_pos", -1);
  4907. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4908. 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);
  4909. cb(KQ_mask, "KQ_mask", -1);
  4910. for (int il = 0; il < n_layer; ++il) {
  4911. struct ggml_tensor * residual = inpL;
  4912. cur = llm_build_norm(ctx0, inpL, hparams,
  4913. model.layers[il].attn_norm,
  4914. model.layers[il].attn_norm_b,
  4915. LLM_NORM, cb, il);
  4916. cb(cur, "attn_norm", il);
  4917. // self attention
  4918. {
  4919. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4920. cb(cur, "wqkv", il);
  4921. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4922. cb(cur, "bqkv", il);
  4923. // split qkv
  4924. GGML_ASSERT(n_head_kv == n_head);
  4925. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4926. cb(tmpqkv, "tmpqkv", il);
  4927. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4928. cb(tmpqkv_perm, "tmpqkv", il);
  4929. struct ggml_tensor * tmpq = ggml_view_3d(
  4930. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4931. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4932. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4933. 0
  4934. );
  4935. cb(tmpq, "tmpq", il);
  4936. struct ggml_tensor * tmpk = ggml_view_3d(
  4937. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4938. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4939. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4940. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4941. );
  4942. cb(tmpk, "tmpk", il);
  4943. // Q/K Layernorm
  4944. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4945. model.layers[il].attn_q_norm,
  4946. model.layers[il].attn_q_norm_b,
  4947. LLM_NORM, cb, il);
  4948. cb(tmpq, "tmpq", il);
  4949. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4950. model.layers[il].attn_k_norm,
  4951. model.layers[il].attn_k_norm_b,
  4952. LLM_NORM, cb, il);
  4953. cb(tmpk, "tmpk", il);
  4954. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4955. struct ggml_tensor * qrot = ggml_view_3d(
  4956. ctx0, tmpq, n_rot, n_head, n_tokens,
  4957. ggml_element_size(tmpq) * n_embd_head,
  4958. ggml_element_size(tmpq) * n_embd_head * n_head,
  4959. 0
  4960. );
  4961. cb(qrot, "qrot", il);
  4962. struct ggml_tensor * krot = ggml_view_3d(
  4963. ctx0, tmpk, n_rot, n_head, n_tokens,
  4964. ggml_element_size(tmpk) * n_embd_head,
  4965. ggml_element_size(tmpk) * n_embd_head * n_head,
  4966. 0
  4967. );
  4968. cb(krot, "krot", il);
  4969. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4970. struct ggml_tensor * qpass = ggml_view_3d(
  4971. ctx0, tmpq, n_rot, n_head, n_tokens,
  4972. ggml_element_size(tmpq) * n_embd_head,
  4973. ggml_element_size(tmpq) * n_embd_head * n_head,
  4974. ggml_element_size(tmpq) * n_rot
  4975. );
  4976. cb(qpass, "qpass", il);
  4977. struct ggml_tensor * kpass = ggml_view_3d(
  4978. ctx0, tmpk, n_rot, n_head, n_tokens,
  4979. ggml_element_size(tmpk) * n_embd_head,
  4980. ggml_element_size(tmpk) * n_embd_head * n_head,
  4981. ggml_element_size(tmpk) * n_rot
  4982. );
  4983. cb(kpass, "kpass", il);
  4984. struct ggml_tensor * qrotated = ggml_rope_custom(
  4985. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4986. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4987. );
  4988. cb(qrotated, "qrotated", il);
  4989. struct ggml_tensor * krotated = ggml_rope_custom(
  4990. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4991. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4992. );
  4993. cb(krotated, "krotated", il);
  4994. // ggml currently only supports concatenation on dim=2
  4995. // so we need to permute qrot, qpass, concat, then permute back.
  4996. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4997. cb(qrotated, "qrotated", il);
  4998. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4999. cb(krotated, "krotated", il);
  5000. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  5001. cb(qpass, "qpass", il);
  5002. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  5003. cb(kpass, "kpass", il);
  5004. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  5005. cb(Qcur, "Qcur", il);
  5006. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  5007. cb(Kcur, "Kcur", il);
  5008. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  5009. cb(Q, "Q", il);
  5010. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  5011. cb(Kcur, "Kcur", il);
  5012. struct ggml_tensor * Vcur = ggml_view_3d(
  5013. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5014. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5015. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5016. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  5017. );
  5018. cb(Vcur, "Vcur", il);
  5019. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5020. model.layers[il].wo, model.layers[il].bo,
  5021. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5022. cb(cur, "kqv_out", il);
  5023. }
  5024. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  5025. cb(ffn_inp, "ffn_inp", il);
  5026. // feed-forward network
  5027. {
  5028. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5029. model.layers[il].ffn_norm,
  5030. model.layers[il].ffn_norm_b,
  5031. LLM_NORM, cb, il);
  5032. cb(cur, "ffn_norm", il);
  5033. cur = llm_build_ffn(ctx0, cur,
  5034. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5035. NULL, NULL,
  5036. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5037. NULL,
  5038. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5039. cb(cur, "ffn_out", il);
  5040. }
  5041. cur = ggml_add(ctx0, cur, ffn_inp);
  5042. cb(cur, "l_out", il);
  5043. inpL = cur;
  5044. }
  5045. cur = inpL;
  5046. cur = llm_build_norm(ctx0, cur, hparams,
  5047. model.output_norm,
  5048. model.output_norm_b,
  5049. LLM_NORM, cb, -1);
  5050. cb(cur, "result_norm", -1);
  5051. cur = ggml_mul_mat(ctx0, model.output, cur);
  5052. cb(cur, "result_output", -1);
  5053. ggml_build_forward_expand(gf, cur);
  5054. return gf;
  5055. }
  5056. struct ggml_cgraph * build_refact() {
  5057. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5058. const int64_t n_embd_head = hparams.n_embd_head_v;
  5059. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5060. struct ggml_tensor * cur;
  5061. struct ggml_tensor * inpL;
  5062. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5063. cb(inpL, "inp_embd", -1);
  5064. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5065. 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);
  5066. cb(KQ_mask, "KQ_mask", -1);
  5067. // positions of the tokens in the KV cache
  5068. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5069. cb(KQ_pos, "KQ_pos", -1);
  5070. for (int il = 0; il < n_layer; ++il) {
  5071. struct ggml_tensor * inpSA = inpL;
  5072. cur = llm_build_norm(ctx0, inpL, hparams,
  5073. model.layers[il].attn_norm, NULL,
  5074. LLM_NORM_RMS, cb, il);
  5075. cb(cur, "attn_norm", il);
  5076. // self-attention
  5077. {
  5078. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5079. cb(Qcur, "Qcur", il);
  5080. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5081. cb(Kcur, "Kcur", il);
  5082. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5083. cb(Vcur, "Vcur", il);
  5084. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5085. cb(Kcur, "Kcur", il);
  5086. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5087. cb(Qcur, "Qcur", il);
  5088. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5089. model.layers[il].wo, NULL,
  5090. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5091. cb(cur, "kqv_out", il);
  5092. }
  5093. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5094. cb(ffn_inp, "ffn_inp", il);
  5095. // feed-forward network
  5096. {
  5097. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5098. model.layers[il].ffn_norm, NULL,
  5099. LLM_NORM_RMS, cb, il);
  5100. cb(cur, "ffn_norm", il);
  5101. cur = llm_build_ffn(ctx0, cur,
  5102. model.layers[il].ffn_up, NULL,
  5103. model.layers[il].ffn_gate, NULL,
  5104. model.layers[il].ffn_down, NULL,
  5105. NULL,
  5106. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5107. cb(cur, "ffn_out", il);
  5108. }
  5109. cur = ggml_add(ctx0, cur, ffn_inp);
  5110. cb(cur, "l_out", il);
  5111. // input for next layer
  5112. inpL = cur;
  5113. }
  5114. cur = inpL;
  5115. cur = llm_build_norm(ctx0, cur, hparams,
  5116. model.output_norm, NULL,
  5117. LLM_NORM_RMS, cb, -1);
  5118. cb(cur, "result_norm", -1);
  5119. // lm_head
  5120. cur = ggml_mul_mat(ctx0, model.output, cur);
  5121. cb(cur, "result_output", -1);
  5122. ggml_build_forward_expand(gf, cur);
  5123. return gf;
  5124. }
  5125. struct ggml_cgraph * build_bert() {
  5126. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5127. const int64_t n_embd_head = hparams.n_embd_head_v;
  5128. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5129. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5130. struct ggml_tensor * cur;
  5131. struct ggml_tensor * inpL;
  5132. // get input vectors with right size
  5133. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  5134. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5135. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  5136. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  5137. // construct input embeddings (token, type, position)
  5138. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5139. // token types are hardcoded to zero ("Sentence A")
  5140. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5141. inpL = ggml_add(ctx0, inpL, type_row0);
  5142. if (model.arch == LLM_ARCH_BERT) {
  5143. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5144. }
  5145. cb(inpL, "inp_embd", -1);
  5146. // embed layer norm
  5147. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5148. cb(inpL, "inp_norm", -1);
  5149. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5150. struct ggml_tensor * KQ_mask = ggml_cont(ctx0, ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_tokens, n_tokens, n_tokens*ggml_type_size(lctx.inp_KQ_mask->type), 0));
  5151. cb(KQ_mask, "KQ_mask", -1); // [n_tokens, n_tokens]
  5152. // iterate layers
  5153. for (int il = 0; il < n_layer; ++il) {
  5154. struct ggml_tensor * cur = inpL;
  5155. struct ggml_tensor * Qcur;
  5156. struct ggml_tensor * Kcur;
  5157. struct ggml_tensor * Vcur;
  5158. // self-attention
  5159. if (model.arch == LLM_ARCH_BERT) {
  5160. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5161. cb(Qcur, "Qcur", il);
  5162. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5163. cb(Kcur, "Kcur", il);
  5164. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5165. cb(Vcur, "Vcur", il);
  5166. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5167. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5168. } else {
  5169. // compute Q and K and RoPE them
  5170. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5171. cb(cur, "wqkv", il);
  5172. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5173. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5174. 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)));
  5175. cb(Qcur, "Qcur", il);
  5176. cb(Kcur, "Kcur", il);
  5177. cb(Vcur, "Vcur", il);
  5178. Qcur = ggml_rope_custom(
  5179. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5180. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5181. ext_factor, attn_factor, beta_fast, beta_slow
  5182. );
  5183. cb(Qcur, "Qcur", il);
  5184. Kcur = ggml_rope_custom(
  5185. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5186. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5187. ext_factor, attn_factor, beta_fast, beta_slow
  5188. );
  5189. cb(Kcur, "Kcur", il);
  5190. }
  5191. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5192. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  5193. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5194. cb(kq, "kq", il);
  5195. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  5196. cb(kq, "kq_soft_max_ext", il);
  5197. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  5198. cb(v, "v", il);
  5199. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  5200. cb(kqv, "kqv", il);
  5201. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5202. cb(kqv_merged, "kqv_merged", il);
  5203. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5204. cb(cur, "kqv_merged_cont", il);
  5205. ggml_build_forward_expand(gf, cur);
  5206. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  5207. if (model.layers[il].bo) {
  5208. cb(cur, "kqv_wo", il);
  5209. }
  5210. if (model.layers[il].bo) {
  5211. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  5212. }
  5213. cb(cur, "kqv_out", il);
  5214. // re-add the layer input
  5215. cur = ggml_add(ctx0, cur, inpL);
  5216. // attention layer norm
  5217. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5218. struct ggml_tensor * ffn_inp = cur;
  5219. cb(ffn_inp, "ffn_inp", il);
  5220. // feed-forward network
  5221. if (model.arch == LLM_ARCH_BERT) {
  5222. cur = llm_build_ffn(ctx0, cur,
  5223. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5224. NULL, NULL,
  5225. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5226. NULL,
  5227. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5228. } else {
  5229. cur = llm_build_ffn(ctx0, cur,
  5230. model.layers[il].ffn_up, NULL,
  5231. model.layers[il].ffn_gate, NULL,
  5232. model.layers[il].ffn_down, NULL,
  5233. NULL,
  5234. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5235. }
  5236. cb(cur, "ffn_out", il);
  5237. // attentions bypass the intermediate layer
  5238. cur = ggml_add(ctx0, cur, ffn_inp);
  5239. // output layer norm
  5240. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5241. // input for next layer
  5242. inpL = cur;
  5243. }
  5244. // final output
  5245. cur = inpL;
  5246. cb(cur, "result_embd", -1);
  5247. // pooling layer
  5248. switch (pooling_type) {
  5249. case LLAMA_POOLING_TYPE_NONE:
  5250. {
  5251. // nop
  5252. } break;
  5253. case LLAMA_POOLING_TYPE_MEAN:
  5254. {
  5255. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5256. cb(cur, "result_embd_pooled", -1);
  5257. } break;
  5258. case LLAMA_POOLING_TYPE_CLS:
  5259. {
  5260. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5261. cb(cur, "result_embd_pooled", -1);
  5262. } break;
  5263. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  5264. {
  5265. GGML_ASSERT(false && "Invalid pooling type");
  5266. } break;
  5267. }
  5268. ggml_build_forward_expand(gf, cur);
  5269. return gf;
  5270. }
  5271. struct ggml_cgraph * build_bloom() {
  5272. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5273. const int64_t n_embd_head = hparams.n_embd_head_v;
  5274. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5275. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5276. struct ggml_tensor * cur;
  5277. struct ggml_tensor * inpL;
  5278. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5279. cb(inpL, "inp_embd", -1);
  5280. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5281. 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);
  5282. cb(KQ_mask, "KQ_mask", -1);
  5283. // positions of the tokens in the KV cache
  5284. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5285. cb(KQ_pos, "KQ_pos", -1);
  5286. inpL = llm_build_norm(ctx0, inpL, hparams,
  5287. model.tok_norm,
  5288. model.tok_norm_b,
  5289. LLM_NORM, cb, -1);
  5290. cb(inpL, "inp_norm", -1);
  5291. for (int il = 0; il < n_layer; ++il) {
  5292. cur = llm_build_norm(ctx0, inpL, hparams,
  5293. model.layers[il].attn_norm,
  5294. model.layers[il].attn_norm_b,
  5295. LLM_NORM, cb, il);
  5296. cb(cur, "attn_norm", il);
  5297. // self-attention
  5298. {
  5299. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5300. cb(cur, "wqkv", il);
  5301. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5302. cb(cur, "bqkv", il);
  5303. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5304. 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)));
  5305. 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)));
  5306. cb(Qcur, "Qcur", il);
  5307. cb(Kcur, "Kcur", il);
  5308. cb(Vcur, "Vcur", il);
  5309. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5310. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5311. model.layers[il].wo, model.layers[il].bo,
  5312. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5313. cb(cur, "kqv_out", il);
  5314. }
  5315. // Add the input
  5316. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5317. cb(ffn_inp, "ffn_inp", il);
  5318. // FF
  5319. {
  5320. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5321. model.layers[il].ffn_norm,
  5322. model.layers[il].ffn_norm_b,
  5323. LLM_NORM, cb, il);
  5324. cb(cur, "ffn_norm", il);
  5325. cur = llm_build_ffn(ctx0, cur,
  5326. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5327. NULL, NULL,
  5328. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5329. NULL,
  5330. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5331. cb(cur, "ffn_out", il);
  5332. }
  5333. inpL = ggml_add(ctx0, cur, ffn_inp);
  5334. cb(inpL, "l_out", il);
  5335. }
  5336. cur = llm_build_norm(ctx0, inpL, hparams,
  5337. model.output_norm,
  5338. model.output_norm_b,
  5339. LLM_NORM, cb, -1);
  5340. cb(cur, "result_norm", -1);
  5341. cur = ggml_mul_mat(ctx0, model.output, cur);
  5342. cb(cur, "result_output", -1);
  5343. ggml_build_forward_expand(gf, cur);
  5344. return gf;
  5345. }
  5346. struct ggml_cgraph * build_mpt() {
  5347. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5348. const int64_t n_embd_head = hparams.n_embd_head_v;
  5349. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5350. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5351. struct ggml_tensor * cur;
  5352. struct ggml_tensor * inpL;
  5353. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5354. cb(inpL, "inp_embd", -1);
  5355. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5356. 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);
  5357. cb(KQ_mask, "KQ_mask", -1);
  5358. // positions of the tokens in the KV cache
  5359. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5360. cb(KQ_pos, "KQ_pos", -1);
  5361. for (int il = 0; il < n_layer; ++il) {
  5362. struct ggml_tensor * attn_norm;
  5363. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5364. model.layers[il].attn_norm,
  5365. model.layers[il].attn_norm_b,
  5366. LLM_NORM, cb, il);
  5367. cb(attn_norm, "attn_norm", il);
  5368. // self-attention
  5369. {
  5370. cur = attn_norm;
  5371. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5372. cb(cur, "wqkv", il);
  5373. if (model.layers[il].bqkv){
  5374. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5375. cb(cur, "bqkv", il);
  5376. }
  5377. if (hparams.f_clamp_kqv > 0.0f) {
  5378. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5379. cb(cur, "wqkv_clamped", il);
  5380. }
  5381. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5382. 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)));
  5383. 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)));
  5384. cb(Qcur, "Qcur", il);
  5385. cb(Kcur, "Kcur", il);
  5386. cb(Vcur, "Vcur", il);
  5387. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5388. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5389. model.layers[il].wo, model.layers[il].bo,
  5390. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5391. cb(cur, "kqv_out", il);
  5392. }
  5393. // Add the input
  5394. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5395. cb(ffn_inp, "ffn_inp", il);
  5396. // feed forward
  5397. {
  5398. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5399. model.layers[il].ffn_norm,
  5400. model.layers[il].ffn_norm_b,
  5401. LLM_NORM, cb, il);
  5402. cb(cur, "ffn_norm", il);
  5403. cur = llm_build_ffn(ctx0, cur,
  5404. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5405. NULL, NULL,
  5406. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5407. model.layers[il].ffn_act,
  5408. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5409. cb(cur, "ffn_out", il);
  5410. }
  5411. cur = ggml_add(ctx0, cur, ffn_inp);
  5412. cb(cur, "l_out", il);
  5413. // input for next layer
  5414. inpL = cur;
  5415. }
  5416. cur = inpL;
  5417. cur = llm_build_norm(ctx0, cur, hparams,
  5418. model.output_norm,
  5419. model.output_norm_b,
  5420. LLM_NORM, cb, -1);
  5421. cb(cur, "result_norm", -1);
  5422. cur = ggml_mul_mat(ctx0, model.output, cur);
  5423. cb(cur, "result_output", -1);
  5424. ggml_build_forward_expand(gf, cur);
  5425. return gf;
  5426. }
  5427. struct ggml_cgraph * build_stablelm() {
  5428. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5429. const int64_t n_embd_head = hparams.n_embd_head_v;
  5430. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5431. struct ggml_tensor * cur;
  5432. struct ggml_tensor * inpL;
  5433. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5434. cb(inpL, "inp_embd", -1);
  5435. // inp_pos - contains the positions
  5436. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5437. cb(inp_pos, "inp_pos", -1);
  5438. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5439. 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);
  5440. cb(KQ_mask, "KQ_mask", -1);
  5441. for (int il = 0; il < n_layer; ++il) {
  5442. struct ggml_tensor * inpSA = inpL;
  5443. // norm
  5444. cur = llm_build_norm(ctx0, inpL, hparams,
  5445. model.layers[il].attn_norm,
  5446. model.layers[il].attn_norm_b,
  5447. LLM_NORM, cb, il);
  5448. cb(cur, "attn_norm", il);
  5449. // self-attention
  5450. {
  5451. // compute Q and K and RoPE them
  5452. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5453. cb(Qcur, "Qcur", il);
  5454. if (model.layers[il].bq) {
  5455. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5456. cb(Qcur, "Qcur", il);
  5457. }
  5458. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5459. cb(Kcur, "Kcur", il);
  5460. if (model.layers[il].bk) {
  5461. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5462. cb(Kcur, "Kcur", il);
  5463. }
  5464. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5465. cb(Vcur, "Vcur", il);
  5466. if (model.layers[il].bv) {
  5467. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5468. cb(Vcur, "Vcur", il);
  5469. }
  5470. Qcur = ggml_rope_custom(
  5471. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5472. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5473. ext_factor, attn_factor, beta_fast, beta_slow
  5474. );
  5475. cb(Qcur, "Qcur", il);
  5476. Kcur = ggml_rope_custom(
  5477. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5478. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5479. ext_factor, attn_factor, beta_fast, beta_slow
  5480. );
  5481. cb(Kcur, "Kcur", il);
  5482. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5483. model.layers[il].wo, NULL,
  5484. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5485. cb(cur, "kqv_out", il);
  5486. }
  5487. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5488. cb(ffn_inp, "ffn_inp", il);
  5489. // feed-forward network
  5490. {
  5491. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5492. model.layers[il].ffn_norm,
  5493. model.layers[il].ffn_norm_b,
  5494. LLM_NORM, cb, il);
  5495. cb(cur, "ffn_norm", il);
  5496. cur = llm_build_ffn(ctx0, cur,
  5497. model.layers[il].ffn_up, NULL,
  5498. model.layers[il].ffn_gate, NULL,
  5499. model.layers[il].ffn_down, NULL,
  5500. NULL,
  5501. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5502. cb(cur, "ffn_out", il);
  5503. }
  5504. cur = ggml_add(ctx0, cur, ffn_inp);
  5505. cb(cur, "l_out", il);
  5506. // input for next layer
  5507. inpL = cur;
  5508. }
  5509. cur = inpL;
  5510. cur = llm_build_norm(ctx0, cur, hparams,
  5511. model.output_norm,
  5512. model.output_norm_b,
  5513. LLM_NORM, cb, -1);
  5514. cb(cur, "result_norm", -1);
  5515. // lm_head
  5516. cur = ggml_mul_mat(ctx0, model.output, cur);
  5517. cb(cur, "result_output", -1);
  5518. ggml_build_forward_expand(gf, cur);
  5519. return gf;
  5520. }
  5521. struct ggml_cgraph * build_qwen() {
  5522. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5523. const int64_t n_embd_head = hparams.n_embd_head_v;
  5524. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5525. struct ggml_tensor * cur;
  5526. struct ggml_tensor * inpL;
  5527. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5528. cb(inpL, "inp_embd", -1);
  5529. // inp_pos - contains the positions
  5530. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5531. cb(inp_pos, "inp_pos", -1);
  5532. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5533. 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);
  5534. cb(KQ_mask, "KQ_mask", -1);
  5535. for (int il = 0; il < n_layer; ++il) {
  5536. struct ggml_tensor * inpSA = inpL;
  5537. cur = llm_build_norm(ctx0, inpL, hparams,
  5538. model.layers[il].attn_norm, NULL,
  5539. LLM_NORM_RMS, cb, il);
  5540. cb(cur, "attn_norm", il);
  5541. // self-attention
  5542. {
  5543. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5544. cb(cur, "wqkv", il);
  5545. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5546. cb(cur, "bqkv", il);
  5547. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5548. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5549. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5550. cb(Qcur, "Qcur", il);
  5551. cb(Kcur, "Kcur", il);
  5552. cb(Vcur, "Vcur", il);
  5553. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5554. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5555. // using mode = 2 for neox mode
  5556. Qcur = ggml_rope_custom(
  5557. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5558. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5559. );
  5560. cb(Qcur, "Qcur", il);
  5561. Kcur = ggml_rope_custom(
  5562. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5563. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5564. );
  5565. cb(Kcur, "Kcur", il);
  5566. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5567. model.layers[il].wo, NULL,
  5568. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5569. cb(cur, "kqv_out", il);
  5570. }
  5571. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5572. cb(ffn_inp, "ffn_inp", il);
  5573. // feed-forward forward
  5574. {
  5575. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5576. model.layers[il].ffn_norm, NULL,
  5577. LLM_NORM_RMS, cb, il);
  5578. cb(cur, "ffn_norm", il);
  5579. cur = llm_build_ffn(ctx0, cur,
  5580. model.layers[il].ffn_up, NULL,
  5581. model.layers[il].ffn_gate, NULL,
  5582. model.layers[il].ffn_down, NULL,
  5583. NULL,
  5584. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5585. cb(cur, "ffn_out", il);
  5586. }
  5587. cur = ggml_add(ctx0, cur, ffn_inp);
  5588. cb(cur, "l_out", il);
  5589. // input for next layer
  5590. inpL = cur;
  5591. }
  5592. cur = inpL;
  5593. cur = llm_build_norm(ctx0, cur, hparams,
  5594. model.output_norm, NULL,
  5595. LLM_NORM_RMS, cb, -1);
  5596. cb(cur, "result_norm", -1);
  5597. // lm_head
  5598. cur = ggml_mul_mat(ctx0, model.output, cur);
  5599. cb(cur, "result_output", -1);
  5600. ggml_build_forward_expand(gf, cur);
  5601. return gf;
  5602. }
  5603. struct ggml_cgraph * build_qwen2() {
  5604. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5605. const int64_t n_embd_head = hparams.n_embd_head_v;
  5606. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5607. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5608. struct ggml_tensor * cur;
  5609. struct ggml_tensor * inpL;
  5610. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5611. cb(inpL, "inp_embd", -1);
  5612. // inp_pos - contains the positions
  5613. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5614. cb(inp_pos, "inp_pos", -1);
  5615. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5616. 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);
  5617. cb(KQ_mask, "KQ_mask", -1);
  5618. for (int il = 0; il < n_layer; ++il) {
  5619. struct ggml_tensor * inpSA = inpL;
  5620. // norm
  5621. cur = llm_build_norm(ctx0, inpL, hparams,
  5622. model.layers[il].attn_norm, NULL,
  5623. LLM_NORM_RMS, cb, il);
  5624. cb(cur, "attn_norm", il);
  5625. // self-attention
  5626. {
  5627. // compute Q and K and RoPE them
  5628. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5629. cb(Qcur, "Qcur", il);
  5630. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5631. cb(Qcur, "Qcur", il);
  5632. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5633. cb(Kcur, "Kcur", il);
  5634. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5635. cb(Kcur, "Kcur", il);
  5636. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5637. cb(Vcur, "Vcur", il);
  5638. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5639. cb(Vcur, "Vcur", il);
  5640. // these nodes are added to the graph together so that they are not reordered
  5641. // by doing so, the number of splits in the graph is reduced
  5642. ggml_build_forward_expand(gf, Qcur);
  5643. ggml_build_forward_expand(gf, Kcur);
  5644. ggml_build_forward_expand(gf, Vcur);
  5645. Qcur = ggml_rope_custom(
  5646. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5647. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5648. ext_factor, attn_factor, beta_fast, beta_slow
  5649. );
  5650. cb(Qcur, "Qcur", il);
  5651. Kcur = ggml_rope_custom(
  5652. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5653. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5654. ext_factor, attn_factor, beta_fast, beta_slow
  5655. );
  5656. cb(Kcur, "Kcur", il);
  5657. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5658. model.layers[il].wo, model.layers[il].bo,
  5659. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5660. cb(cur, "kqv_out", il);
  5661. }
  5662. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5663. cb(ffn_inp, "ffn_inp", il);
  5664. // feed-forward network
  5665. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5666. model.layers[il].ffn_norm, NULL,
  5667. LLM_NORM_RMS, cb, il);
  5668. cb(cur, "ffn_norm", il);
  5669. cur = llm_build_ffn(ctx0, cur,
  5670. model.layers[il].ffn_up, NULL,
  5671. model.layers[il].ffn_gate, NULL,
  5672. model.layers[il].ffn_down, NULL,
  5673. NULL,
  5674. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5675. cb(cur, "ffn_out", il);
  5676. cur = ggml_add(ctx0, cur, ffn_inp);
  5677. cb(cur, "l_out", il);
  5678. // input for next layer
  5679. inpL = cur;
  5680. }
  5681. cur = inpL;
  5682. cur = llm_build_norm(ctx0, cur, hparams,
  5683. model.output_norm, NULL,
  5684. LLM_NORM_RMS, cb, -1);
  5685. cb(cur, "result_norm", -1);
  5686. // lm_head
  5687. cur = ggml_mul_mat(ctx0, model.output, cur);
  5688. cb(cur, "result_output", -1);
  5689. ggml_build_forward_expand(gf, cur);
  5690. return gf;
  5691. }
  5692. struct ggml_cgraph * build_phi2() {
  5693. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5694. const int64_t n_embd_head = hparams.n_embd_head_v;
  5695. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5696. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5697. struct ggml_tensor * cur;
  5698. struct ggml_tensor * attn_norm_output;
  5699. struct ggml_tensor * ffn_output;
  5700. struct ggml_tensor * inpL;
  5701. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5702. cb(inpL, "inp_embd", -1);
  5703. // inp_pos - contains the positions
  5704. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5705. cb(inp_pos, "inp_pos", -1);
  5706. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5707. 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);
  5708. cb(KQ_mask, "KQ_mask", -1);
  5709. for (int il = 0; il < n_layer; ++il) {
  5710. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5711. model.layers[il].attn_norm,
  5712. model.layers[il].attn_norm_b,
  5713. LLM_NORM, cb, il);
  5714. cb(attn_norm_output, "attn_norm", il);
  5715. // self-attention
  5716. {
  5717. struct ggml_tensor * Qcur = nullptr;
  5718. struct ggml_tensor * Kcur = nullptr;
  5719. struct ggml_tensor * Vcur = nullptr;
  5720. if (model.layers[il].wqkv) {
  5721. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5722. cb(cur, "wqkv", il);
  5723. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5724. cb(cur, "bqkv", il);
  5725. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5726. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5727. 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)));
  5728. } else {
  5729. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5730. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5731. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5732. }
  5733. cb(Qcur, "Qcur", il);
  5734. cb(Kcur, "Kcur", il);
  5735. cb(Vcur, "Vcur", il);
  5736. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5737. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5738. Qcur = ggml_rope_custom(
  5739. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5740. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5741. );
  5742. cb(Qcur, "Qcur", il);
  5743. // with phi2, we scale the Q to avoid precision issues
  5744. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5745. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5746. cb(Qcur, "Qcur", il);
  5747. Kcur = ggml_rope_custom(
  5748. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5749. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5750. );
  5751. cb(Kcur, "Kcur", il);
  5752. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5753. model.layers[il].wo, model.layers[il].bo,
  5754. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5755. cb(cur, "kqv_out", il);
  5756. }
  5757. // FF
  5758. {
  5759. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5760. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5761. NULL, NULL,
  5762. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5763. NULL,
  5764. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5765. cb(ffn_output, "ffn_out", il);
  5766. }
  5767. cur = ggml_add(ctx0, cur, ffn_output);
  5768. cb(cur, "l_out", il);
  5769. cur = ggml_add(ctx0, cur, inpL);
  5770. cb(cur, "l_out", il);
  5771. inpL = cur;
  5772. }
  5773. cur = llm_build_norm(ctx0, inpL, hparams,
  5774. model.output_norm,
  5775. model.output_norm_b,
  5776. LLM_NORM, cb, -1);
  5777. cb(cur, "result_norm", -1);
  5778. cur = ggml_mul_mat(ctx0, model.output, cur);
  5779. cb(cur, "result_output_no_bias", -1);
  5780. cur = ggml_add(ctx0, cur, model.output_b);
  5781. cb(cur, "result_output", -1);
  5782. ggml_build_forward_expand(gf, cur);
  5783. return gf;
  5784. }
  5785. struct ggml_cgraph * build_plamo() {
  5786. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5787. const int64_t n_embd_head = hparams.n_embd_head_v;
  5788. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5789. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5790. struct ggml_tensor * cur;
  5791. struct ggml_tensor * inpL;
  5792. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5793. cb(inpL, "inp_embd", -1);
  5794. // inp_pos - contains the positions
  5795. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5796. cb(inp_pos, "inp_pos", -1);
  5797. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5798. 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);
  5799. cb(KQ_mask, "KQ_mask", -1);
  5800. for (int il = 0; il < n_layer; ++il) {
  5801. // norm
  5802. cur = llm_build_norm(ctx0, inpL, hparams,
  5803. model.layers[il].attn_norm, NULL,
  5804. LLM_NORM_RMS, cb, il);
  5805. cb(cur, "attn_norm", il);
  5806. struct ggml_tensor * attention_norm = cur;
  5807. // self-attention
  5808. {
  5809. // compute Q and K and RoPE them
  5810. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5811. cb(Qcur, "Qcur", il);
  5812. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5813. cb(Kcur, "Kcur", il);
  5814. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5815. cb(Vcur, "Vcur", il);
  5816. Qcur = ggml_rope_custom(
  5817. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  5818. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5819. ext_factor, attn_factor, beta_fast, beta_slow);
  5820. cb(Qcur, "Qcur", il);
  5821. Kcur = ggml_rope_custom(
  5822. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  5823. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5824. ext_factor, attn_factor, beta_fast, beta_slow);
  5825. cb(Kcur, "Kcur", il);
  5826. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5827. model.layers[il].wo, NULL,
  5828. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5829. cb(cur, "kqv_out", il);
  5830. }
  5831. struct ggml_tensor * sa_out = cur;
  5832. cur = attention_norm;
  5833. // feed-forward network
  5834. {
  5835. cur = llm_build_ffn(ctx0, cur,
  5836. model.layers[il].ffn_up, NULL,
  5837. model.layers[il].ffn_gate, NULL,
  5838. model.layers[il].ffn_down, NULL,
  5839. NULL,
  5840. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5841. cb(cur, "ffn_out", il);
  5842. }
  5843. cur = ggml_add(ctx0, cur, sa_out);
  5844. cb(cur, "l_out", il);
  5845. cur = ggml_add(ctx0, cur, inpL);
  5846. cb(cur, "l_out", il);
  5847. // input for next layer
  5848. inpL = cur;
  5849. }
  5850. cur = inpL;
  5851. cur = llm_build_norm(ctx0, cur, hparams,
  5852. model.output_norm, NULL,
  5853. LLM_NORM_RMS, cb, -1);
  5854. cb(cur, "result_norm", -1);
  5855. // lm_head
  5856. cur = ggml_mul_mat(ctx0, model.output, cur);
  5857. cb(cur, "result_output", -1);
  5858. ggml_build_forward_expand(gf, cur);
  5859. return gf;
  5860. }
  5861. struct ggml_cgraph * build_gpt2() {
  5862. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5863. const int64_t n_embd_head = hparams.n_embd_head_v;
  5864. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5865. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5866. struct ggml_tensor * cur;
  5867. struct ggml_tensor * pos;
  5868. struct ggml_tensor * inpL;
  5869. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5870. cb(inpL, "inp_embd", -1);
  5871. // inp_pos - contains the positions
  5872. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5873. cb(inp_pos, "inp_pos", -1);
  5874. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5875. 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);
  5876. cb(KQ_mask, "KQ_mask", -1);
  5877. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5878. cb(pos, "pos_embd", -1);
  5879. inpL = ggml_add(ctx0, inpL, pos);
  5880. cb(inpL, "inpL", -1);
  5881. for (int il = 0; il < n_layer; ++il) {
  5882. cur = llm_build_norm(ctx0, inpL, hparams,
  5883. model.layers[il].attn_norm,
  5884. model.layers[il].attn_norm_b,
  5885. LLM_NORM, cb, il);
  5886. cb(cur, "attn_norm", il);
  5887. // self-attention
  5888. {
  5889. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5890. cb(cur, "wqkv", il);
  5891. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5892. cb(cur, "bqkv", il);
  5893. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5894. 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)));
  5895. 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)));
  5896. cb(Qcur, "Qcur", il);
  5897. cb(Kcur, "Kcur", il);
  5898. cb(Vcur, "Vcur", il);
  5899. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5900. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5901. model.layers[il].wo, model.layers[il].bo,
  5902. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5903. cb(cur, "kqv_out", il);
  5904. }
  5905. // add the input
  5906. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5907. cb(ffn_inp, "ffn_inp", il);
  5908. // FF
  5909. {
  5910. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5911. model.layers[il].ffn_norm,
  5912. model.layers[il].ffn_norm_b,
  5913. LLM_NORM, cb, il);
  5914. cb(cur, "ffn_norm", il);
  5915. cur = llm_build_ffn(ctx0, cur,
  5916. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5917. NULL, NULL,
  5918. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5919. NULL,
  5920. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5921. cb(cur, "ffn_out", il);
  5922. }
  5923. inpL = ggml_add(ctx0, cur, ffn_inp);
  5924. cb(inpL, "l_out", il);
  5925. }
  5926. cur = llm_build_norm(ctx0, inpL, hparams,
  5927. model.output_norm,
  5928. model.output_norm_b,
  5929. LLM_NORM, cb, -1);
  5930. cb(cur, "result_norm", -1);
  5931. cur = ggml_mul_mat(ctx0, model.output, cur);
  5932. cb(cur, "result_output", -1);
  5933. ggml_build_forward_expand(gf, cur);
  5934. return gf;
  5935. }
  5936. struct ggml_cgraph * build_codeshell() {
  5937. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5938. const int64_t n_embd_head = hparams.n_embd_head_v;
  5939. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5940. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5941. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5942. struct ggml_tensor * cur;
  5943. struct ggml_tensor * inpL;
  5944. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5945. cb(inpL, "inp_embd", -1);
  5946. // inp_pos - contains the positions
  5947. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5948. cb(inp_pos, "inp_pos", -1);
  5949. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5950. 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);
  5951. cb(KQ_mask, "KQ_mask", -1);
  5952. for (int il = 0; il < n_layer; ++il) {
  5953. cur = llm_build_norm(ctx0, inpL, hparams,
  5954. model.layers[il].attn_norm,
  5955. model.layers[il].attn_norm_b,
  5956. LLM_NORM, cb, il);
  5957. cb(cur, "attn_norm", il);
  5958. // self-attention
  5959. {
  5960. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5961. cb(cur, "wqkv", il);
  5962. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5963. cb(cur, "bqkv", il);
  5964. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5965. 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)));
  5966. 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)));
  5967. cb(tmpq, "tmpq", il);
  5968. cb(tmpk, "tmpk", il);
  5969. cb(Vcur, "Vcur", il);
  5970. struct ggml_tensor * Qcur = ggml_rope_custom(
  5971. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5972. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5973. ext_factor, attn_factor, beta_fast, beta_slow
  5974. );
  5975. cb(Qcur, "Qcur", il);
  5976. struct ggml_tensor * Kcur = ggml_rope_custom(
  5977. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5978. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5979. ext_factor, attn_factor, beta_fast, beta_slow
  5980. );
  5981. cb(Kcur, "Kcur", il);
  5982. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5983. model.layers[il].wo, model.layers[il].bo,
  5984. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5985. cb(cur, "kqv_out", il);
  5986. }
  5987. // add the input
  5988. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5989. cb(ffn_inp, "ffn_inp", il);
  5990. // FF
  5991. {
  5992. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5993. model.layers[il].ffn_norm,
  5994. model.layers[il].ffn_norm_b,
  5995. LLM_NORM, cb, il);
  5996. cb(cur, "ffn_norm", il);
  5997. cur = llm_build_ffn(ctx0, cur,
  5998. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5999. NULL, NULL,
  6000. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6001. NULL,
  6002. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6003. cb(cur, "ffn_out", il);
  6004. }
  6005. inpL = ggml_add(ctx0, cur, ffn_inp);
  6006. cb(inpL, "l_out", il);
  6007. }
  6008. cur = llm_build_norm(ctx0, inpL, hparams,
  6009. model.output_norm,
  6010. model.output_norm_b,
  6011. LLM_NORM, cb, -1);
  6012. cb(cur, "result_norm", -1);
  6013. cur = ggml_mul_mat(ctx0, model.output, cur);
  6014. cb(cur, "result_output", -1);
  6015. ggml_build_forward_expand(gf, cur);
  6016. return gf;
  6017. }
  6018. struct ggml_cgraph * build_orion() {
  6019. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6020. const int64_t n_embd_head = hparams.n_embd_head_v;
  6021. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6022. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6023. struct ggml_tensor * cur;
  6024. struct ggml_tensor * inpL;
  6025. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6026. cb(inpL, "inp_embd", -1);
  6027. // inp_pos - contains the positions
  6028. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6029. cb(inp_pos, "inp_pos", -1);
  6030. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6031. 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);
  6032. cb(KQ_mask, "KQ_mask", -1);
  6033. for (int il = 0; il < n_layer; ++il) {
  6034. struct ggml_tensor * inpSA = inpL;
  6035. // norm
  6036. cur = llm_build_norm(ctx0, inpL, hparams,
  6037. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6038. LLM_NORM, cb, il);
  6039. cb(cur, "attn_norm", il);
  6040. // self-attention
  6041. {
  6042. // compute Q and K and RoPE them
  6043. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6044. cb(Qcur, "Qcur", il);
  6045. // if (model.layers[il].bq) {
  6046. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6047. // cb(Qcur, "Qcur", il);
  6048. // }
  6049. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6050. cb(Kcur, "Kcur", il);
  6051. // if (model.layers[il].bk) {
  6052. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6053. // cb(Kcur, "Kcur", il);
  6054. // }
  6055. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6056. cb(Vcur, "Vcur", il);
  6057. // if (model.layers[il].bv) {
  6058. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6059. // cb(Vcur, "Vcur", il);
  6060. // }
  6061. Qcur = ggml_rope_custom(
  6062. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6063. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6064. ext_factor, attn_factor, beta_fast, beta_slow
  6065. );
  6066. cb(Qcur, "Qcur", il);
  6067. Kcur = ggml_rope_custom(
  6068. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6069. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6070. ext_factor, attn_factor, beta_fast, beta_slow
  6071. );
  6072. cb(Kcur, "Kcur", il);
  6073. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6074. model.layers[il].wo, NULL,
  6075. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6076. cb(cur, "kqv_out", il);
  6077. }
  6078. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6079. cb(ffn_inp, "ffn_inp", il);
  6080. // feed-forward network
  6081. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6082. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6083. LLM_NORM, cb, il);
  6084. cb(cur, "ffn_norm", il);
  6085. cur = llm_build_ffn(ctx0, cur,
  6086. model.layers[il].ffn_up, NULL,
  6087. model.layers[il].ffn_gate, NULL,
  6088. model.layers[il].ffn_down, NULL,
  6089. NULL,
  6090. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6091. cb(cur, "ffn_out", il);
  6092. cur = ggml_add(ctx0, cur, ffn_inp);
  6093. cb(cur, "l_out", il);
  6094. // input for next layer
  6095. inpL = cur;
  6096. }
  6097. cur = inpL;
  6098. cur = llm_build_norm(ctx0, cur, hparams,
  6099. model.output_norm, model.output_norm_b,
  6100. LLM_NORM, cb, -1);
  6101. cb(cur, "result_norm", -1);
  6102. // lm_head
  6103. cur = ggml_mul_mat(ctx0, model.output, cur);
  6104. cb(cur, "result_output", -1);
  6105. ggml_build_forward_expand(gf, cur);
  6106. return gf;
  6107. }
  6108. struct ggml_cgraph * build_internlm2() {
  6109. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6110. const int64_t n_embd_head = hparams.n_embd_head_v;
  6111. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6112. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6113. struct ggml_tensor * cur;
  6114. struct ggml_tensor * inpL;
  6115. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6116. cb(inpL, "inp_embd", -1);
  6117. // inp_pos - contains the positions
  6118. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6119. cb(inp_pos, "inp_pos", -1);
  6120. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6121. 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);
  6122. cb(KQ_mask, "KQ_mask", -1);
  6123. for (int il = 0; il < n_layer; ++il) {
  6124. struct ggml_tensor * inpSA = inpL;
  6125. // norm
  6126. cur = llm_build_norm(ctx0, inpL, hparams,
  6127. model.layers[il].attn_norm, NULL,
  6128. LLM_NORM_RMS, cb, il);
  6129. cb(cur, "attn_norm", il);
  6130. // self-attention
  6131. {
  6132. // compute Q and K and RoPE them
  6133. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6134. cb(Qcur, "Qcur", il);
  6135. if (model.layers[il].bq) {
  6136. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6137. cb(Qcur, "Qcur", il);
  6138. }
  6139. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6140. cb(Kcur, "Kcur", il);
  6141. if (model.layers[il].bk) {
  6142. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6143. cb(Kcur, "Kcur", il);
  6144. }
  6145. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6146. cb(Vcur, "Vcur", il);
  6147. if (model.layers[il].bv) {
  6148. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6149. cb(Vcur, "Vcur", il);
  6150. }
  6151. Qcur = ggml_rope_custom(
  6152. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6153. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6154. ext_factor, attn_factor, beta_fast, beta_slow
  6155. );
  6156. cb(Qcur, "Qcur", il);
  6157. Kcur = ggml_rope_custom(
  6158. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6159. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6160. ext_factor, attn_factor, beta_fast, beta_slow
  6161. );
  6162. cb(Kcur, "Kcur", il);
  6163. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6164. model.layers[il].wo, model.layers[il].bo,
  6165. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6166. cb(cur, "kqv_out", il);
  6167. }
  6168. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6169. cb(ffn_inp, "ffn_inp", il);
  6170. // feed-forward network
  6171. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6172. model.layers[il].ffn_norm, NULL,
  6173. LLM_NORM_RMS, cb, il);
  6174. cb(cur, "ffn_norm", il);
  6175. cur = llm_build_ffn(ctx0, cur,
  6176. model.layers[il].ffn_up, NULL,
  6177. model.layers[il].ffn_gate, NULL,
  6178. model.layers[il].ffn_down, NULL,
  6179. NULL,
  6180. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6181. cb(cur, "ffn_out", il);
  6182. cur = ggml_add(ctx0, cur, ffn_inp);
  6183. cb(cur, "l_out", il);
  6184. // input for next layer
  6185. inpL = cur;
  6186. }
  6187. cur = inpL;
  6188. cur = llm_build_norm(ctx0, cur, hparams,
  6189. model.output_norm, NULL,
  6190. LLM_NORM_RMS, cb, -1);
  6191. cb(cur, "result_norm", -1);
  6192. // lm_head
  6193. cur = ggml_mul_mat(ctx0, model.output, cur);
  6194. cb(cur, "result_output", -1);
  6195. ggml_build_forward_expand(gf, cur);
  6196. return gf;
  6197. }
  6198. // ref: https://arxiv.org/abs/2203.03466
  6199. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6200. // based on the original build_llama() function
  6201. struct ggml_cgraph * build_minicpm() {
  6202. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6203. const int64_t n_embd_head = hparams.n_embd_head_v;
  6204. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6205. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6206. const int64_t n_embd = hparams.n_embd;
  6207. //TODO: if the model varies, these parameters need to be read from the model
  6208. const int64_t n_embd_base = 256;
  6209. const float scale_embd = 12.0f;
  6210. const float scale_depth = 1.4f;
  6211. struct ggml_tensor * cur;
  6212. struct ggml_tensor * inpL;
  6213. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6214. cb(inpL, "inp_embd", -1);
  6215. // scale the input embeddings
  6216. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6217. cb(inpL, "inp_scaled", -1);
  6218. // inp_pos - contains the positions
  6219. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6220. cb(inp_pos, "inp_pos", -1);
  6221. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6222. 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);
  6223. cb(KQ_mask, "KQ_mask", -1);
  6224. for (int il = 0; il < n_layer; ++il) {
  6225. struct ggml_tensor * inpSA = inpL;
  6226. // norm
  6227. cur = llm_build_norm(ctx0, inpL, hparams,
  6228. model.layers[il].attn_norm, NULL,
  6229. LLM_NORM_RMS, cb, il);
  6230. cb(cur, "attn_norm", il);
  6231. // self-attention
  6232. {
  6233. // compute Q and K and RoPE them
  6234. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6235. cb(Qcur, "Qcur", il);
  6236. if (model.layers[il].bq) {
  6237. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6238. cb(Qcur, "Qcur", il);
  6239. }
  6240. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6241. cb(Kcur, "Kcur", il);
  6242. if (model.layers[il].bk) {
  6243. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6244. cb(Kcur, "Kcur", il);
  6245. }
  6246. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6247. cb(Vcur, "Vcur", il);
  6248. if (model.layers[il].bv) {
  6249. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6250. cb(Vcur, "Vcur", il);
  6251. }
  6252. Qcur = ggml_rope_custom(
  6253. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6254. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6255. ext_factor, attn_factor, beta_fast, beta_slow
  6256. );
  6257. cb(Qcur, "Qcur", il);
  6258. Kcur = ggml_rope_custom(
  6259. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6260. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6261. ext_factor, attn_factor, beta_fast, beta_slow
  6262. );
  6263. cb(Kcur, "Kcur", il);
  6264. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6265. model.layers[il].wo, model.layers[il].bo,
  6266. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6267. cb(cur, "kqv_out", il);
  6268. }
  6269. // scale_res - scale the hidden states for residual connection
  6270. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6271. cur = ggml_scale(ctx0, cur, scale_res);
  6272. cb(cur, "hidden_scaled", -1);
  6273. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6274. cb(ffn_inp, "ffn_inp", il);
  6275. // feed-forward network
  6276. {
  6277. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6278. model.layers[il].ffn_norm, NULL,
  6279. LLM_NORM_RMS, cb, il);
  6280. cb(cur, "ffn_norm", il);
  6281. cur = llm_build_ffn(ctx0, cur,
  6282. model.layers[il].ffn_up, NULL,
  6283. model.layers[il].ffn_gate, NULL,
  6284. model.layers[il].ffn_down, NULL,
  6285. NULL,
  6286. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6287. cb(cur, "ffn_out", il);
  6288. }
  6289. // scale the hidden states for residual connection
  6290. cur = ggml_scale(ctx0, cur, scale_res);
  6291. cb(cur, "hidden_scaled_ffn", -1);
  6292. cur = ggml_add(ctx0, cur, ffn_inp);
  6293. cb(cur, "l_out", il);
  6294. // input for next layer
  6295. inpL = cur;
  6296. }
  6297. cur = inpL;
  6298. cur = llm_build_norm(ctx0, cur, hparams,
  6299. model.output_norm, NULL,
  6300. LLM_NORM_RMS, cb, -1);
  6301. cb(cur, "result_norm", -1);
  6302. // lm_head scaling
  6303. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6304. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6305. cb(cur, "lmhead_scaling", -1);
  6306. // lm_head
  6307. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6308. cb(cur, "result_output", -1);
  6309. ggml_build_forward_expand(gf, cur);
  6310. return gf;
  6311. }
  6312. struct ggml_cgraph * build_gemma() {
  6313. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6314. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6315. struct ggml_tensor * cur;
  6316. struct ggml_tensor * inpL;
  6317. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6318. cb(inpL, "inp_embd", -1);
  6319. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6320. cb(inpL, "inp_scaled", -1);
  6321. // inp_pos - contains the positions
  6322. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6323. cb(inp_pos, "inp_pos", -1);
  6324. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6325. 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);
  6326. cb(KQ_mask, "KQ_mask", -1);
  6327. for (int il = 0; il < n_layer; ++il) {
  6328. // norm
  6329. cur = llm_build_norm(ctx0, inpL, hparams,
  6330. model.layers[il].attn_norm, NULL,
  6331. LLM_NORM_RMS, cb, il);
  6332. cb(cur, "attn_norm", il);
  6333. // self-attention
  6334. {
  6335. // compute Q and K and RoPE them
  6336. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6337. cb(Qcur, "Qcur", il);
  6338. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6339. cb(Kcur, "Kcur", il);
  6340. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6341. cb(Vcur, "Vcur", il);
  6342. Qcur = ggml_rope_custom(
  6343. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6344. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6345. ext_factor, attn_factor, beta_fast, beta_slow);
  6346. cb(Qcur, "Qcur", il);
  6347. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6348. cb(Qcur, "Qcur_scaled", il);
  6349. Kcur = ggml_rope_custom(
  6350. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6351. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6352. ext_factor, attn_factor, beta_fast, beta_slow);
  6353. cb(Kcur, "Kcur", il);
  6354. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6355. model.layers[il].wo, NULL,
  6356. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6357. cb(cur, "kqv_out", il);
  6358. }
  6359. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6360. cb(sa_out, "sa_out", il);
  6361. cur = llm_build_norm(ctx0, sa_out, hparams,
  6362. model.layers[il].ffn_norm, NULL,
  6363. LLM_NORM_RMS, cb, il);
  6364. cb(cur, "ffn_norm", il);
  6365. // feed-forward network
  6366. {
  6367. cur = llm_build_ffn(ctx0, cur,
  6368. model.layers[il].ffn_up, NULL,
  6369. model.layers[il].ffn_gate, NULL,
  6370. model.layers[il].ffn_down, NULL,
  6371. NULL,
  6372. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6373. cb(cur, "ffn_out", il);
  6374. }
  6375. cur = ggml_add(ctx0, cur, sa_out);
  6376. cb(cur, "l_out", il);
  6377. // input for next layer
  6378. inpL = cur;
  6379. }
  6380. cur = inpL;
  6381. cur = llm_build_norm(ctx0, cur, hparams,
  6382. model.output_norm, NULL,
  6383. LLM_NORM_RMS, cb, -1);
  6384. cb(cur, "result_norm", -1);
  6385. // lm_head
  6386. cur = ggml_mul_mat(ctx0, model.output, cur);
  6387. cb(cur, "result_output", -1);
  6388. ggml_build_forward_expand(gf, cur);
  6389. return gf;
  6390. }
  6391. struct ggml_cgraph * build_starcoder2() {
  6392. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6393. const int64_t n_embd_head = hparams.n_embd_head_v;
  6394. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6395. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6396. struct ggml_tensor * cur;
  6397. struct ggml_tensor * inpL;
  6398. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6399. cb(inpL, "inp_embd", -1);
  6400. // inp_pos - contains the positions
  6401. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6402. cb(inp_pos, "inp_pos", -1);
  6403. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6404. 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);
  6405. cb(KQ_mask, "KQ_mask", -1);
  6406. for (int il = 0; il < n_layer; ++il) {
  6407. struct ggml_tensor * inpSA = inpL;
  6408. // norm
  6409. cur = llm_build_norm(ctx0, inpL, hparams,
  6410. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6411. LLM_NORM, cb, il);
  6412. cb(cur, "attn_norm", il);
  6413. // self-attention
  6414. {
  6415. // compute Q and K and RoPE them
  6416. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6417. cb(Qcur, "Qcur", il);
  6418. if (model.layers[il].bq) {
  6419. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6420. cb(Qcur, "Qcur", il);
  6421. }
  6422. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6423. cb(Kcur, "Kcur", il);
  6424. if (model.layers[il].bk) {
  6425. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6426. cb(Kcur, "Kcur", il);
  6427. }
  6428. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6429. cb(Vcur, "Vcur", il);
  6430. if (model.layers[il].bv) {
  6431. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6432. cb(Vcur, "Vcur", il);
  6433. }
  6434. Qcur = ggml_rope_custom(
  6435. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6436. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6437. ext_factor, attn_factor, beta_fast, beta_slow
  6438. );
  6439. cb(Qcur, "Qcur", il);
  6440. Kcur = ggml_rope_custom(
  6441. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6442. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6443. ext_factor, attn_factor, beta_fast, beta_slow
  6444. );
  6445. cb(Kcur, "Kcur", il);
  6446. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6447. model.layers[il].wo, model.layers[il].bo,
  6448. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6449. cb(cur, "kqv_out", il);
  6450. }
  6451. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6452. cb(ffn_inp, "ffn_inp", il);
  6453. // feed-forward network
  6454. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6455. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6456. LLM_NORM, cb, il);
  6457. cb(cur, "ffn_norm", il);
  6458. cur = llm_build_ffn(ctx0, cur,
  6459. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6460. NULL, NULL,
  6461. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6462. NULL,
  6463. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6464. cb(cur, "ffn_out", il);
  6465. cur = ggml_add(ctx0, cur, ffn_inp);
  6466. cb(cur, "l_out", il);
  6467. // input for next layer
  6468. inpL = cur;
  6469. }
  6470. cur = inpL;
  6471. cur = llm_build_norm(ctx0, cur, hparams,
  6472. model.output_norm, model.output_norm_b,
  6473. LLM_NORM, cb, -1);
  6474. cb(cur, "result_norm", -1);
  6475. // lm_head
  6476. cur = ggml_mul_mat(ctx0, model.output, cur);
  6477. cb(cur, "result_output", -1);
  6478. ggml_build_forward_expand(gf, cur);
  6479. return gf;
  6480. }
  6481. };
  6482. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  6483. llama_batch dummy;
  6484. dummy.n_tokens = 0;
  6485. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6486. struct llm_build_context llm(lctx, dummy, cb, false);
  6487. llm.init();
  6488. struct ggml_cgraph * result = llm.build_defrag(ids);
  6489. llm.free();
  6490. return result;
  6491. }
  6492. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  6493. llama_batch dummy;
  6494. dummy.n_tokens = 0;
  6495. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6496. struct llm_build_context llm(lctx, dummy, cb, false);
  6497. llm.init();
  6498. struct ggml_cgraph * result = llm.build_k_shift();
  6499. llm.free();
  6500. return result;
  6501. }
  6502. static struct ggml_cgraph * llama_build_graph(
  6503. llama_context & lctx,
  6504. const llama_batch & batch,
  6505. bool worst_case) {
  6506. const auto & model = lctx.model;
  6507. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6508. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6509. if (il >= 0) {
  6510. ggml_format_name(cur, "%s-%d", name, il);
  6511. } else {
  6512. ggml_set_name(cur, name);
  6513. }
  6514. if (!lctx.cparams.offload_kqv) {
  6515. if (strcmp(name, "kqv_merged_cont") == 0) {
  6516. // all nodes between the KV store and the attention output are run on the CPU
  6517. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6518. }
  6519. }
  6520. };
  6521. struct ggml_cgraph * result = NULL;
  6522. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6523. llm.init();
  6524. switch (model.arch) {
  6525. case LLM_ARCH_LLAMA:
  6526. {
  6527. result = llm.build_llama();
  6528. } break;
  6529. case LLM_ARCH_BAICHUAN:
  6530. {
  6531. result = llm.build_baichuan();
  6532. } break;
  6533. case LLM_ARCH_FALCON:
  6534. {
  6535. result = llm.build_falcon();
  6536. } break;
  6537. case LLM_ARCH_STARCODER:
  6538. {
  6539. result = llm.build_starcoder();
  6540. } break;
  6541. case LLM_ARCH_PERSIMMON:
  6542. {
  6543. result = llm.build_persimmon();
  6544. } break;
  6545. case LLM_ARCH_REFACT:
  6546. {
  6547. result = llm.build_refact();
  6548. } break;
  6549. case LLM_ARCH_BERT:
  6550. case LLM_ARCH_NOMIC_BERT:
  6551. {
  6552. result = llm.build_bert();
  6553. } break;
  6554. case LLM_ARCH_BLOOM:
  6555. {
  6556. result = llm.build_bloom();
  6557. } break;
  6558. case LLM_ARCH_MPT:
  6559. {
  6560. result = llm.build_mpt();
  6561. } break;
  6562. case LLM_ARCH_STABLELM:
  6563. {
  6564. result = llm.build_stablelm();
  6565. } break;
  6566. case LLM_ARCH_QWEN:
  6567. {
  6568. result = llm.build_qwen();
  6569. } break;
  6570. case LLM_ARCH_QWEN2:
  6571. {
  6572. result = llm.build_qwen2();
  6573. } break;
  6574. case LLM_ARCH_PHI2:
  6575. {
  6576. result = llm.build_phi2();
  6577. } break;
  6578. case LLM_ARCH_PLAMO:
  6579. {
  6580. result = llm.build_plamo();
  6581. } break;
  6582. case LLM_ARCH_GPT2:
  6583. {
  6584. result = llm.build_gpt2();
  6585. } break;
  6586. case LLM_ARCH_CODESHELL:
  6587. {
  6588. result = llm.build_codeshell();
  6589. } break;
  6590. case LLM_ARCH_ORION:
  6591. {
  6592. result = llm.build_orion();
  6593. } break;
  6594. case LLM_ARCH_INTERNLM2:
  6595. {
  6596. result = llm.build_internlm2();
  6597. } break;
  6598. case LLM_ARCH_MINICPM:
  6599. {
  6600. result = llm.build_minicpm();
  6601. } break;
  6602. case LLM_ARCH_GEMMA:
  6603. {
  6604. result = llm.build_gemma();
  6605. } break;
  6606. case LLM_ARCH_STARCODER2:
  6607. {
  6608. result = llm.build_starcoder2();
  6609. } break;
  6610. default:
  6611. GGML_ASSERT(false);
  6612. }
  6613. llm.free();
  6614. return result;
  6615. }
  6616. static void llama_set_k_shift(llama_context & lctx) {
  6617. const auto & cparams = lctx.cparams;
  6618. const int64_t n_ctx = cparams.n_ctx;
  6619. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6620. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6621. for (int i = 0; i < n_ctx; ++i) {
  6622. data[i] = lctx.kv_self.cells[i].delta;
  6623. }
  6624. }
  6625. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6626. //
  6627. // set input data
  6628. //
  6629. const auto & hparams = lctx.model.hparams;
  6630. const auto & cparams = lctx.cparams;
  6631. const auto & kv_self = lctx.kv_self;
  6632. if (batch.token) {
  6633. const int64_t n_tokens = batch.n_tokens;
  6634. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6635. }
  6636. if (batch.embd) {
  6637. const int64_t n_embd = hparams.n_embd;
  6638. const int64_t n_tokens = batch.n_tokens;
  6639. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6640. }
  6641. if (batch.pos) {
  6642. const int64_t n_tokens = batch.n_tokens;
  6643. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6644. }
  6645. if (hparams.causal_attn) {
  6646. const int64_t n_kv = kv_self.n;
  6647. const int64_t n_tokens = batch.n_tokens;
  6648. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6649. float * data = (float *) lctx.inp_KQ_mask->data;
  6650. for (int h = 0; h < 1; ++h) {
  6651. for (int j = 0; j < n_tokens; ++j) {
  6652. const llama_pos pos = batch.pos[j];
  6653. const llama_seq_id seq_id = batch.seq_id[j][0];
  6654. for (int i = 0; i < n_kv; ++i) {
  6655. float f;
  6656. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  6657. f = -INFINITY;
  6658. } else {
  6659. f = 0.0f;
  6660. }
  6661. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6662. }
  6663. }
  6664. }
  6665. } else {
  6666. // non-causal attention attends only the tokens within the batch (i.e. the KV cache is not used)
  6667. const int64_t n_tokens = batch.n_tokens;
  6668. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6669. float * data = (float *) lctx.inp_KQ_mask->data;
  6670. for (int h = 0; h < 1; ++h) {
  6671. for (int j = 0; j < n_tokens; ++j) {
  6672. const llama_seq_id seq_id = batch.seq_id[j][0];
  6673. for (int i = 0; i < n_tokens; ++i) {
  6674. float f = -INFINITY;
  6675. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  6676. if (batch.seq_id[i][s] == seq_id) {
  6677. f = 0.0f;
  6678. break;
  6679. }
  6680. }
  6681. data[h*(n_tokens*n_tokens) + j*n_tokens + i] = f;
  6682. }
  6683. }
  6684. }
  6685. }
  6686. if (hparams.need_kq_pos) {
  6687. const int64_t n_kv = kv_self.n;
  6688. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6689. float * data = (float *) lctx.inp_KQ_pos->data;
  6690. for (int i = 0; i < n_kv; ++i) {
  6691. data[i] = float(lctx.kv_self.cells[i].pos);
  6692. }
  6693. }
  6694. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  6695. const int64_t n_tokens = batch.n_tokens;
  6696. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6697. float * data = (float *) lctx.inp_mean->data;
  6698. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6699. std::vector<uint64_t> sum(n_tokens, 0);
  6700. for (int i = 0; i < n_tokens; ++i) {
  6701. const llama_seq_id seq_id = batch.seq_id[i][0];
  6702. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  6703. sum[seq_id] += 1;
  6704. }
  6705. std::vector<float> div(n_tokens, 0.0f);
  6706. for (int i = 0; i < n_tokens; ++i) {
  6707. const uint64_t s = sum[i];
  6708. if (s > 0) {
  6709. div[i] = 1.0f/float(s);
  6710. }
  6711. }
  6712. for (int i = 0; i < n_tokens; ++i) {
  6713. const llama_seq_id seq_id = batch.seq_id[i][0];
  6714. data[seq_id*n_tokens + i] = div[seq_id];
  6715. }
  6716. }
  6717. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  6718. const int64_t n_tokens = batch.n_tokens;
  6719. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6720. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6721. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  6722. for (int i = 0; i < n_tokens; ++i) {
  6723. const llama_seq_id seq_id = batch.seq_id[i][0];
  6724. const llama_pos pos = batch.pos[i];
  6725. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  6726. if (pos == 0) {
  6727. data[seq_id] = i;
  6728. }
  6729. }
  6730. }
  6731. }
  6732. static void llama_graph_compute(
  6733. llama_context & lctx,
  6734. ggml_cgraph * gf,
  6735. int n_threads) {
  6736. #ifdef GGML_USE_MPI
  6737. const int64_t n_layer = lctx.model.hparams.n_layer;
  6738. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6739. #endif
  6740. #ifdef GGML_USE_METAL
  6741. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6742. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6743. }
  6744. #endif
  6745. if (lctx.backend_cpu != nullptr) {
  6746. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6747. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  6748. }
  6749. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6750. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6751. #ifdef GGML_USE_MPI
  6752. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6753. #endif
  6754. }
  6755. // decode a batch of tokens by evaluating the transformer
  6756. //
  6757. // - lctx: llama context
  6758. // - batch: batch to evaluate
  6759. //
  6760. // return 0 on success
  6761. // return positive int on warning
  6762. // return negative int on error
  6763. //
  6764. static int llama_decode_internal(
  6765. llama_context & lctx,
  6766. llama_batch batch) {
  6767. const uint32_t n_tokens = batch.n_tokens;
  6768. if (n_tokens == 0) {
  6769. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6770. return -1;
  6771. }
  6772. const auto & model = lctx.model;
  6773. const auto & hparams = model.hparams;
  6774. const auto & cparams = lctx.cparams;
  6775. const auto n_batch = cparams.n_batch;
  6776. GGML_ASSERT(n_tokens <= n_batch);
  6777. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6778. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6779. const int64_t t_start_us = ggml_time_us();
  6780. #ifdef GGML_USE_MPI
  6781. // TODO: needs fix after #3228
  6782. GGML_ASSERT(false && "not implemented");
  6783. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6784. #endif
  6785. GGML_ASSERT(n_threads > 0);
  6786. auto & kv_self = lctx.kv_self;
  6787. const int64_t n_embd = hparams.n_embd;
  6788. const int64_t n_vocab = hparams.n_vocab;
  6789. // helpers for smoother batch API transition
  6790. // after deprecating the llama_eval calls, these will be removed
  6791. std::vector<llama_pos> pos;
  6792. std::vector<int32_t> n_seq_id;
  6793. std::vector<llama_seq_id *> seq_id_arr;
  6794. std::vector<std::vector<llama_seq_id>> seq_id;
  6795. if (batch.pos == nullptr) {
  6796. pos.resize(n_tokens);
  6797. for (uint32_t i = 0; i < n_tokens; i++) {
  6798. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6799. }
  6800. batch.pos = pos.data();
  6801. }
  6802. if (batch.seq_id == nullptr) {
  6803. n_seq_id.resize(n_tokens);
  6804. seq_id.resize(n_tokens);
  6805. seq_id_arr.resize(n_tokens);
  6806. for (uint32_t i = 0; i < n_tokens; i++) {
  6807. n_seq_id[i] = 1;
  6808. seq_id[i].resize(1);
  6809. seq_id[i][0] = batch.all_seq_id;
  6810. seq_id_arr[i] = seq_id[i].data();
  6811. }
  6812. batch.n_seq_id = n_seq_id.data();
  6813. batch.seq_id = seq_id_arr.data();
  6814. }
  6815. // non-causal masks do not use the KV cache
  6816. if (hparams.causal_attn) {
  6817. llama_kv_cache_update(&lctx);
  6818. // if we have enough unused cells before the current head ->
  6819. // better to start searching from the beginning of the cache, hoping to fill it
  6820. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6821. kv_self.head = 0;
  6822. }
  6823. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6824. return 1;
  6825. }
  6826. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6827. // after enough generations, the benefit from this heuristic disappears
  6828. // if we start defragmenting the cache, the benefit from this will be more important
  6829. kv_self.n = std::min(cparams.n_ctx, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6830. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6831. }
  6832. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6833. ggml_backend_sched_reset(lctx.sched);
  6834. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6835. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6836. // the output is always the last tensor in the graph
  6837. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6838. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  6839. if (!hparams.causal_attn) {
  6840. res = nullptr; // do not extract logits for embedding models such as BERT
  6841. // token or sequence embeddings
  6842. embd = gf->nodes[gf->n_nodes - 1];
  6843. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  6844. } else {
  6845. if (strcmp(res->name, "result_output") == 0) {
  6846. // the token embeddings could be the second to last tensor, or the third to last tensor
  6847. if (strcmp(embd->name, "result_norm") != 0) {
  6848. embd = gf->nodes[gf->n_nodes - 3];
  6849. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  6850. }
  6851. } else {
  6852. GGML_ASSERT(false && "missing result_output tensor");
  6853. }
  6854. }
  6855. // 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);
  6856. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6857. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6858. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6859. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6860. // with the BLAS calls. need a better solution
  6861. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6862. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6863. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6864. n_threads = std::min(4, n_threads);
  6865. }
  6866. llama_set_inputs(lctx, batch);
  6867. llama_graph_compute(lctx, gf, n_threads);
  6868. // update the kv ring buffer
  6869. {
  6870. kv_self.head += n_tokens;
  6871. // Ensure kv cache head points to a valid index.
  6872. if (kv_self.head >= kv_self.size) {
  6873. kv_self.head = 0;
  6874. }
  6875. }
  6876. // decide if we need to defrag the kv cache
  6877. if (cparams.defrag_thold >= 0.0f) {
  6878. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used + n_tokens)/float(kv_self.n) : 0.0f;
  6879. // queue defragmentation for next llama_kv_cache_update
  6880. if (fragmentation > cparams.defrag_thold) {
  6881. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  6882. llama_kv_cache_defrag(kv_self);
  6883. }
  6884. }
  6885. #ifdef GGML_PERF
  6886. // print timing information per ggml operation (for debugging purposes)
  6887. // requires GGML_PERF to be defined
  6888. ggml_graph_print(gf);
  6889. #endif
  6890. // plot the computation graph in dot format (for debugging purposes)
  6891. //if (n_past%100 == 0) {
  6892. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6893. //}
  6894. // extract logits
  6895. // TODO: do not compute and extract logits if only embeddings are needed
  6896. // need to update the graphs to skip "result_output"
  6897. if (res) {
  6898. auto & logits_out = lctx.logits;
  6899. #ifndef NDEBUG
  6900. auto & logits_valid = lctx.logits_valid;
  6901. logits_valid.clear();
  6902. logits_valid.resize(n_tokens);
  6903. logits_out.clear();
  6904. #endif
  6905. ggml_backend_t backend_res = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6906. GGML_ASSERT(backend_res != nullptr);
  6907. if (batch.logits) {
  6908. logits_out.resize(n_vocab * n_tokens);
  6909. for (uint32_t i = 0; i < n_tokens; i++) {
  6910. if (batch.logits[i] == 0) {
  6911. continue;
  6912. }
  6913. ggml_backend_tensor_get_async(backend_res, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6914. #ifndef NDEBUG
  6915. logits_valid[i] = true;
  6916. #endif
  6917. }
  6918. } else if (lctx.logits_all) {
  6919. logits_out.resize(n_vocab * n_tokens);
  6920. ggml_backend_tensor_get_async(backend_res, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6921. #ifndef NDEBUG
  6922. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6923. #endif
  6924. } else {
  6925. logits_out.resize(n_vocab);
  6926. ggml_backend_tensor_get_async(backend_res, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6927. #ifndef NDEBUG
  6928. logits_valid[0] = true;
  6929. #endif
  6930. }
  6931. ggml_backend_synchronize(backend_res);
  6932. }
  6933. // extract embeddings
  6934. if (cparams.embeddings && embd) {
  6935. ggml_backend_t backend_embd = ggml_backend_sched_get_node_backend(lctx.sched, embd);
  6936. GGML_ASSERT(backend_embd != nullptr);
  6937. switch (cparams.pooling_type) {
  6938. case LLAMA_POOLING_TYPE_NONE:
  6939. {
  6940. // extract token embeddings
  6941. auto & embd_out = lctx.embd;
  6942. if (batch.logits) {
  6943. embd_out.resize(n_embd * n_tokens);
  6944. for (uint32_t i = 0; i < n_tokens; i++) {
  6945. if (batch.logits[i] == 0) {
  6946. continue;
  6947. }
  6948. ggml_backend_tensor_get_async(backend_embd, embd, embd_out.data() + (n_embd*i), (n_embd*i)*sizeof(float), n_embd*sizeof(float));
  6949. }
  6950. }
  6951. } break;
  6952. case LLAMA_POOLING_TYPE_CLS:
  6953. case LLAMA_POOLING_TYPE_MEAN:
  6954. {
  6955. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  6956. // extract sequence embeddings
  6957. auto & embd_seq_out = lctx.embd_seq;
  6958. embd_seq_out.clear();
  6959. for (uint32_t i = 0; i < n_tokens; i++) {
  6960. const llama_seq_id seq_id = batch.seq_id[i][0];
  6961. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  6962. continue;
  6963. }
  6964. embd_seq_out[seq_id].resize(n_embd);
  6965. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  6966. }
  6967. } break;
  6968. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6969. {
  6970. GGML_ASSERT(false && "unknown pooling type");
  6971. } break;
  6972. }
  6973. ggml_backend_synchronize(backend_embd);
  6974. }
  6975. // measure the performance only for the single-token evals
  6976. if (n_tokens == 1) {
  6977. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6978. lctx.n_eval++;
  6979. }
  6980. else if (n_tokens > 1) {
  6981. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6982. lctx.n_p_eval += n_tokens;
  6983. }
  6984. // get a more accurate load time, upon first eval
  6985. // TODO: fix this
  6986. if (!lctx.has_evaluated_once) {
  6987. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6988. lctx.has_evaluated_once = true;
  6989. }
  6990. return 0;
  6991. }
  6992. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  6993. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  6994. auto & kv_self = lctx.kv_self;
  6995. const auto & hparams = lctx.model.hparams;
  6996. const uint32_t n_layer = hparams.n_layer;
  6997. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  6998. const uint32_t n_used = kv_self.used;
  6999. assert(n_used <= n_kv);
  7000. //const int64_t t_start = ggml_time_us();
  7001. // number of cells moved
  7002. uint32_t n_moves = 0;
  7003. // determine which KV cells to move where
  7004. //
  7005. // cell i moves to ids[i]
  7006. //
  7007. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  7008. //
  7009. std::vector<uint32_t> ids(n_kv, n_kv);
  7010. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  7011. const auto & cell0 = kv_self.cells[i0];
  7012. if (!cell0.is_empty()) {
  7013. ids[i0] = i0;
  7014. continue;
  7015. }
  7016. // found a hole - fill it with data from the end of the cache
  7017. uint32_t nh = 1;
  7018. // determine the size of the hole
  7019. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  7020. nh++;
  7021. }
  7022. // each move requires 6*n_layer tensors (see build_defrag)
  7023. // - source view, destination view, copy operation
  7024. // - x2 for keys and values
  7025. //
  7026. if (6*(n_moves + nh)*n_layer >= LLAMA_MAX_NODES) {
  7027. // the graph is too big, we cannot move more cells
  7028. break;
  7029. }
  7030. uint32_t nf = 0;
  7031. uint32_t is = n_kv - 1;
  7032. // starting from the end, find nh non-empty cells
  7033. for (; is > i0; --is) {
  7034. const auto & cell1 = kv_self.cells[is];
  7035. if (cell1.is_empty() || ids[is] != n_kv) {
  7036. continue;
  7037. }
  7038. // non-empty cell which is not yet moved
  7039. nf++;
  7040. if (nf == nh) {
  7041. break;
  7042. }
  7043. }
  7044. // this can only happen if `n_used` is not accurate, which would be a bug
  7045. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  7046. nf = 0;
  7047. uint32_t i1 = is;
  7048. // are we moving a continuous block of memory?
  7049. bool cont = false;
  7050. // go back and move the nf cells to the hole
  7051. for (; i1 < n_kv; ++i1) {
  7052. auto & cell1 = kv_self.cells[i1];
  7053. if (cell1.is_empty() || ids[i1] != n_kv) {
  7054. cont = false;
  7055. continue;
  7056. }
  7057. // this cell goes to (i0 + nf)
  7058. ids[i1] = i0 + nf;
  7059. // move the cell meta data
  7060. kv_self.cells[i0 + nf] = cell1;
  7061. // clear the old cell and move the head there
  7062. cell1 = llama_kv_cell();
  7063. kv_self.head = n_used;
  7064. if (!cont) {
  7065. n_moves++;
  7066. cont = true;
  7067. }
  7068. nf++;
  7069. if (nf == nh) {
  7070. break;
  7071. }
  7072. }
  7073. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  7074. i0 += nh - 1;
  7075. }
  7076. if (n_moves == 0) {
  7077. return;
  7078. }
  7079. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  7080. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  7081. #if 0
  7082. // CPU defrag
  7083. //
  7084. // TODO: optimizations are possible:
  7085. // - multiple threads
  7086. // - avoid copying to the host memory when already there
  7087. //
  7088. // likely not worth the effort, as we have ggml_graph based defrag
  7089. //
  7090. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  7091. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  7092. const uint32_t kv_size = kv_self.size;
  7093. std::vector<uint8_t> buf_k;
  7094. std::vector<uint8_t> buf_v;
  7095. for (uint32_t il = 0; il < n_layer; ++il) {
  7096. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  7097. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  7098. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  7099. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  7100. buf_k.resize(k_size);
  7101. buf_v.resize(v_size);
  7102. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7103. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7104. // batch move [i, i+nm) to [id, id+nm)
  7105. // note: cells can move only to a lower index
  7106. for (uint32_t i = 0; i < n_kv; ++i) {
  7107. const uint32_t id = ids[i];
  7108. if (i == id || id == n_kv) {
  7109. continue;
  7110. }
  7111. uint32_t nm = 1;
  7112. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  7113. nm++;
  7114. }
  7115. // move keys
  7116. {
  7117. const int64_t os = i*k_size_row;
  7118. const int64_t od = id*k_size_row;
  7119. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  7120. }
  7121. // move values (note: they are transposed)
  7122. {
  7123. const int64_t os = i;
  7124. const int64_t od = id;
  7125. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  7126. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  7127. }
  7128. }
  7129. i += nm - 1;
  7130. }
  7131. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7132. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7133. }
  7134. #else
  7135. // ggml_graph defrag
  7136. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  7137. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7138. #endif
  7139. //const int64_t t_end = ggml_time_us();
  7140. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  7141. }
  7142. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  7143. // apply K-shift if needed
  7144. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  7145. llama_set_k_shift(lctx);
  7146. {
  7147. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  7148. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7149. }
  7150. {
  7151. auto & kv_self = lctx.kv_self;
  7152. kv_self.has_shift = false;
  7153. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7154. kv_self.cells[i].delta = 0;
  7155. }
  7156. }
  7157. }
  7158. // defragment the KV cache if needed
  7159. if (lctx.kv_self.do_defrag) {
  7160. llama_kv_cache_defrag_internal(lctx);
  7161. lctx.kv_self.do_defrag = false;
  7162. }
  7163. }
  7164. //
  7165. // tokenizer
  7166. //
  7167. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  7168. return vocab.type;
  7169. }
  7170. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  7171. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  7172. }
  7173. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  7174. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  7175. }
  7176. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  7177. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  7178. }
  7179. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  7180. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  7181. }
  7182. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  7183. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  7184. }
  7185. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  7186. GGML_ASSERT(llama_is_byte_token(vocab, id));
  7187. const auto& token_data = vocab.id_to_token.at(id);
  7188. switch (llama_vocab_get_type(vocab)) {
  7189. case LLAMA_VOCAB_TYPE_SPM: {
  7190. auto buf = token_data.text.substr(3, 2);
  7191. return strtol(buf.c_str(), NULL, 16);
  7192. }
  7193. case LLAMA_VOCAB_TYPE_BPE: {
  7194. GGML_ASSERT(false);
  7195. return unicode_to_bytes_bpe(token_data.text);
  7196. }
  7197. case LLAMA_VOCAB_TYPE_WPM: {
  7198. GGML_ASSERT(false);
  7199. }
  7200. default:
  7201. GGML_ASSERT(false);
  7202. }
  7203. }
  7204. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  7205. static const char * hex = "0123456789ABCDEF";
  7206. switch (llama_vocab_get_type(vocab)) {
  7207. case LLAMA_VOCAB_TYPE_SPM: {
  7208. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  7209. auto token = vocab.token_to_id.find(buf);
  7210. if (token != vocab.token_to_id.end()) {
  7211. return (*token).second;
  7212. }
  7213. // Try to fall back to just the byte as a string
  7214. const char buf2[2] = { (char)ch, 0 };
  7215. return vocab.token_to_id.at(buf2);
  7216. }
  7217. case LLAMA_VOCAB_TYPE_WPM:
  7218. case LLAMA_VOCAB_TYPE_BPE: {
  7219. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  7220. }
  7221. default:
  7222. GGML_ASSERT(false);
  7223. }
  7224. }
  7225. static void llama_escape_whitespace(std::string & text) {
  7226. replace_all(text, " ", "\xe2\x96\x81");
  7227. }
  7228. static void llama_unescape_whitespace(std::string & word) {
  7229. replace_all(word, "\xe2\x96\x81", " ");
  7230. }
  7231. struct llm_symbol {
  7232. using index = int;
  7233. index prev;
  7234. index next;
  7235. const char * text;
  7236. size_t n;
  7237. };
  7238. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  7239. // SPM tokenizer
  7240. // original implementation:
  7241. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  7242. struct llm_bigram_spm {
  7243. struct comparator {
  7244. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  7245. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  7246. }
  7247. };
  7248. using queue_storage = std::vector<llm_bigram_spm>;
  7249. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  7250. llm_symbol::index left;
  7251. llm_symbol::index right;
  7252. float score;
  7253. size_t size;
  7254. };
  7255. struct llm_tokenizer_spm {
  7256. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  7257. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7258. // split string into utf8 chars
  7259. int index = 0;
  7260. size_t offs = 0;
  7261. while (offs < text.size()) {
  7262. llm_symbol sym;
  7263. size_t len = utf8_len(text[offs]);
  7264. sym.text = text.c_str() + offs;
  7265. sym.n = std::min(len, text.size() - offs);
  7266. offs += sym.n;
  7267. sym.prev = index - 1;
  7268. sym.next = offs == text.size() ? -1 : index + 1;
  7269. index++;
  7270. symbols.emplace_back(sym);
  7271. }
  7272. // seed the work queue with all possible 2-character tokens.
  7273. for (size_t i = 1; i < symbols.size(); ++i) {
  7274. try_add_bigram(i - 1, i);
  7275. }
  7276. // keep substituting the highest frequency pairs for as long as we can.
  7277. while (!work_queue.empty()) {
  7278. auto bigram = work_queue.top();
  7279. work_queue.pop();
  7280. auto & left_sym = symbols[bigram.left];
  7281. auto & right_sym = symbols[bigram.right];
  7282. // if one of the symbols already got merged, skip it.
  7283. if (left_sym.n == 0 || right_sym.n == 0 ||
  7284. left_sym.n + right_sym.n != bigram.size) {
  7285. continue;
  7286. }
  7287. // merge the right sym into the left one
  7288. left_sym.n += right_sym.n;
  7289. right_sym.n = 0;
  7290. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  7291. // remove the right sym from the chain
  7292. left_sym.next = right_sym.next;
  7293. if (right_sym.next >= 0) {
  7294. symbols[right_sym.next].prev = bigram.left;
  7295. }
  7296. // find more substitutions
  7297. try_add_bigram(left_sym.prev, bigram.left);
  7298. try_add_bigram(bigram.left, left_sym.next);
  7299. }
  7300. for (int i = 0; i != -1; i = symbols[i].next) {
  7301. auto & symbol = symbols[i];
  7302. resegment(symbol, output);
  7303. }
  7304. }
  7305. private:
  7306. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  7307. auto text = std::string(symbol.text, symbol.n);
  7308. auto token = vocab.token_to_id.find(text);
  7309. // Do we need to support is_unused?
  7310. if (token != vocab.token_to_id.end()) {
  7311. output.push_back((*token).second);
  7312. return;
  7313. }
  7314. const auto p = rev_merge.find(text);
  7315. if (p == rev_merge.end()) {
  7316. // output any symbols that did not form tokens as bytes.
  7317. output.reserve(output.size() + symbol.n);
  7318. for (int j = 0; j < (int)symbol.n; ++j) {
  7319. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  7320. output.push_back(token_id);
  7321. }
  7322. return;
  7323. }
  7324. resegment(symbols[p->second.first], output);
  7325. resegment(symbols[p->second.second], output);
  7326. }
  7327. void try_add_bigram(int left, int right) {
  7328. if (left == -1 || right == -1) {
  7329. return;
  7330. }
  7331. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  7332. auto token = vocab.token_to_id.find(text);
  7333. if (token == vocab.token_to_id.end()) {
  7334. return;
  7335. }
  7336. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  7337. return;
  7338. }
  7339. const auto & tok_data = vocab.id_to_token[(*token).second];
  7340. llm_bigram_spm bigram;
  7341. bigram.left = left;
  7342. bigram.right = right;
  7343. bigram.score = tok_data.score;
  7344. bigram.size = text.size();
  7345. work_queue.push(bigram);
  7346. // Do we need to support is_unused?
  7347. rev_merge[text] = std::make_pair(left, right);
  7348. }
  7349. const llama_vocab & vocab;
  7350. std::vector<llm_symbol> symbols;
  7351. llm_bigram_spm::queue work_queue;
  7352. std::map<std::string, std::pair<int, int>> rev_merge;
  7353. };
  7354. // BPE tokenizer
  7355. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  7356. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  7357. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  7358. struct llm_bigram_bpe {
  7359. struct comparator {
  7360. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  7361. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  7362. }
  7363. };
  7364. using queue_storage = std::vector<llm_bigram_bpe>;
  7365. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  7366. llm_symbol::index left;
  7367. llm_symbol::index right;
  7368. std::string text;
  7369. int rank;
  7370. size_t size;
  7371. };
  7372. struct llm_tokenizer_bpe {
  7373. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  7374. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7375. int final_prev_index = -1;
  7376. auto word_collection = bpe_gpt2_preprocess(text);
  7377. symbols_final.clear();
  7378. for (auto & word : word_collection) {
  7379. work_queue = llm_bigram_bpe::queue();
  7380. symbols.clear();
  7381. int index = 0;
  7382. size_t offset = 0;
  7383. while (offset < word.size()) {
  7384. llm_symbol sym;
  7385. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  7386. sym.text = word.c_str() + offset;
  7387. sym.n = char_len;
  7388. offset += sym.n;
  7389. sym.prev = index - 1;
  7390. sym.next = offset == word.size() ? -1 : index + 1;
  7391. index++;
  7392. symbols.emplace_back(sym);
  7393. }
  7394. for (size_t i = 1; i < symbols.size(); ++i) {
  7395. add_new_bigram(i - 1, i);
  7396. }
  7397. // build token(s)
  7398. while (!work_queue.empty()) {
  7399. auto bigram = work_queue.top();
  7400. work_queue.pop();
  7401. auto & left_symbol = symbols[bigram.left];
  7402. auto & right_symbol = symbols[bigram.right];
  7403. if (left_symbol.n == 0 || right_symbol.n == 0) {
  7404. continue;
  7405. }
  7406. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  7407. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  7408. if (left_token + right_token != bigram.text) {
  7409. continue; // Skip this bigram if it's outdated
  7410. }
  7411. // merge the right sym into the left one
  7412. left_symbol.n += right_symbol.n;
  7413. right_symbol.n = 0;
  7414. // remove the right sym from the chain
  7415. left_symbol.next = right_symbol.next;
  7416. if (right_symbol.next >= 0) {
  7417. symbols[right_symbol.next].prev = bigram.left;
  7418. }
  7419. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  7420. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  7421. }
  7422. // add the fnished tokens to the final list keeping correct order for next and prev
  7423. for (auto & sym : symbols) {
  7424. if (sym.n > 0) {
  7425. sym.prev = final_prev_index;
  7426. sym.next = -1;
  7427. if (final_prev_index != -1) {
  7428. symbols_final[final_prev_index].next = symbols_final.size();
  7429. }
  7430. symbols_final.emplace_back(sym);
  7431. final_prev_index = symbols_final.size() - 1;
  7432. }
  7433. }
  7434. }
  7435. symbols = symbols_final;
  7436. if (!symbols.empty()) {
  7437. for (int i = 0; i != -1; i = symbols[i].next) {
  7438. auto & symbol = symbols[i];
  7439. if (symbol.n == 0) {
  7440. continue;
  7441. }
  7442. const std::string str = std::string(symbol.text, symbol.n);
  7443. const auto token = vocab.token_to_id.find(str);
  7444. if (token == vocab.token_to_id.end()) {
  7445. for (auto j = str.begin(); j != str.end(); ++j) {
  7446. std::string byte_str(1, *j);
  7447. auto token_multibyte = vocab.token_to_id.find(byte_str);
  7448. if (token_multibyte == vocab.token_to_id.end()) {
  7449. throw std::runtime_error("ERROR: byte not found in vocab");
  7450. }
  7451. output.push_back((*token_multibyte).second);
  7452. }
  7453. } else {
  7454. output.push_back((*token).second);
  7455. }
  7456. }
  7457. }
  7458. }
  7459. private:
  7460. void add_new_bigram(int left, int right) {
  7461. if (left == -1 || right == -1) {
  7462. return;
  7463. }
  7464. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  7465. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  7466. int rank_found = -1;
  7467. rank_found = vocab.find_bpe_rank(left_token, right_token);
  7468. if (rank_found < 0) {
  7469. return;
  7470. }
  7471. llm_bigram_bpe bigram;
  7472. bigram.left = left;
  7473. bigram.right = right;
  7474. bigram.text = left_token + right_token;
  7475. bigram.size = left_token.size() + right_token.size();
  7476. bigram.rank = rank_found;
  7477. work_queue.push(bigram);
  7478. }
  7479. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  7480. std::vector<std::string> bpe_words;
  7481. std::vector<std::string> bpe_encoded_words;
  7482. std::string token = "";
  7483. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  7484. bool collecting_numeric = false;
  7485. bool collecting_letter = false;
  7486. bool collecting_special = false;
  7487. bool collecting_whitespace_lookahead = false;
  7488. bool collecting = false;
  7489. std::vector<std::string> text_utf;
  7490. text_utf.reserve(text.size());
  7491. bpe_words.reserve(text.size());
  7492. bpe_encoded_words.reserve(text.size());
  7493. auto cps = codepoints_from_utf8(text);
  7494. for (size_t i = 0; i < cps.size(); ++i)
  7495. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7496. for (int i = 0; i < (int)text_utf.size(); i++) {
  7497. const std::string & utf_char = text_utf[i];
  7498. bool split_condition = false;
  7499. int bytes_remain = text_utf.size() - i;
  7500. // forward backward lookups
  7501. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7502. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7503. // handling contractions
  7504. if (!split_condition && bytes_remain >= 2) {
  7505. // 's|'t|'m|'d
  7506. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7507. split_condition = true;
  7508. }
  7509. if (split_condition) {
  7510. if (token.size()) {
  7511. bpe_words.emplace_back(token); // push previous content as token
  7512. }
  7513. token = utf_char + utf_char_next;
  7514. bpe_words.emplace_back(token);
  7515. token = "";
  7516. i++;
  7517. continue;
  7518. }
  7519. }
  7520. if (!split_condition && bytes_remain >= 3) {
  7521. // 're|'ve|'ll
  7522. if (utf_char == "\'" && (
  7523. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7524. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7525. (utf_char_next == "l" && utf_char_next_next == "l"))
  7526. ) {
  7527. split_condition = true;
  7528. }
  7529. if (split_condition) {
  7530. // current token + next token can be defined
  7531. if (token.size()) {
  7532. bpe_words.emplace_back(token); // push previous content as token
  7533. }
  7534. token = utf_char + utf_char_next + utf_char_next_next;
  7535. bpe_words.emplace_back(token); // the contraction
  7536. token = "";
  7537. i += 2;
  7538. continue;
  7539. }
  7540. }
  7541. if (!split_condition && !collecting) {
  7542. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7543. collecting_letter = true;
  7544. collecting = true;
  7545. }
  7546. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7547. collecting_numeric = true;
  7548. collecting = true;
  7549. }
  7550. else if (
  7551. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7552. (!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)
  7553. ) {
  7554. collecting_special = true;
  7555. collecting = true;
  7556. }
  7557. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7558. collecting_whitespace_lookahead = true;
  7559. collecting = true;
  7560. }
  7561. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7562. split_condition = true;
  7563. }
  7564. }
  7565. else if (!split_condition && collecting) {
  7566. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7567. split_condition = true;
  7568. }
  7569. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7570. split_condition = true;
  7571. }
  7572. 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)) {
  7573. split_condition = true;
  7574. }
  7575. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7576. split_condition = true;
  7577. }
  7578. }
  7579. if (utf_char_next == "") {
  7580. split_condition = true; // final
  7581. token += utf_char;
  7582. }
  7583. if (split_condition) {
  7584. if (token.size()) {
  7585. bpe_words.emplace_back(token);
  7586. }
  7587. token = utf_char;
  7588. collecting = false;
  7589. collecting_letter = false;
  7590. collecting_numeric = false;
  7591. collecting_special = false;
  7592. collecting_whitespace_lookahead = false;
  7593. }
  7594. else {
  7595. token += utf_char;
  7596. }
  7597. }
  7598. for (std::string & word : bpe_words) {
  7599. std::string encoded_token = "";
  7600. for (char & c : word) {
  7601. encoded_token += bytes_to_unicode_bpe(c);
  7602. }
  7603. bpe_encoded_words.emplace_back(encoded_token);
  7604. }
  7605. return bpe_encoded_words;
  7606. }
  7607. const llama_vocab & vocab;
  7608. std::vector<llm_symbol> symbols;
  7609. std::vector<llm_symbol> symbols_final;
  7610. llm_bigram_bpe::queue work_queue;
  7611. };
  7612. struct llm_tokenizer_wpm {
  7613. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7614. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7615. auto * token_map = &vocab.token_to_id;
  7616. // normalize and split by whitespace
  7617. std::vector<std::string> words = preprocess(text);
  7618. // bos token prepended already
  7619. // find the longest tokens that form the words
  7620. for (const std::string &word : words) {
  7621. // skip empty words
  7622. if (word.size() == 0) {
  7623. continue;
  7624. }
  7625. // prepend phantom space
  7626. std::string word1 = "\xe2\x96\x81" + word;
  7627. int n = word1.size();
  7628. // we're at the start of a new word
  7629. int i = 0;
  7630. bool match_any = false;
  7631. // move through character position in word
  7632. while (i < n) {
  7633. // loop through possible match length
  7634. bool match = false;
  7635. for (int j = n; j > i; j--) {
  7636. auto it = token_map->find(word1.substr(i, j - i));
  7637. if (it != token_map->end()) {
  7638. output.push_back(it->second);
  7639. match = true;
  7640. match_any = true;
  7641. i = j;
  7642. break;
  7643. }
  7644. }
  7645. // must be an unknown character
  7646. if (!match) {
  7647. i++;
  7648. }
  7649. }
  7650. // we didn't find any matches for this word
  7651. if (!match_any) {
  7652. output.push_back(vocab.special_unk_id);
  7653. }
  7654. }
  7655. // append eos token
  7656. output.push_back(vocab.special_eos_id);
  7657. }
  7658. std::vector<std::string> preprocess(const std::string & text) {
  7659. // normalalization form D
  7660. std::vector<uint32_t> codepoints = codepoints_from_utf8(text);
  7661. std::vector<uint32_t> nfd_codepoints;
  7662. for (uint32_t code : codepoints) {
  7663. auto it = nfd_map.equal_range(code);
  7664. if (it.first != it.second) {
  7665. for (auto jt = it.first; jt != it.second; jt++) {
  7666. nfd_codepoints.push_back(jt->second);
  7667. }
  7668. } else {
  7669. nfd_codepoints.push_back(code);
  7670. }
  7671. }
  7672. // strip accents, strip control, uniformize whitespace,
  7673. // to lowercase, pad chinese characters, pad punctuation
  7674. std::string new_str = "";
  7675. for (uint32_t code : nfd_codepoints) {
  7676. int type = codepoint_type(code);
  7677. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  7678. continue;
  7679. }
  7680. code = to_lower(code);
  7681. if (type == CODEPOINT_TYPE_WHITESPACE) {
  7682. code = ' ';
  7683. }
  7684. std::string s = codepoint_to_utf8(code);
  7685. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  7686. new_str += " ";
  7687. new_str += s;
  7688. new_str += " ";
  7689. } else {
  7690. new_str += s;
  7691. }
  7692. }
  7693. // split by whitespace
  7694. uint64_t l = 0;
  7695. uint64_t r = 0;
  7696. std::vector<std::string> words;
  7697. while (r < new_str.size()) {
  7698. // if is whitespace
  7699. if (isspace(new_str[r])) {
  7700. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7701. l = r + 1;
  7702. r = l;
  7703. }
  7704. else {
  7705. r += 1;
  7706. }
  7707. }
  7708. if (r > l) {
  7709. words.push_back(new_str.substr(l, (r - l)));
  7710. }
  7711. return words;
  7712. }
  7713. uint32_t to_lower(uint32_t code) {
  7714. static const std::locale locale("en_US.UTF-8");
  7715. #if defined(_WIN32)
  7716. if (code > 0xFFFF) {
  7717. return code;
  7718. }
  7719. #endif
  7720. return std::tolower(wchar_t(code), locale);
  7721. }
  7722. bool is_ascii_punct(uint32_t code) {
  7723. return code < 256 && ispunct(code);
  7724. }
  7725. bool is_chinese_char(uint32_t codepoint) {
  7726. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7727. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7728. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7729. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7730. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7731. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7732. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7733. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7734. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7735. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7736. return true; // NOLINT
  7737. }
  7738. return false;
  7739. }
  7740. const llama_vocab & vocab;
  7741. };
  7742. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7743. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7744. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7745. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7746. struct fragment_buffer_variant {
  7747. fragment_buffer_variant(llama_vocab::id _token)
  7748. :
  7749. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7750. token(_token),
  7751. raw_text(_dummy),
  7752. offset(0),
  7753. length(0) {}
  7754. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7755. :
  7756. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7757. token((llama_vocab::id) - 1),
  7758. raw_text(_raw_text),
  7759. offset(_offset),
  7760. length(_length){
  7761. GGML_ASSERT(_offset >= 0);
  7762. GGML_ASSERT(_length >= 1);
  7763. GGML_ASSERT(offset + length <= raw_text.length());
  7764. }
  7765. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7766. const llama_vocab::id token;
  7767. const std::string _dummy;
  7768. const std::string & raw_text;
  7769. const uint64_t offset;
  7770. const uint64_t length;
  7771. };
  7772. // #define PRETOKENIZERDEBUG
  7773. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7774. // for each special token
  7775. for (const auto & st: vocab.special_tokens_cache) {
  7776. const auto & special_token = st.first;
  7777. const auto & special_id = st.second;
  7778. // for each text fragment
  7779. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7780. while (it != buffer.end()) {
  7781. auto & fragment = (*it);
  7782. // if a fragment is text ( not yet processed )
  7783. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7784. auto * raw_text = &(fragment.raw_text);
  7785. auto raw_text_base_offset = fragment.offset;
  7786. auto raw_text_base_length = fragment.length;
  7787. // loop over the text
  7788. while (true) {
  7789. // find the first occurrence of a given special token in this fragment
  7790. // passing offset argument only limit the "search area" but match coordinates
  7791. // are still relative to the source full raw_text
  7792. auto match = raw_text->find(special_token, raw_text_base_offset);
  7793. // no occurrences found, stop processing this fragment for a given special token
  7794. if (match == std::string::npos) break;
  7795. // check if match is within bounds of offset <-> length
  7796. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7797. #ifdef PRETOKENIZERDEBUG
  7798. 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());
  7799. #endif
  7800. auto source = std::distance(buffer.begin(), it);
  7801. // if match is further than base offset
  7802. // then we have some text to the left of it
  7803. if (match > raw_text_base_offset) {
  7804. // left
  7805. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7806. const int64_t left_reminder_length = match - raw_text_base_offset;
  7807. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7808. #ifdef PRETOKENIZERDEBUG
  7809. 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());
  7810. #endif
  7811. it++;
  7812. }
  7813. // special token
  7814. buffer.emplace_after(it, special_id);
  7815. it++;
  7816. // right
  7817. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7818. const int64_t right_reminder_offset = match + special_token.length();
  7819. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7820. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7821. #ifdef PRETOKENIZERDEBUG
  7822. 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());
  7823. #endif
  7824. it++;
  7825. if (source == 0) {
  7826. buffer.erase_after(buffer.before_begin());
  7827. } else {
  7828. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7829. }
  7830. // repeat for the right side
  7831. raw_text_base_offset = right_reminder_offset;
  7832. raw_text_base_length = right_reminder_length;
  7833. #ifdef PRETOKENIZERDEBUG
  7834. 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());
  7835. #endif
  7836. } else {
  7837. if (source == 0) {
  7838. buffer.erase_after(buffer.before_begin());
  7839. } else {
  7840. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7841. }
  7842. break;
  7843. }
  7844. }
  7845. }
  7846. it++;
  7847. }
  7848. }
  7849. }
  7850. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7851. std::vector<llama_vocab::id> output;
  7852. // OG tokenizer behavior:
  7853. //
  7854. // tokenizer.encode('', add_bos=True) returns [1]
  7855. // tokenizer.encode('', add_bos=False) returns []
  7856. if (bos && vocab.special_bos_id != -1) {
  7857. output.push_back(vocab.special_bos_id);
  7858. }
  7859. if (raw_text.empty()) {
  7860. return output;
  7861. }
  7862. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7863. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7864. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7865. switch (vocab.type) {
  7866. case LLAMA_VOCAB_TYPE_SPM:
  7867. {
  7868. for (const auto & fragment : fragment_buffer) {
  7869. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7870. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7871. // TODO: It's likely possible to get rid of this string copy entirely
  7872. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7873. // and passing 'add space prefix' as bool argument
  7874. //
  7875. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7876. if (&fragment == &fragment_buffer.front()) {
  7877. if (vocab.add_space_prefix) {
  7878. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7879. }
  7880. }
  7881. #ifdef PRETOKENIZERDEBUG
  7882. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7883. #endif
  7884. llm_tokenizer_spm tokenizer(vocab);
  7885. llama_escape_whitespace(raw_text);
  7886. tokenizer.tokenize(raw_text, output);
  7887. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7888. output.push_back(fragment.token);
  7889. }
  7890. }
  7891. } break;
  7892. case LLAMA_VOCAB_TYPE_BPE:
  7893. {
  7894. for (const auto & fragment : fragment_buffer) {
  7895. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7896. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7897. #ifdef PRETOKENIZERDEBUG
  7898. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7899. #endif
  7900. llm_tokenizer_bpe tokenizer(vocab);
  7901. tokenizer.tokenize(raw_text, output);
  7902. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7903. output.push_back(fragment.token);
  7904. }
  7905. }
  7906. } break;
  7907. case LLAMA_VOCAB_TYPE_WPM:
  7908. {
  7909. for (const auto & fragment : fragment_buffer) {
  7910. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7911. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7912. #ifdef PRETOKENIZERDEBUG
  7913. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7914. #endif
  7915. llm_tokenizer_wpm tokenizer(vocab);
  7916. tokenizer.tokenize(raw_text, output);
  7917. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7918. output.push_back(fragment.token);
  7919. }
  7920. }
  7921. } break;
  7922. }
  7923. return output;
  7924. }
  7925. //
  7926. // grammar - internal
  7927. //
  7928. struct llama_partial_utf8 {
  7929. uint32_t value; // bit value so far (unshifted)
  7930. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7931. };
  7932. struct llama_grammar {
  7933. const std::vector<std::vector<llama_grammar_element>> rules;
  7934. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7935. // buffer for partially generated UTF-8 sequence from accepted tokens
  7936. llama_partial_utf8 partial_utf8;
  7937. };
  7938. struct llama_grammar_candidate {
  7939. size_t index;
  7940. const uint32_t * code_points;
  7941. llama_partial_utf8 partial_utf8;
  7942. };
  7943. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7944. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7945. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7946. const std::string & src,
  7947. llama_partial_utf8 partial_start) {
  7948. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7949. const char * pos = src.c_str();
  7950. std::vector<uint32_t> code_points;
  7951. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7952. code_points.reserve(src.size() + 1);
  7953. uint32_t value = partial_start.value;
  7954. int n_remain = partial_start.n_remain;
  7955. // continue previous decode, if applicable
  7956. while (*pos != 0 && n_remain > 0) {
  7957. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7958. if ((next_byte >> 6) != 2) {
  7959. // invalid sequence, abort
  7960. code_points.push_back(0);
  7961. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7962. }
  7963. value = (value << 6) + (next_byte & 0x3F);
  7964. ++pos;
  7965. --n_remain;
  7966. }
  7967. if (partial_start.n_remain > 0 && n_remain == 0) {
  7968. code_points.push_back(value);
  7969. }
  7970. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7971. while (*pos != 0) {
  7972. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7973. uint8_t highbits = first_byte >> 4;
  7974. n_remain = lookup[highbits] - 1;
  7975. if (n_remain < 0) {
  7976. // invalid sequence, abort
  7977. code_points.clear();
  7978. code_points.push_back(0);
  7979. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7980. }
  7981. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7982. value = first_byte & mask;
  7983. ++pos;
  7984. while (*pos != 0 && n_remain > 0) {
  7985. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7986. ++pos;
  7987. --n_remain;
  7988. }
  7989. if (n_remain == 0) {
  7990. code_points.push_back(value);
  7991. }
  7992. }
  7993. code_points.push_back(0);
  7994. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7995. }
  7996. // returns true iff pos points to the end of one of the definitions of a rule
  7997. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7998. switch (pos->type) {
  7999. case LLAMA_GRETYPE_END: return true; // NOLINT
  8000. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  8001. default: return false;
  8002. }
  8003. }
  8004. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  8005. // asserts that pos is pointing to a char range element
  8006. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  8007. const llama_grammar_element * pos,
  8008. const uint32_t chr) {
  8009. bool found = false;
  8010. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8011. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  8012. do {
  8013. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8014. // inclusive range, e.g. [a-z]
  8015. found = found || (pos->value <= chr && chr <= pos[1].value);
  8016. pos += 2;
  8017. } else {
  8018. // exact char match, e.g. [a] or "a"
  8019. found = found || pos->value == chr;
  8020. pos += 1;
  8021. }
  8022. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8023. return std::make_pair(found == is_positive_char, pos);
  8024. }
  8025. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  8026. // range at pos (regular or inverse range)
  8027. // asserts that pos is pointing to a char range element
  8028. static bool llama_grammar_match_partial_char(
  8029. const llama_grammar_element * pos,
  8030. const llama_partial_utf8 partial_utf8) {
  8031. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8032. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  8033. uint32_t partial_value = partial_utf8.value;
  8034. int n_remain = partial_utf8.n_remain;
  8035. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  8036. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  8037. return false;
  8038. }
  8039. // range of possible code points this partial UTF-8 sequence could complete to
  8040. uint32_t low = partial_value << (n_remain * 6);
  8041. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  8042. if (low == 0) {
  8043. if (n_remain == 2) {
  8044. low = 1 << 11;
  8045. } else if (n_remain == 3) {
  8046. low = 1 << 16;
  8047. }
  8048. }
  8049. do {
  8050. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8051. // inclusive range, e.g. [a-z]
  8052. if (pos->value <= high && low <= pos[1].value) {
  8053. return is_positive_char;
  8054. }
  8055. pos += 2;
  8056. } else {
  8057. // exact char match, e.g. [a] or "a"
  8058. if (low <= pos->value && pos->value <= high) {
  8059. return is_positive_char;
  8060. }
  8061. pos += 1;
  8062. }
  8063. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8064. return !is_positive_char;
  8065. }
  8066. // transforms a grammar pushdown stack into N possible stacks, all ending
  8067. // at a character range (terminal element)
  8068. static void llama_grammar_advance_stack(
  8069. const std::vector<std::vector<llama_grammar_element>> & rules,
  8070. const std::vector<const llama_grammar_element *> & stack,
  8071. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  8072. if (stack.empty()) {
  8073. new_stacks.emplace_back(stack);
  8074. return;
  8075. }
  8076. const llama_grammar_element * pos = stack.back();
  8077. switch (pos->type) {
  8078. case LLAMA_GRETYPE_RULE_REF: {
  8079. const size_t rule_id = static_cast<size_t>(pos->value);
  8080. const llama_grammar_element * subpos = rules[rule_id].data();
  8081. do {
  8082. // init new stack without the top (pos)
  8083. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8084. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  8085. // if this rule ref is followed by another element, add that to stack
  8086. new_stack.push_back(pos + 1);
  8087. }
  8088. if (!llama_grammar_is_end_of_sequence(subpos)) {
  8089. // if alternate is nonempty, add to stack
  8090. new_stack.push_back(subpos);
  8091. }
  8092. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8093. while (!llama_grammar_is_end_of_sequence(subpos)) {
  8094. // scan to end of alternate def
  8095. subpos++;
  8096. }
  8097. if (subpos->type == LLAMA_GRETYPE_ALT) {
  8098. // there's another alternate def of this rule to process
  8099. subpos++;
  8100. } else {
  8101. break;
  8102. }
  8103. } while (true);
  8104. break;
  8105. }
  8106. case LLAMA_GRETYPE_CHAR:
  8107. case LLAMA_GRETYPE_CHAR_NOT:
  8108. new_stacks.emplace_back(stack);
  8109. break;
  8110. default:
  8111. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  8112. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  8113. // those
  8114. GGML_ASSERT(false);
  8115. }
  8116. }
  8117. // takes a set of possible pushdown stacks on a grammar, which are required to
  8118. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  8119. // produces the N possible stacks if the given char is accepted at those
  8120. // positions
  8121. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  8122. const std::vector<std::vector<llama_grammar_element>> & rules,
  8123. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8124. const uint32_t chr) {
  8125. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  8126. for (const auto & stack : stacks) {
  8127. if (stack.empty()) {
  8128. continue;
  8129. }
  8130. auto match = llama_grammar_match_char(stack.back(), chr);
  8131. if (match.first) {
  8132. const llama_grammar_element * pos = match.second;
  8133. // update top of stack to next element, if any
  8134. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8135. if (!llama_grammar_is_end_of_sequence(pos)) {
  8136. new_stack.push_back(pos);
  8137. }
  8138. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8139. }
  8140. }
  8141. return new_stacks;
  8142. }
  8143. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8144. const std::vector<std::vector<llama_grammar_element>> & rules,
  8145. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8146. const std::vector<llama_grammar_candidate> & candidates);
  8147. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  8148. const std::vector<std::vector<llama_grammar_element>> & rules,
  8149. const std::vector<const llama_grammar_element *> & stack,
  8150. const std::vector<llama_grammar_candidate> & candidates) {
  8151. std::vector<llama_grammar_candidate> rejects;
  8152. if (stack.empty()) {
  8153. for (const auto & tok : candidates) {
  8154. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  8155. rejects.push_back(tok);
  8156. }
  8157. }
  8158. return rejects;
  8159. }
  8160. const llama_grammar_element * stack_pos = stack.back();
  8161. std::vector<llama_grammar_candidate> next_candidates;
  8162. for (const auto & tok : candidates) {
  8163. if (*tok.code_points == 0) {
  8164. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  8165. // that cannot satisfy this position in grammar
  8166. if (tok.partial_utf8.n_remain != 0 &&
  8167. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  8168. rejects.push_back(tok);
  8169. }
  8170. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  8171. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  8172. } else {
  8173. rejects.push_back(tok);
  8174. }
  8175. }
  8176. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  8177. // update top of stack to next element, if any
  8178. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  8179. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  8180. stack_after.push_back(stack_pos_after);
  8181. }
  8182. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  8183. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  8184. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  8185. for (const auto & tok : next_rejects) {
  8186. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  8187. }
  8188. return rejects;
  8189. }
  8190. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8191. const std::vector<std::vector<llama_grammar_element>> & rules,
  8192. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8193. const std::vector<llama_grammar_candidate> & candidates) {
  8194. GGML_ASSERT(!stacks.empty()); // REVIEW
  8195. if (candidates.empty()) {
  8196. return std::vector<llama_grammar_candidate>();
  8197. }
  8198. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  8199. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  8200. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  8201. }
  8202. return rejects;
  8203. }
  8204. //
  8205. // grammar - external
  8206. //
  8207. struct llama_grammar * llama_grammar_init(
  8208. const llama_grammar_element ** rules,
  8209. size_t n_rules,
  8210. size_t start_rule_index) {
  8211. const llama_grammar_element * pos;
  8212. // copy rule definitions into vectors
  8213. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  8214. for (size_t i = 0; i < n_rules; i++) {
  8215. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  8216. vec_rules[i].push_back(*pos);
  8217. }
  8218. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  8219. }
  8220. // loop over alternates of start rule to build initial stacks
  8221. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8222. pos = rules[start_rule_index];
  8223. do {
  8224. std::vector<const llama_grammar_element *> stack;
  8225. if (!llama_grammar_is_end_of_sequence(pos)) {
  8226. // if alternate is nonempty, add to stack
  8227. stack.push_back(pos);
  8228. }
  8229. llama_grammar_advance_stack(vec_rules, stack, stacks);
  8230. while (!llama_grammar_is_end_of_sequence(pos)) {
  8231. // scan to end of alternate def
  8232. pos++;
  8233. }
  8234. if (pos->type == LLAMA_GRETYPE_ALT) {
  8235. // there's another alternate def of this rule to process
  8236. pos++;
  8237. } else {
  8238. break;
  8239. }
  8240. } while (true);
  8241. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  8242. }
  8243. void llama_grammar_free(struct llama_grammar * grammar) {
  8244. delete grammar;
  8245. }
  8246. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  8247. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  8248. // redirect elements in stacks to point to new rules
  8249. for (size_t is = 0; is < result->stacks.size(); is++) {
  8250. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  8251. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  8252. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  8253. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  8254. result->stacks[is][ie] = &result->rules[ir0][ir1];
  8255. }
  8256. }
  8257. }
  8258. }
  8259. }
  8260. return result;
  8261. }
  8262. //
  8263. // sampling
  8264. //
  8265. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  8266. if (seed == LLAMA_DEFAULT_SEED) {
  8267. seed = time(NULL);
  8268. }
  8269. ctx->rng.seed(seed);
  8270. }
  8271. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  8272. GGML_ASSERT(candidates->size > 0);
  8273. const int64_t t_start_sample_us = ggml_time_us();
  8274. // Sort the logits in descending order
  8275. if (!candidates->sorted) {
  8276. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8277. return a.logit > b.logit;
  8278. });
  8279. candidates->sorted = true;
  8280. }
  8281. float max_l = candidates->data[0].logit;
  8282. float cum_sum = 0.0f;
  8283. for (size_t i = 0; i < candidates->size; ++i) {
  8284. float p = expf(candidates->data[i].logit - max_l);
  8285. candidates->data[i].p = p;
  8286. cum_sum += p;
  8287. }
  8288. for (size_t i = 0; i < candidates->size; ++i) {
  8289. candidates->data[i].p /= cum_sum;
  8290. }
  8291. if (ctx) {
  8292. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8293. }
  8294. }
  8295. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  8296. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  8297. // if (k >= (int32_t)candidates->size) {
  8298. // return;
  8299. // }
  8300. const int64_t t_start_sample_us = ggml_time_us();
  8301. if (k <= 0) {
  8302. k = candidates->size;
  8303. }
  8304. k = std::max(k, (int) min_keep);
  8305. k = std::min(k, (int) candidates->size);
  8306. // Sort scores in descending order
  8307. if (!candidates->sorted) {
  8308. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  8309. return a.logit > b.logit;
  8310. };
  8311. if (k <= 128) {
  8312. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  8313. } else {
  8314. constexpr int nbuckets = 128;
  8315. constexpr float bucket_low = -10.0f;
  8316. constexpr float bucket_high = 10.0f;
  8317. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  8318. constexpr float bucker_inter = -bucket_low * bucket_scale;
  8319. std::vector<int> bucket_idx(candidates->size);
  8320. std::vector<int> histo(nbuckets, 0);
  8321. for (int i = 0; i < (int)candidates->size; ++i) {
  8322. const float val = candidates->data[i].logit;
  8323. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  8324. ib = std::max(0, std::min(nbuckets-1, ib));
  8325. bucket_idx[i] = ib;
  8326. ++histo[ib];
  8327. }
  8328. int nhave = 0;
  8329. int ib = nbuckets - 1;
  8330. for ( ; ib >= 0; --ib) {
  8331. nhave += histo[ib];
  8332. if (nhave >= k) break;
  8333. }
  8334. std::vector<llama_token_data> tmp_tokens(nhave);
  8335. auto ptr = tmp_tokens.data();
  8336. std::vector<llama_token_data*> bucket_ptrs;
  8337. bucket_ptrs.reserve(nbuckets - ib);
  8338. for (int j = nbuckets - 1; j >= ib; --j) {
  8339. bucket_ptrs.push_back(ptr);
  8340. ptr += histo[j];
  8341. }
  8342. for (int i = 0; i < (int)candidates->size; ++i) {
  8343. int j = bucket_idx[i];
  8344. if (j >= ib) {
  8345. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  8346. }
  8347. }
  8348. ptr = tmp_tokens.data();
  8349. int ndone = 0;
  8350. for (int j = nbuckets-1; j > ib; --j) {
  8351. std::sort(ptr, ptr + histo[j], comp);
  8352. ptr += histo[j];
  8353. ndone += histo[j];
  8354. }
  8355. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  8356. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  8357. }
  8358. candidates->sorted = true;
  8359. }
  8360. candidates->size = k;
  8361. if (ctx) {
  8362. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8363. }
  8364. }
  8365. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8366. if (p >= 1.0f) {
  8367. return;
  8368. }
  8369. llama_sample_softmax(ctx, candidates);
  8370. const int64_t t_start_sample_us = ggml_time_us();
  8371. // Compute the cumulative probabilities
  8372. float cum_sum = 0.0f;
  8373. size_t last_idx = candidates->size;
  8374. for (size_t i = 0; i < candidates->size; ++i) {
  8375. cum_sum += candidates->data[i].p;
  8376. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  8377. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  8378. if (cum_sum >= p && i + 1 >= min_keep) {
  8379. last_idx = i + 1;
  8380. break;
  8381. }
  8382. }
  8383. // Resize the output vector to keep only the top-p tokens
  8384. candidates->size = last_idx;
  8385. if (ctx) {
  8386. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8387. }
  8388. }
  8389. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8390. if (p <= 0.0f || !candidates->size) {
  8391. return;
  8392. }
  8393. const int64_t t_start_sample_us = ggml_time_us();
  8394. bool min_p_applied = false;
  8395. // if the candidates aren't sorted, try the unsorted implementation first
  8396. if (!candidates->sorted) {
  8397. std::vector<llama_token_data> filtered_tokens;
  8398. float max_logit = -FLT_MAX;
  8399. for (size_t i = 0; i < candidates->size; ++i) {
  8400. max_logit = std::max(max_logit, candidates->data[i].logit);
  8401. }
  8402. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  8403. for (size_t i = 0; i < candidates->size; ++i) {
  8404. if (candidates->data[i].logit >= min_logit) {
  8405. filtered_tokens.push_back(candidates->data[i]);
  8406. }
  8407. }
  8408. // if we have enough values the operation was a success
  8409. if (filtered_tokens.size() >= min_keep) {
  8410. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  8411. candidates->size = filtered_tokens.size();
  8412. min_p_applied = true;
  8413. }
  8414. }
  8415. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  8416. if (!min_p_applied) {
  8417. // Sort the logits in descending order
  8418. if (!candidates->sorted) {
  8419. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8420. return a.logit > b.logit;
  8421. });
  8422. candidates->sorted = true;
  8423. }
  8424. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  8425. size_t i = 1; // first token always matches
  8426. for (; i < candidates->size; ++i) {
  8427. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  8428. break; // prob too small
  8429. }
  8430. }
  8431. // Resize the output vector to keep only the matching tokens
  8432. candidates->size = i;
  8433. }
  8434. if (ctx) {
  8435. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8436. }
  8437. }
  8438. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8439. if (z >= 1.0f || candidates->size <= 2) {
  8440. return;
  8441. }
  8442. llama_sample_softmax(nullptr, candidates);
  8443. const int64_t t_start_sample_us = ggml_time_us();
  8444. // Compute the first and second derivatives
  8445. std::vector<float> first_derivatives(candidates->size - 1);
  8446. std::vector<float> second_derivatives(candidates->size - 2);
  8447. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8448. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8449. }
  8450. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8451. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8452. }
  8453. // Calculate absolute value of second derivatives
  8454. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8455. second_derivatives[i] = std::abs(second_derivatives[i]);
  8456. }
  8457. // Normalize the second derivatives
  8458. {
  8459. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8460. if (second_derivatives_sum > 1e-6f) {
  8461. for (float & value : second_derivatives) {
  8462. value /= second_derivatives_sum;
  8463. }
  8464. } else {
  8465. for (float & value : second_derivatives) {
  8466. value = 1.0f / second_derivatives.size();
  8467. }
  8468. }
  8469. }
  8470. float cum_sum = 0.0f;
  8471. size_t last_idx = candidates->size;
  8472. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8473. cum_sum += second_derivatives[i];
  8474. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8475. if (cum_sum > z && i >= min_keep) {
  8476. last_idx = i;
  8477. break;
  8478. }
  8479. }
  8480. // Resize the output vector to keep only the tokens above the tail location
  8481. candidates->size = last_idx;
  8482. if (ctx) {
  8483. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8484. }
  8485. }
  8486. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8487. // Reference implementation:
  8488. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8489. if (p >= 1.0f) {
  8490. return;
  8491. }
  8492. // Compute the softmax of logits and calculate entropy
  8493. llama_sample_softmax(nullptr, candidates);
  8494. const int64_t t_start_sample_us = ggml_time_us();
  8495. float entropy = 0.0f;
  8496. for (size_t i = 0; i < candidates->size; ++i) {
  8497. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8498. }
  8499. // Compute the absolute difference between negative log probability and entropy for each candidate
  8500. std::vector<float> shifted_scores;
  8501. for (size_t i = 0; i < candidates->size; ++i) {
  8502. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8503. shifted_scores.push_back(shifted_score);
  8504. }
  8505. // Sort tokens based on the shifted_scores and their corresponding indices
  8506. std::vector<size_t> indices(candidates->size);
  8507. std::iota(indices.begin(), indices.end(), 0);
  8508. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8509. return shifted_scores[a] < shifted_scores[b];
  8510. });
  8511. // Compute the cumulative probabilities
  8512. float cum_sum = 0.0f;
  8513. size_t last_idx = indices.size();
  8514. for (size_t i = 0; i < indices.size(); ++i) {
  8515. size_t idx = indices[i];
  8516. cum_sum += candidates->data[idx].p;
  8517. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8518. if (cum_sum > p && i >= min_keep - 1) {
  8519. last_idx = i + 1;
  8520. break;
  8521. }
  8522. }
  8523. // Resize the output vector to keep only the locally typical tokens
  8524. std::vector<llama_token_data> new_candidates;
  8525. for (size_t i = 0; i < last_idx; ++i) {
  8526. size_t idx = indices[i];
  8527. new_candidates.push_back(candidates->data[idx]);
  8528. }
  8529. // Replace the data in candidates with the new_candidates data
  8530. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8531. candidates->size = new_candidates.size();
  8532. candidates->sorted = false;
  8533. if (ctx) {
  8534. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8535. }
  8536. }
  8537. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8538. const int64_t t_start_sample_us = ggml_time_us();
  8539. // no need to do anything if there is only one (or zero) candidates
  8540. if(candidates_p->size <= 1) {
  8541. return;
  8542. }
  8543. // Calculate maximum possible entropy
  8544. float max_entropy = -logf(1.0f / candidates_p->size);
  8545. llama_sample_softmax(nullptr, candidates_p);
  8546. // Calculate entropy of the softmax probabilities
  8547. float entropy = 0.0f;
  8548. for (size_t i = 0; i < candidates_p->size; ++i) {
  8549. float prob = candidates_p->data[i].p;
  8550. if (prob > 0.0f) { // Ensure no log(0)
  8551. entropy -= prob * logf(prob);
  8552. }
  8553. }
  8554. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8555. float normalized_entropy = entropy / max_entropy;
  8556. // Map the normalized entropy to the desired temperature range using the power function
  8557. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8558. #ifdef DEBUG
  8559. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8560. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8561. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8562. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8563. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8564. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8565. #endif
  8566. // Apply the dynamically calculated temperature scaling
  8567. for (size_t i = 0; i < candidates_p->size; ++i) {
  8568. candidates_p->data[i].logit /= dyn_temp;
  8569. }
  8570. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8571. double max_l_double = candidates_p->data[0].logit;
  8572. double cum_sum_double = 0.0;
  8573. for (size_t i = 0; i < candidates_p->size; ++i) {
  8574. double p = exp(candidates_p->data[i].logit - max_l_double);
  8575. candidates_p->data[i].p = p; // Store the scaled probability
  8576. cum_sum_double += p;
  8577. }
  8578. for (size_t i = 0; i < candidates_p->size; ++i) {
  8579. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8580. }
  8581. #ifdef DEBUG
  8582. // Print the updated top 25 probabilities after temperature scaling
  8583. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8584. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8585. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8586. }
  8587. #endif
  8588. if (ctx) {
  8589. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8590. }
  8591. }
  8592. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8593. const int64_t t_start_sample_us = ggml_time_us();
  8594. for (size_t i = 0; i < candidates_p->size; ++i) {
  8595. candidates_p->data[i].logit /= temp;
  8596. }
  8597. if (ctx) {
  8598. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8599. }
  8600. }
  8601. void llama_sample_repetition_penalties(
  8602. struct llama_context * ctx,
  8603. llama_token_data_array * candidates,
  8604. const llama_token * last_tokens,
  8605. size_t penalty_last_n,
  8606. float penalty_repeat,
  8607. float penalty_freq,
  8608. float penalty_present) {
  8609. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8610. return;
  8611. }
  8612. const int64_t t_start_sample_us = ggml_time_us();
  8613. // Create a frequency map to count occurrences of each token in last_tokens
  8614. std::unordered_map<llama_token, int> token_count;
  8615. for (size_t i = 0; i < penalty_last_n; ++i) {
  8616. token_count[last_tokens[i]]++;
  8617. }
  8618. // Apply frequency and presence penalties to the candidates
  8619. for (size_t i = 0; i < candidates->size; ++i) {
  8620. const auto token_iter = token_count.find(candidates->data[i].id);
  8621. if (token_iter == token_count.end()) {
  8622. continue;
  8623. }
  8624. const int count = token_iter->second;
  8625. // 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.
  8626. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8627. if (candidates->data[i].logit <= 0) {
  8628. candidates->data[i].logit *= penalty_repeat;
  8629. } else {
  8630. candidates->data[i].logit /= penalty_repeat;
  8631. }
  8632. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8633. }
  8634. candidates->sorted = false;
  8635. if (ctx) {
  8636. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8637. }
  8638. }
  8639. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8640. GGML_ASSERT(ctx);
  8641. const int64_t t_start_sample_us = ggml_time_us();
  8642. bool allow_eos = false;
  8643. for (const auto & stack : grammar->stacks) {
  8644. if (stack.empty()) {
  8645. allow_eos = true;
  8646. break;
  8647. }
  8648. }
  8649. const llama_token eos = llama_token_eos(&ctx->model);
  8650. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8651. candidates_decoded.reserve(candidates->size);
  8652. std::vector<llama_grammar_candidate> candidates_grammar;
  8653. candidates_grammar.reserve(candidates->size);
  8654. for (size_t i = 0; i < candidates->size; ++i) {
  8655. const llama_token id = candidates->data[i].id;
  8656. const std::string piece = llama_token_to_piece(ctx, id);
  8657. if (id == eos) {
  8658. if (!allow_eos) {
  8659. candidates->data[i].logit = -INFINITY;
  8660. }
  8661. } else if (piece.empty() || piece[0] == 0) {
  8662. candidates->data[i].logit = -INFINITY;
  8663. } else {
  8664. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8665. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8666. }
  8667. }
  8668. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8669. for (const auto & reject : rejects) {
  8670. candidates->data[reject.index].logit = -INFINITY;
  8671. }
  8672. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8673. }
  8674. static void llama_log_softmax(float * array, size_t size) {
  8675. float max_l = *std::max_element(array, array + size);
  8676. float sum = 0.f;
  8677. for (size_t i = 0; i < size; ++i) {
  8678. float p = expf(array[i] - max_l);
  8679. sum += p;
  8680. array[i] = p;
  8681. }
  8682. for (size_t i = 0; i < size; ++i) {
  8683. array[i] = logf(array[i] / sum);
  8684. }
  8685. }
  8686. void llama_sample_apply_guidance(
  8687. struct llama_context * ctx,
  8688. float * logits,
  8689. float * logits_guidance,
  8690. float scale) {
  8691. GGML_ASSERT(ctx);
  8692. const auto t_start_sample_us = ggml_time_us();
  8693. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8694. llama_log_softmax(logits, n_vocab);
  8695. llama_log_softmax(logits_guidance, n_vocab);
  8696. for (int i = 0; i < n_vocab; ++i) {
  8697. auto & l = logits[i];
  8698. const auto & g = logits_guidance[i];
  8699. l = scale * (l - g) + g;
  8700. }
  8701. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8702. }
  8703. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8704. GGML_ASSERT(ctx);
  8705. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8706. int64_t t_start_sample_us;
  8707. t_start_sample_us = ggml_time_us();
  8708. llama_sample_softmax(nullptr, candidates);
  8709. // Estimate s_hat using the most probable m tokens
  8710. float s_hat = 0.0;
  8711. float sum_ti_bi = 0.0;
  8712. float sum_ti_sq = 0.0;
  8713. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8714. float t_i = logf(float(i + 2) / float(i + 1));
  8715. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8716. sum_ti_bi += t_i * b_i;
  8717. sum_ti_sq += t_i * t_i;
  8718. }
  8719. s_hat = sum_ti_bi / sum_ti_sq;
  8720. // Compute k from the estimated s_hat and target surprise value
  8721. float epsilon_hat = s_hat - 1;
  8722. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8723. // Sample the next word X using top-k sampling
  8724. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8725. if (ctx) {
  8726. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8727. }
  8728. llama_token X = llama_sample_token(ctx, candidates);
  8729. t_start_sample_us = ggml_time_us();
  8730. // Compute error as the difference between observed surprise and target surprise value
  8731. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8732. return candidate.id == X;
  8733. }));
  8734. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8735. float e = observed_surprise - tau;
  8736. // Update mu using the learning rate and error
  8737. *mu = *mu - eta * e;
  8738. if (ctx) {
  8739. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8740. }
  8741. return X;
  8742. }
  8743. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8744. int64_t t_start_sample_us;
  8745. t_start_sample_us = ggml_time_us();
  8746. llama_sample_softmax(ctx, candidates);
  8747. // Truncate the words with surprise values greater than mu
  8748. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8749. return -log2f(candidate.p) > *mu;
  8750. }));
  8751. if (candidates->size == 0) {
  8752. candidates->size = 1;
  8753. }
  8754. if (ctx) {
  8755. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8756. }
  8757. // Normalize the probabilities of the remaining words
  8758. llama_sample_softmax(ctx, candidates);
  8759. // Sample the next word X from the remaining words
  8760. llama_token X = llama_sample_token(ctx, candidates);
  8761. t_start_sample_us = ggml_time_us();
  8762. // Compute error as the difference between observed surprise and target surprise value
  8763. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8764. return candidate.id == X;
  8765. }));
  8766. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8767. float e = observed_surprise - tau;
  8768. // Update mu using the learning rate and error
  8769. *mu = *mu - eta * e;
  8770. if (ctx) {
  8771. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8772. }
  8773. return X;
  8774. }
  8775. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8776. const int64_t t_start_sample_us = ggml_time_us();
  8777. // Find max element
  8778. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8779. return a.logit < b.logit;
  8780. });
  8781. llama_token result = max_iter->id;
  8782. if (ctx) {
  8783. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8784. ctx->n_sample++;
  8785. }
  8786. return result;
  8787. }
  8788. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8789. GGML_ASSERT(ctx);
  8790. const int64_t t_start_sample_us = ggml_time_us();
  8791. llama_sample_softmax(nullptr, candidates);
  8792. std::vector<float> probs;
  8793. probs.reserve(candidates->size);
  8794. for (size_t i = 0; i < candidates->size; ++i) {
  8795. probs.push_back(candidates->data[i].p);
  8796. }
  8797. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8798. auto & rng = ctx->rng;
  8799. int idx = dist(rng);
  8800. llama_token result = candidates->data[idx].id;
  8801. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8802. ctx->n_sample++;
  8803. return result;
  8804. }
  8805. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8806. const int64_t t_start_sample_us = ggml_time_us();
  8807. if (token == llama_token_eos(&ctx->model)) {
  8808. for (const auto & stack : grammar->stacks) {
  8809. if (stack.empty()) {
  8810. return;
  8811. }
  8812. }
  8813. GGML_ASSERT(false);
  8814. }
  8815. const std::string piece = llama_token_to_piece(ctx, token);
  8816. // Note terminating 0 in decoded string
  8817. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8818. const auto & code_points = decoded.first;
  8819. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8820. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8821. }
  8822. grammar->partial_utf8 = decoded.second;
  8823. GGML_ASSERT(!grammar->stacks.empty());
  8824. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8825. }
  8826. //
  8827. // Beam search
  8828. //
  8829. struct llama_beam {
  8830. std::vector<llama_token> tokens;
  8831. float p; // Cumulative beam probability (renormalized relative to all beams)
  8832. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8833. // Sort beams by probability. In case of ties, prefer beams at eob.
  8834. bool operator<(const llama_beam & rhs) const {
  8835. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8836. }
  8837. // Shift off first n tokens and discard them.
  8838. void shift_tokens(const size_t n) {
  8839. if (n) {
  8840. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8841. tokens.resize(tokens.size() - n);
  8842. }
  8843. }
  8844. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8845. };
  8846. // A struct for calculating logit-related info.
  8847. struct llama_logit_info {
  8848. const float * const logits;
  8849. const int n_vocab;
  8850. const float max_l;
  8851. const float normalizer;
  8852. struct sum_exp {
  8853. float max_l;
  8854. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8855. };
  8856. llama_logit_info(llama_context * ctx)
  8857. : logits(llama_get_logits(ctx))
  8858. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8859. , max_l(*std::max_element(logits, logits + n_vocab))
  8860. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8861. { }
  8862. llama_token_data get_token_data(const llama_token token_id) const {
  8863. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8864. return {token_id, logits[token_id], p};
  8865. }
  8866. // Return top k token_data by logit.
  8867. std::vector<llama_token_data> top_k(size_t k) {
  8868. std::vector<llama_token_data> min_heap; // min-heap by logit
  8869. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8870. min_heap.reserve(k_min);
  8871. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8872. min_heap.push_back(get_token_data(token_id));
  8873. }
  8874. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8875. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8876. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8877. if (min_heap.front().logit < logits[token_id]) {
  8878. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8879. min_heap.back().id = token_id;
  8880. min_heap.back().logit = logits[token_id];
  8881. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8882. }
  8883. }
  8884. return min_heap;
  8885. }
  8886. float probability_from_logit(float logit) const {
  8887. return normalizer * std::exp(logit - max_l);
  8888. }
  8889. };
  8890. struct llama_beam_search_data {
  8891. llama_context * ctx;
  8892. size_t n_beams;
  8893. int n_past;
  8894. int n_predict;
  8895. std::vector<llama_beam> beams;
  8896. std::vector<llama_beam> next_beams;
  8897. // Re-calculated on each loop iteration
  8898. size_t common_prefix_length;
  8899. // Used to communicate to/from callback on beams state.
  8900. std::vector<llama_beam_view> beam_views;
  8901. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8902. : ctx(ctx)
  8903. , n_beams(n_beams)
  8904. , n_past(n_past)
  8905. , n_predict(n_predict)
  8906. , beam_views(n_beams) {
  8907. beams.reserve(n_beams);
  8908. next_beams.reserve(n_beams);
  8909. }
  8910. // Collapse beams to a single beam given by index.
  8911. void collapse_beams(const size_t beam_idx) {
  8912. if (0u < beam_idx) {
  8913. std::swap(beams[0], beams[beam_idx]);
  8914. }
  8915. beams.resize(1);
  8916. }
  8917. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8918. // The repetitive patterns below reflect the 2 stages of heaps:
  8919. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8920. // * If the heap is full and a new element is found that should be included, pop the
  8921. // least element to the back(), replace it with the new, then push it into the heap.
  8922. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8923. // Min-heaps use a greater-than comparator.
  8924. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8925. if (beam.eob) {
  8926. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8927. if (next_beams.size() < n_beams) {
  8928. next_beams.push_back(std::move(beam));
  8929. if (next_beams.size() == n_beams) {
  8930. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8931. }
  8932. } else if (next_beams.front().p < beam.p) {
  8933. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8934. next_beams.back() = std::move(beam);
  8935. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8936. }
  8937. } else {
  8938. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8939. if (!beam.tokens.empty()) {
  8940. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8941. }
  8942. llama_logit_info logit_info(ctx);
  8943. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8944. size_t i=0;
  8945. if (next_beams.size() < n_beams) {
  8946. for (; next_beams.size() < n_beams ; ++i) {
  8947. llama_beam next_beam = beam;
  8948. next_beam.tokens.push_back(next_tokens[i].id);
  8949. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8950. next_beams.push_back(std::move(next_beam));
  8951. }
  8952. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8953. } else {
  8954. for (; next_beams.front().p == 0.0f ; ++i) {
  8955. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8956. next_beams.back() = beam;
  8957. next_beams.back().tokens.push_back(next_tokens[i].id);
  8958. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8959. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8960. }
  8961. }
  8962. for (; i < n_beams ; ++i) {
  8963. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8964. if (next_beams.front().p < next_p) {
  8965. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8966. next_beams.back() = beam;
  8967. next_beams.back().tokens.push_back(next_tokens[i].id);
  8968. next_beams.back().p = next_p;
  8969. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8970. }
  8971. }
  8972. }
  8973. }
  8974. // Find common_prefix_length based on beams.
  8975. // Requires beams is not empty.
  8976. size_t find_common_prefix_length() {
  8977. size_t common_prefix_length = beams[0].tokens.size();
  8978. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8979. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8980. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8981. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8982. common_prefix_length = j;
  8983. break;
  8984. }
  8985. }
  8986. }
  8987. return common_prefix_length;
  8988. }
  8989. // Construct beams_state to send back to caller via the callback function.
  8990. // Side effect: set common_prefix_length = find_common_prefix_length();
  8991. llama_beams_state get_beams_state(const bool last_call) {
  8992. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8993. beam_views[i] = beams[i].view();
  8994. }
  8995. common_prefix_length = find_common_prefix_length();
  8996. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8997. }
  8998. // Loop:
  8999. // * while i < n_predict, AND
  9000. // * any of the beams have not yet reached end-of-beam (eob), AND
  9001. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  9002. // (since all other beam probabilities can only decrease)
  9003. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  9004. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  9005. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  9006. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  9007. !beams[top_beam_index()].eob ; ++i) {
  9008. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  9009. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  9010. if (common_prefix_length) {
  9011. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  9012. n_past += common_prefix_length;
  9013. }
  9014. // Zero-out next_beam probabilities to place them last in following min-heap.
  9015. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  9016. for (llama_beam & beam : beams) {
  9017. beam.shift_tokens(common_prefix_length);
  9018. fill_next_beams_by_top_probabilities(beam);
  9019. }
  9020. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  9021. beams.swap(next_beams);
  9022. renormalize_beam_probabilities(beams);
  9023. }
  9024. collapse_beams(top_beam_index());
  9025. callback(callback_data, get_beams_state(true));
  9026. }
  9027. // As beams grow, the cumulative probabilities decrease.
  9028. // Renormalize them to avoid floating point underflow.
  9029. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  9030. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  9031. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  9032. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  9033. }
  9034. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  9035. size_t top_beam_index() {
  9036. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  9037. }
  9038. // Copy (p,eob) for each beam which may have been changed by the callback.
  9039. void update_beams_from_beam_views() {
  9040. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9041. beams[i].p = beam_views[i].p;
  9042. beams[i].eob = beam_views[i].eob;
  9043. }
  9044. }
  9045. };
  9046. void llama_beam_search(llama_context * ctx,
  9047. llama_beam_search_callback_fn_t callback, void * callback_data,
  9048. size_t n_beams, int n_past, int n_predict) {
  9049. assert(ctx);
  9050. const int64_t t_start_sample_us = ggml_time_us();
  9051. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  9052. beam_search_data.loop(callback, callback_data);
  9053. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9054. ctx->n_sample++;
  9055. }
  9056. //
  9057. // quantization
  9058. //
  9059. struct quantize_state_internal {
  9060. const llama_model & model;
  9061. const llama_model_quantize_params * params;
  9062. int n_attention_wv = 0;
  9063. int n_ffn_down = 0;
  9064. int n_ffn_gate = 0;
  9065. int n_ffn_up = 0;
  9066. int i_attention_wv = 0;
  9067. int i_ffn_down = 0;
  9068. int i_ffn_gate = 0;
  9069. int i_ffn_up = 0;
  9070. int n_k_quantized = 0;
  9071. int n_fallback = 0;
  9072. bool has_imatrix = false;
  9073. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  9074. : model(model)
  9075. , params(params)
  9076. {}
  9077. };
  9078. static void llama_tensor_dequantize_internal(
  9079. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  9080. const size_t nelements, const int nthread
  9081. ) {
  9082. if (output.size() < nelements) {
  9083. output.resize(nelements);
  9084. }
  9085. float * f32_output = (float *) output.data();
  9086. ggml_type_traits_t qtype;
  9087. if (ggml_is_quantized(tensor->type)) {
  9088. qtype = ggml_internal_get_type_traits(tensor->type);
  9089. if (qtype.to_float == NULL) {
  9090. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  9091. }
  9092. } else if (tensor->type != GGML_TYPE_F16) {
  9093. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  9094. }
  9095. if (nthread < 2) {
  9096. if (tensor->type == GGML_TYPE_F16) {
  9097. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  9098. } else if (ggml_is_quantized(tensor->type)) {
  9099. qtype.to_float(tensor->data, f32_output, nelements);
  9100. } else {
  9101. GGML_ASSERT(false); // unreachable
  9102. }
  9103. return;
  9104. }
  9105. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  9106. size_t block_size_bytes = ggml_type_size(tensor->type);
  9107. GGML_ASSERT(nelements % block_size == 0);
  9108. size_t nblocks = nelements / block_size;
  9109. size_t blocks_per_thread = nblocks / nthread;
  9110. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  9111. size_t in_buff_offs = 0;
  9112. size_t out_buff_offs = 0;
  9113. for (int tnum = 0; tnum < nthread; tnum++) {
  9114. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  9115. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  9116. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  9117. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  9118. if (typ == GGML_TYPE_F16) {
  9119. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  9120. } else {
  9121. qtype.to_float(inbuf, outbuf, nels);
  9122. }
  9123. };
  9124. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  9125. in_buff_offs += thr_block_bytes;
  9126. out_buff_offs += thr_elems;
  9127. }
  9128. for (auto & w : workers) { w.join(); }
  9129. workers.clear();
  9130. }
  9131. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  9132. const std::string name = ggml_get_name(tensor);
  9133. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9134. const llm_arch arch = qs.model.arch;
  9135. const auto tn = LLM_TN(arch);
  9136. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  9137. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  9138. };
  9139. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  9140. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  9141. if (n_expert > 1) {
  9142. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  9143. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  9144. // for getting the current layer as I initially thought, and we need to resort to parsing the
  9145. // tensor name.
  9146. n_layer /= n_expert;
  9147. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  9148. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  9149. }
  9150. if (i_layer < 0 || i_layer >= n_layer) {
  9151. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  9152. }
  9153. }
  9154. return std::make_pair(i_layer, n_layer);
  9155. };
  9156. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  9157. // with the quantization of the output tensor
  9158. if (name == tn(LLM_TENSOR_OUTPUT, "weight") ||
  9159. (LLM_TENSOR_NAMES.at(arch).find(LLM_TENSOR_OUTPUT) == LLM_TENSOR_NAMES.at(arch).end() && name == "token_embd.weight")) {
  9160. int nx = tensor->ne[0];
  9161. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  9162. new_type = GGML_TYPE_Q8_0;
  9163. }
  9164. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9165. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9166. new_type = GGML_TYPE_Q5_K;
  9167. }
  9168. else if (new_type != GGML_TYPE_Q8_0) {
  9169. new_type = GGML_TYPE_Q6_K;
  9170. }
  9171. } else if (name == "token_embd.weight") {
  9172. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  9173. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  9174. new_type = GGML_TYPE_Q2_K;
  9175. }
  9176. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9177. new_type = GGML_TYPE_IQ3_S;
  9178. }
  9179. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9180. new_type = GGML_TYPE_IQ3_S;
  9181. }
  9182. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  9183. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9184. if (name.find("attn_v.weight") != std::string::npos) {
  9185. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  9186. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9187. ++qs.i_attention_wv;
  9188. }
  9189. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  9190. new_type = GGML_TYPE_Q4_K;
  9191. }
  9192. else if (name.find("ffn_down") != std::string::npos) {
  9193. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  9194. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9195. }
  9196. ++qs.i_ffn_down;
  9197. }
  9198. else if (name.find("attn_output.weight") != std::string::npos) {
  9199. if (qs.model.hparams.n_expert == 8) {
  9200. new_type = GGML_TYPE_Q5_K;
  9201. } else {
  9202. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  9203. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  9204. }
  9205. }
  9206. } else if (name.find("attn_v.weight") != std::string::npos) {
  9207. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  9208. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9209. }
  9210. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  9211. new_type = GGML_TYPE_Q4_K;
  9212. }
  9213. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9214. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  9215. }
  9216. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9217. new_type = GGML_TYPE_Q4_K;
  9218. }
  9219. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9220. new_type = GGML_TYPE_Q4_K;
  9221. }
  9222. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9223. new_type = GGML_TYPE_Q4_K;
  9224. }
  9225. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9226. new_type = GGML_TYPE_Q4_K;
  9227. }
  9228. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9229. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9230. }
  9231. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  9232. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  9233. new_type = GGML_TYPE_Q5_K;
  9234. }
  9235. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  9236. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  9237. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  9238. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  9239. (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;
  9240. if (qs.model.type == MODEL_70B) {
  9241. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  9242. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  9243. // nearly negligible increase in model size by quantizing this tensor with more bits:
  9244. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  9245. }
  9246. if (qs.model.hparams.n_expert == 8) {
  9247. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9248. // TODO: explore better strategies
  9249. new_type = GGML_TYPE_Q8_0;
  9250. }
  9251. ++qs.i_attention_wv;
  9252. } else if (name.find("attn_k.weight") != std::string::npos) {
  9253. if (qs.model.hparams.n_expert == 8) {
  9254. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9255. // TODO: explore better strategies
  9256. new_type = GGML_TYPE_Q8_0;
  9257. }
  9258. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9259. new_type = GGML_TYPE_IQ3_XXS;
  9260. }
  9261. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9262. new_type = GGML_TYPE_IQ2_S;
  9263. }
  9264. } else if (name.find("attn_q.weight") != std::string::npos) {
  9265. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9266. new_type = GGML_TYPE_IQ3_XXS;
  9267. }
  9268. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9269. new_type = GGML_TYPE_IQ2_S;
  9270. }
  9271. } else if (name.find("ffn_down") != std::string::npos) {
  9272. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  9273. int i_layer = info.first, n_layer = info.second;
  9274. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9275. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  9276. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  9277. }
  9278. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  9279. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9280. }
  9281. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9282. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  9283. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  9284. : GGML_TYPE_Q3_K;
  9285. }
  9286. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  9287. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  9288. new_type = GGML_TYPE_Q4_K;
  9289. }
  9290. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  9291. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  9292. }
  9293. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  9294. if (arch == LLM_ARCH_FALCON) {
  9295. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  9296. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9297. } else {
  9298. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9299. }
  9300. }
  9301. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  9302. new_type = GGML_TYPE_Q5_K;
  9303. }
  9304. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9305. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  9306. new_type = GGML_TYPE_Q5_K;
  9307. }
  9308. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  9309. && qs.has_imatrix && i_layer < n_layer/8) {
  9310. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  9311. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  9312. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  9313. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  9314. }
  9315. ++qs.i_ffn_down;
  9316. } else if (name.find("attn_output.weight") != std::string::npos) {
  9317. if (arch != LLM_ARCH_FALCON) {
  9318. if (qs.model.hparams.n_expert == 8) {
  9319. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9320. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  9321. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  9322. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  9323. new_type = GGML_TYPE_Q5_K;
  9324. }
  9325. } else {
  9326. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  9327. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  9328. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  9329. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  9330. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  9331. }
  9332. } else {
  9333. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  9334. }
  9335. }
  9336. else if (name.find("attn_qkv.weight") != std::string::npos) {
  9337. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9338. new_type = GGML_TYPE_Q4_K;
  9339. }
  9340. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  9341. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  9342. }
  9343. else if (name.find("ffn_gate") != std::string::npos) {
  9344. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  9345. int i_layer = info.first, n_layer = info.second;
  9346. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9347. new_type = GGML_TYPE_IQ3_XXS;
  9348. }
  9349. ++qs.i_ffn_gate;
  9350. }
  9351. else if (name.find("ffn_up") != std::string::npos) {
  9352. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  9353. int i_layer = info.first, n_layer = info.second;
  9354. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9355. new_type = GGML_TYPE_IQ3_XXS;
  9356. }
  9357. ++qs.i_ffn_up;
  9358. }
  9359. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9360. //}
  9361. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  9362. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  9363. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9364. //}
  9365. // This can be used to reduce the size of the Q5_K_S model.
  9366. // The associated PPL increase is fully in line with the size reduction
  9367. //else {
  9368. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  9369. //}
  9370. bool convert_incompatible_tensor = false;
  9371. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  9372. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  9373. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  9374. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  9375. int nx = tensor->ne[0];
  9376. int ny = tensor->ne[1];
  9377. if (nx % QK_K != 0) {
  9378. 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));
  9379. convert_incompatible_tensor = true;
  9380. } else {
  9381. ++qs.n_k_quantized;
  9382. }
  9383. }
  9384. if (convert_incompatible_tensor) {
  9385. switch (new_type) {
  9386. case GGML_TYPE_IQ2_XXS:
  9387. case GGML_TYPE_IQ2_XS:
  9388. case GGML_TYPE_IQ2_S:
  9389. case GGML_TYPE_IQ3_XXS:
  9390. case GGML_TYPE_IQ3_S:
  9391. case GGML_TYPE_IQ1_S:
  9392. case GGML_TYPE_Q2_K:
  9393. case GGML_TYPE_Q3_K:
  9394. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  9395. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  9396. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  9397. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  9398. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  9399. }
  9400. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  9401. ++qs.n_fallback;
  9402. }
  9403. return new_type;
  9404. }
  9405. static int32_t llama_tensor_quantize_internal(enum ggml_type new_type, const float * f32_data, void * new_data, const int chunk_size, int nrows, int n_per_row, int64_t * hist_cur, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  9406. std::mutex mutex;
  9407. int counter = 0;
  9408. size_t new_size = 0;
  9409. if (nthread < 2) {
  9410. // single-thread
  9411. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur, imatrix);
  9412. }
  9413. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9414. nrows, n_per_row, imatrix]() {
  9415. std::array<int64_t, 1 << 4> local_hist = {};
  9416. const int nrows_per_chunk = chunk_size / n_per_row;
  9417. size_t local_size = 0;
  9418. while (true) {
  9419. std::unique_lock<std::mutex> lock(mutex);
  9420. int first_row = counter; counter += nrows_per_chunk;
  9421. if (first_row >= nrows) {
  9422. if (local_size > 0) {
  9423. for (int j=0; j<int(local_hist.size()); ++j) {
  9424. hist_cur[j] += local_hist[j];
  9425. }
  9426. new_size += local_size;
  9427. }
  9428. break;
  9429. }
  9430. lock.unlock();
  9431. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9432. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9433. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9434. }
  9435. };
  9436. for (int it = 0; it < nthread - 1; ++it) {
  9437. workers.emplace_back(compute);
  9438. }
  9439. compute();
  9440. for (auto & w : workers) { w.join(); }
  9441. workers.clear();
  9442. return new_size;
  9443. }
  9444. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  9445. ggml_type quantized_type;
  9446. llama_ftype ftype = params->ftype;
  9447. switch (params->ftype) {
  9448. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  9449. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  9450. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  9451. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  9452. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  9453. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  9454. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  9455. // K-quants
  9456. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  9457. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  9458. case LLAMA_FTYPE_MOSTLY_IQ3_XS: quantized_type = GGML_TYPE_IQ3_S; break;
  9459. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  9460. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  9461. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  9462. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  9463. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  9464. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  9465. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  9466. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  9467. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  9468. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  9469. case LLAMA_FTYPE_MOSTLY_IQ2_S: quantized_type = GGML_TYPE_IQ2_XS; break;
  9470. case LLAMA_FTYPE_MOSTLY_IQ2_M: quantized_type = GGML_TYPE_IQ2_S; break;
  9471. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  9472. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  9473. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  9474. case LLAMA_FTYPE_MOSTLY_IQ4_XS: quantized_type = GGML_TYPE_IQ4_XS; break;
  9475. case LLAMA_FTYPE_MOSTLY_IQ3_S: quantized_type = GGML_TYPE_IQ3_S; break;
  9476. case LLAMA_FTYPE_MOSTLY_IQ3_M: quantized_type = GGML_TYPE_IQ3_S; break;
  9477. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  9478. }
  9479. int nthread = params->nthread;
  9480. if (nthread <= 0) {
  9481. nthread = std::thread::hardware_concurrency();
  9482. }
  9483. // mmap consistently increases speed Linux, and also increases speed on Windows with
  9484. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  9485. #if defined(__linux__) || defined(_WIN32)
  9486. constexpr bool use_mmap = true;
  9487. #else
  9488. constexpr bool use_mmap = false;
  9489. #endif
  9490. llama_model_loader ml(fname_inp, use_mmap, NULL);
  9491. ml.init_mapping(false); // no prefetching?
  9492. llama_model model;
  9493. llm_load_arch(ml, model);
  9494. llm_load_hparams(ml, model);
  9495. struct quantize_state_internal qs(model, params);
  9496. if (params->only_copy) {
  9497. ftype = model.ftype;
  9498. }
  9499. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  9500. if (params->imatrix) {
  9501. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  9502. if (imatrix_data) {
  9503. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  9504. qs.has_imatrix = true;
  9505. }
  9506. }
  9507. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  9508. struct gguf_context * ctx_out = gguf_init_empty();
  9509. // copy the KV pairs from the input file
  9510. gguf_set_kv (ctx_out, ml.ctx_gguf);
  9511. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  9512. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  9513. for (int i = 0; i < ml.n_tensors; ++i) {
  9514. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9515. const std::string name = ggml_get_name(meta);
  9516. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9517. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9518. ++qs.n_attention_wv;
  9519. }
  9520. else if (name.find("ffn_down") != std::string::npos) {
  9521. ++qs.n_ffn_down;
  9522. }
  9523. else if (name.find("ffn_gate") != std::string::npos) {
  9524. ++qs.n_ffn_gate;
  9525. }
  9526. else if (name.find("ffn_up") != std::string::npos) {
  9527. ++qs.n_ffn_up;
  9528. }
  9529. }
  9530. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9531. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9532. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9533. }
  9534. size_t total_size_org = 0;
  9535. size_t total_size_new = 0;
  9536. std::vector<int64_t> hist_all(1 << 4, 0);
  9537. std::vector<std::thread> workers;
  9538. workers.reserve(nthread);
  9539. int idx = 0;
  9540. std::vector<no_init<uint8_t>> read_data;
  9541. std::vector<no_init<uint8_t>> work;
  9542. std::vector<no_init<float>> f32_conv_buf;
  9543. // populate the original tensors so we get an initial meta data
  9544. for (int i = 0; i < ml.n_tensors; ++i) {
  9545. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9546. gguf_add_tensor(ctx_out, meta);
  9547. }
  9548. std::ofstream fout(fname_out, std::ios::binary);
  9549. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9550. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9551. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9552. // placeholder for the meta data
  9553. ::zeros(fout, meta_size);
  9554. for (int i = 0; i < ml.n_tensors; ++i) {
  9555. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9556. const std::string name = ggml_get_name(tensor);
  9557. if (!ml.use_mmap) {
  9558. if (read_data.size() < ggml_nbytes(tensor)) {
  9559. read_data.resize(ggml_nbytes(tensor));
  9560. }
  9561. tensor->data = read_data.data();
  9562. }
  9563. ml.load_data_for(tensor);
  9564. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9565. ++idx, ml.n_tensors,
  9566. ggml_get_name(tensor),
  9567. llama_format_tensor_shape(tensor).c_str(),
  9568. ggml_type_name(tensor->type));
  9569. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9570. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9571. // quantize only 2D tensors
  9572. quantize &= (ggml_n_dims(tensor) == 2);
  9573. quantize &= params->quantize_output_tensor || name != "output.weight";
  9574. quantize &= !params->only_copy;
  9575. // do not quantize expert gating tensors
  9576. // NOTE: can't use LLM_TN here because the layer number is not known
  9577. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  9578. // do not quantize positional embeddings and token types (BERT)
  9579. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9580. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9581. enum ggml_type new_type;
  9582. void * new_data;
  9583. size_t new_size;
  9584. if (quantize) {
  9585. new_type = quantized_type;
  9586. if (!params->pure) {
  9587. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9588. }
  9589. // If we've decided to quantize to the same type the tensor is already
  9590. // in then there's nothing to do.
  9591. quantize = tensor->type != new_type;
  9592. }
  9593. if (!quantize) {
  9594. new_type = tensor->type;
  9595. new_data = tensor->data;
  9596. new_size = ggml_nbytes(tensor);
  9597. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9598. } else {
  9599. const size_t nelements = ggml_nelements(tensor);
  9600. const float * imatrix = nullptr;
  9601. if (imatrix_data) {
  9602. auto it = imatrix_data->find(tensor->name);
  9603. if (it == imatrix_data->end()) {
  9604. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9605. } else {
  9606. if (it->second.size() == (size_t)tensor->ne[0]) {
  9607. imatrix = it->second.data();
  9608. } else {
  9609. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9610. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9611. }
  9612. }
  9613. }
  9614. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9615. new_type == GGML_TYPE_IQ2_XS ||
  9616. new_type == GGML_TYPE_IQ2_S ||
  9617. new_type == GGML_TYPE_IQ1_S ||
  9618. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9619. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9620. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9621. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9622. LLAMA_LOG_ERROR("============================================================\n\n");
  9623. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9624. }
  9625. float * f32_data;
  9626. if (tensor->type == GGML_TYPE_F32) {
  9627. f32_data = (float *) tensor->data;
  9628. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9629. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9630. } else {
  9631. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9632. f32_data = (float *) f32_conv_buf.data();
  9633. }
  9634. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9635. fflush(stdout);
  9636. if (work.size() < nelements * 4) {
  9637. work.resize(nelements * 4); // upper bound on size
  9638. }
  9639. new_data = work.data();
  9640. std::array<int64_t, 1 << 4> hist_cur = {};
  9641. const int n_per_row = tensor->ne[0];
  9642. const int nrows = nelements / n_per_row;
  9643. static const int min_chunk_size = 32 * 512;
  9644. 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);
  9645. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9646. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9647. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, hist_cur.data(), imatrix, workers, nthread_use);
  9648. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9649. int64_t tot_count = 0;
  9650. for (size_t i = 0; i < hist_cur.size(); i++) {
  9651. hist_all[i] += hist_cur[i];
  9652. tot_count += hist_cur[i];
  9653. }
  9654. if (tot_count > 0) {
  9655. LLAMA_LOG_INFO(" | hist: ");
  9656. for (size_t i = 0; i < hist_cur.size(); i++) {
  9657. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9658. }
  9659. }
  9660. LLAMA_LOG_INFO("\n");
  9661. }
  9662. total_size_org += ggml_nbytes(tensor);
  9663. total_size_new += new_size;
  9664. // update the gguf meta data as we go
  9665. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9666. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9667. // write tensor data + padding
  9668. fout.write((const char *) new_data, new_size);
  9669. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9670. }
  9671. // go back to beginning of file and write the updated meta data
  9672. {
  9673. fout.seekp(0);
  9674. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9675. gguf_get_meta_data(ctx_out, data.data());
  9676. fout.write((const char *) data.data(), data.size());
  9677. }
  9678. fout.close();
  9679. gguf_free(ctx_out);
  9680. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9681. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9682. // print histogram for all tensors
  9683. {
  9684. int64_t sum_all = 0;
  9685. for (size_t i = 0; i < hist_all.size(); i++) {
  9686. sum_all += hist_all[i];
  9687. }
  9688. if (sum_all > 0) {
  9689. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9690. for (size_t i = 0; i < hist_all.size(); i++) {
  9691. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9692. }
  9693. LLAMA_LOG_INFO("\n");
  9694. }
  9695. }
  9696. if (qs.n_fallback > 0) {
  9697. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9698. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9699. }
  9700. }
  9701. static int llama_apply_lora_from_file_internal(
  9702. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9703. ) {
  9704. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9705. const int64_t t_start_lora_us = ggml_time_us();
  9706. llama_file fin(path_lora, "rb");
  9707. // verify magic and version
  9708. {
  9709. uint32_t magic = fin.read_u32();
  9710. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9711. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9712. return 1;
  9713. }
  9714. uint32_t format_version = fin.read_u32();
  9715. if (format_version != 1) {
  9716. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9717. return 1;
  9718. }
  9719. }
  9720. int32_t lora_r = fin.read_u32();
  9721. int32_t lora_alpha = fin.read_u32();
  9722. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9723. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9724. // load base model
  9725. std::unique_ptr<llama_model_loader> ml;
  9726. if (path_base_model) {
  9727. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9728. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9729. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9730. }
  9731. struct tensor_meta {
  9732. std::string name;
  9733. ggml_type type;
  9734. int32_t ne[2];
  9735. size_t offset;
  9736. };
  9737. std::map<std::string, tensor_meta> tensor_meta_map;
  9738. // load all tensor meta
  9739. while (true) {
  9740. if (fin.tell() == fin.size) {
  9741. // eof
  9742. break;
  9743. }
  9744. int32_t n_dims;
  9745. int32_t name_len;
  9746. int32_t ftype;
  9747. fin.read_raw(&n_dims, sizeof(n_dims));
  9748. fin.read_raw(&name_len, sizeof(name_len));
  9749. fin.read_raw(&ftype, sizeof(ftype));
  9750. if (n_dims != 1 && n_dims != 2) {
  9751. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9752. return 1;
  9753. }
  9754. int32_t ne[2] = { 1, 1 };
  9755. for (int i = 0; i < n_dims; ++i) {
  9756. fin.read_raw(&ne[i], sizeof(ne[i]));
  9757. }
  9758. std::string name;
  9759. {
  9760. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9761. char buf[GGML_MAX_NAME];
  9762. fin.read_raw(buf, name_len);
  9763. name = std::string(buf, name_len);
  9764. }
  9765. // check for lora suffix
  9766. std::string lora_suffix;
  9767. if (name.length() > 6) {
  9768. lora_suffix = name.substr(name.length() - 6);
  9769. }
  9770. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9771. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9772. return 1;
  9773. }
  9774. // tensor type
  9775. ggml_type wtype;
  9776. switch (ftype) {
  9777. case 0: wtype = GGML_TYPE_F32; break;
  9778. case 1: wtype = GGML_TYPE_F16; break;
  9779. default:
  9780. {
  9781. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9782. __func__, ftype);
  9783. return 1;
  9784. }
  9785. }
  9786. // data offset
  9787. size_t offset = fin.tell();
  9788. offset = (offset + 31) & -32;
  9789. // skip tensor data
  9790. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9791. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9792. }
  9793. bool warned = false;
  9794. int n_tensors = 0;
  9795. // apply
  9796. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9797. if (backend_cpu == nullptr) {
  9798. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9799. return 1;
  9800. }
  9801. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9802. std::vector<no_init<uint8_t>> read_buf;
  9803. for (const auto & it : model.tensors_by_name) {
  9804. const std::string & base_name = it.first;
  9805. ggml_tensor * model_t = it.second;
  9806. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9807. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9808. continue;
  9809. }
  9810. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9811. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9812. ggml_init_params lora_init_params = {
  9813. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9814. /* .mem_buffer */ nullptr,
  9815. /* .no_alloc */ true,
  9816. };
  9817. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9818. if (lora_ctx == nullptr) {
  9819. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9820. ggml_backend_free(backend_cpu);
  9821. return 1;
  9822. }
  9823. // create tensors
  9824. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9825. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9826. ggml_set_name(loraA, metaA.name.c_str());
  9827. ggml_set_name(loraB, metaB.name.c_str());
  9828. ggml_tensor * base_t;
  9829. if (ml) {
  9830. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9831. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9832. return 1;
  9833. }
  9834. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9835. } else {
  9836. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9837. }
  9838. ggml_set_name(base_t, base_name.c_str());
  9839. // allocate in backend buffer
  9840. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9841. if (lora_buf == nullptr) {
  9842. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9843. return 1;
  9844. }
  9845. // load tensor data
  9846. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9847. read_buf.resize(ggml_nbytes(tensor));
  9848. fin.seek(tensor_meta.offset, SEEK_SET);
  9849. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9850. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9851. };
  9852. load_tensor(metaA, loraA);
  9853. load_tensor(metaB, loraB);
  9854. // load base model tensor data
  9855. if (ml) {
  9856. ml->load_data_for(base_t);
  9857. } else {
  9858. ggml_backend_tensor_copy(model_t, base_t);
  9859. }
  9860. if (ggml_is_quantized(base_t->type) && !warned) {
  9861. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9862. "use a f16 or f32 base model with --lora-base\n", __func__);
  9863. warned = true;
  9864. }
  9865. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9866. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9867. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9868. ggml_free(lora_ctx);
  9869. ggml_backend_buffer_free(lora_buf);
  9870. ggml_backend_free(backend_cpu);
  9871. return 1;
  9872. }
  9873. auto build_lora_graph = [&]() {
  9874. // w = w + BA*s
  9875. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9876. ggml_set_name(BA, "BA");
  9877. if (scaling != 1.0f) {
  9878. BA = ggml_scale(lora_ctx, BA, scaling);
  9879. ggml_set_name(BA, "BA_scaled");
  9880. }
  9881. ggml_tensor * r;
  9882. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9883. ggml_set_name(r, "r_add");
  9884. if (base_t->type != model_t->type) {
  9885. // convert the result to the model type
  9886. r = ggml_cast(lora_ctx, r, model_t->type);
  9887. ggml_set_name(r, "r_cast");
  9888. }
  9889. return r;
  9890. };
  9891. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9892. ggml_tensor * r = build_lora_graph();
  9893. ggml_build_forward_expand(gf, r);
  9894. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9895. if (graph_buf == nullptr) {
  9896. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9897. ggml_free(lora_ctx);
  9898. ggml_backend_buffer_free(lora_buf);
  9899. ggml_backend_free(backend_cpu);
  9900. return 1;
  9901. }
  9902. ggml_backend_graph_compute(backend_cpu, gf);
  9903. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9904. #if 0
  9905. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9906. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9907. // sched compute
  9908. ggml_build_forward_expand(gf, build_graph());
  9909. ggml_backend_sched_init_measure(sched, gf);
  9910. // create the graph again, since the previous one was destroyed by the measure
  9911. ggml_graph_clear(gf);
  9912. ggml_build_forward_expand(gf, build_graph());
  9913. ggml_backend_sched_graph_compute(sched, gf);
  9914. ggml_backend_sched_free(sched);
  9915. #endif
  9916. ggml_backend_buffer_free(lora_buf);
  9917. ggml_backend_buffer_free(graph_buf);
  9918. ggml_free(lora_ctx);
  9919. n_tensors++;
  9920. if (n_tensors % 4 == 0) {
  9921. LLAMA_LOG_INFO(".");
  9922. }
  9923. }
  9924. ggml_backend_free(backend_cpu);
  9925. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9926. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9927. return 0;
  9928. }
  9929. //
  9930. // interface implementation
  9931. //
  9932. struct llama_model_params llama_model_default_params() {
  9933. struct llama_model_params result = {
  9934. /*.n_gpu_layers =*/ 0,
  9935. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  9936. /*.main_gpu =*/ 0,
  9937. /*.tensor_split =*/ nullptr,
  9938. /*.progress_callback =*/ nullptr,
  9939. /*.progress_callback_user_data =*/ nullptr,
  9940. /*.kv_overrides =*/ nullptr,
  9941. /*.vocab_only =*/ false,
  9942. /*.use_mmap =*/ true,
  9943. /*.use_mlock =*/ false,
  9944. };
  9945. #ifdef GGML_USE_METAL
  9946. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9947. result.n_gpu_layers = 999;
  9948. #endif
  9949. return result;
  9950. }
  9951. struct llama_context_params llama_context_default_params() {
  9952. struct llama_context_params result = {
  9953. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9954. /*.n_ctx =*/ 512,
  9955. /*.n_batch =*/ 512,
  9956. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9957. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9958. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  9959. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  9960. /*.rope_freq_base =*/ 0.0f,
  9961. /*.rope_freq_scale =*/ 0.0f,
  9962. /*.yarn_ext_factor =*/ -1.0f,
  9963. /*.yarn_attn_factor =*/ 1.0f,
  9964. /*.yarn_beta_fast =*/ 32.0f,
  9965. /*.yarn_beta_slow =*/ 1.0f,
  9966. /*.yarn_orig_ctx =*/ 0,
  9967. /*.defrag_thold =*/ -1.0f,
  9968. /*.cb_eval =*/ nullptr,
  9969. /*.cb_eval_user_data =*/ nullptr,
  9970. /*.type_k =*/ GGML_TYPE_F16,
  9971. /*.type_v =*/ GGML_TYPE_F16,
  9972. /*.logits_all =*/ false,
  9973. /*.embeddings =*/ false,
  9974. /*.offload_kqv =*/ true,
  9975. /*.abort_callback =*/ nullptr,
  9976. /*.abort_callback_data =*/ nullptr,
  9977. };
  9978. return result;
  9979. }
  9980. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9981. struct llama_model_quantize_params result = {
  9982. /*.nthread =*/ 0,
  9983. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9984. /*.allow_requantize =*/ false,
  9985. /*.quantize_output_tensor =*/ true,
  9986. /*.only_copy =*/ false,
  9987. /*.pure =*/ false,
  9988. /*.imatrix =*/ nullptr,
  9989. };
  9990. return result;
  9991. }
  9992. size_t llama_max_devices(void) {
  9993. #if defined(GGML_USE_METAL)
  9994. return 1;
  9995. #elif defined(GGML_USE_CUBLAS)
  9996. return GGML_CUDA_MAX_DEVICES;
  9997. #elif defined(GGML_USE_SYCL)
  9998. return GGML_SYCL_MAX_DEVICES;
  9999. #elif defined(GGML_USE_VULKAN)
  10000. return GGML_VK_MAX_DEVICES;
  10001. #else
  10002. return 1;
  10003. #endif
  10004. }
  10005. bool llama_supports_mmap(void) {
  10006. return llama_mmap::SUPPORTED;
  10007. }
  10008. bool llama_supports_mlock(void) {
  10009. return llama_mlock::SUPPORTED;
  10010. }
  10011. bool llama_supports_gpu_offload(void) {
  10012. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  10013. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  10014. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  10015. return true;
  10016. #else
  10017. return false;
  10018. #endif
  10019. }
  10020. void llama_backend_init(void) {
  10021. ggml_time_init();
  10022. // needed to initialize f16 tables
  10023. {
  10024. struct ggml_init_params params = { 0, NULL, false };
  10025. struct ggml_context * ctx = ggml_init(params);
  10026. ggml_free(ctx);
  10027. }
  10028. #ifdef GGML_USE_MPI
  10029. ggml_mpi_backend_init();
  10030. #endif
  10031. }
  10032. void llama_numa_init(enum ggml_numa_strategy numa) {
  10033. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  10034. ggml_numa_init(numa);
  10035. }
  10036. }
  10037. void llama_backend_free(void) {
  10038. #ifdef GGML_USE_MPI
  10039. ggml_mpi_backend_free();
  10040. #endif
  10041. ggml_quantize_free();
  10042. }
  10043. int64_t llama_time_us(void) {
  10044. return ggml_time_us();
  10045. }
  10046. struct llama_model * llama_load_model_from_file(
  10047. const char * path_model,
  10048. struct llama_model_params params) {
  10049. ggml_time_init();
  10050. llama_model * model = new llama_model;
  10051. unsigned cur_percentage = 0;
  10052. if (params.progress_callback == NULL) {
  10053. params.progress_callback_user_data = &cur_percentage;
  10054. params.progress_callback = [](float progress, void * ctx) {
  10055. unsigned * cur_percentage_p = (unsigned *) ctx;
  10056. unsigned percentage = (unsigned) (100 * progress);
  10057. while (percentage > *cur_percentage_p) {
  10058. *cur_percentage_p = percentage;
  10059. LLAMA_LOG_INFO(".");
  10060. if (percentage >= 100) {
  10061. LLAMA_LOG_INFO("\n");
  10062. }
  10063. }
  10064. return true;
  10065. };
  10066. }
  10067. int status = llama_model_load(path_model, *model, params);
  10068. GGML_ASSERT(status <= 0);
  10069. if (status < 0) {
  10070. if (status == -1) {
  10071. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  10072. } else if (status == -2) {
  10073. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  10074. }
  10075. delete model;
  10076. return nullptr;
  10077. }
  10078. return model;
  10079. }
  10080. void llama_free_model(struct llama_model * model) {
  10081. delete model;
  10082. }
  10083. struct llama_context * llama_new_context_with_model(
  10084. struct llama_model * model,
  10085. struct llama_context_params params) {
  10086. if (!model) {
  10087. return nullptr;
  10088. }
  10089. llama_context * ctx = new llama_context(*model);
  10090. const auto & hparams = model->hparams;
  10091. auto & cparams = ctx->cparams;
  10092. cparams.n_batch = params.n_batch;
  10093. cparams.n_threads = params.n_threads;
  10094. cparams.n_threads_batch = params.n_threads_batch;
  10095. cparams.yarn_ext_factor = params.yarn_ext_factor;
  10096. cparams.yarn_attn_factor = params.yarn_attn_factor;
  10097. cparams.yarn_beta_fast = params.yarn_beta_fast;
  10098. cparams.yarn_beta_slow = params.yarn_beta_slow;
  10099. cparams.defrag_thold = params.defrag_thold;
  10100. cparams.embeddings = params.embeddings;
  10101. cparams.offload_kqv = params.offload_kqv;
  10102. cparams.pooling_type = params.pooling_type;
  10103. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  10104. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  10105. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  10106. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  10107. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  10108. hparams.n_ctx_train;
  10109. cparams.cb_eval = params.cb_eval;
  10110. cparams.cb_eval_user_data = params.cb_eval_user_data;
  10111. auto rope_scaling_type = params.rope_scaling_type;
  10112. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  10113. rope_scaling_type = hparams.rope_scaling_type_train;
  10114. }
  10115. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  10116. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  10117. }
  10118. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  10119. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  10120. }
  10121. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10122. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10123. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  10124. } else {
  10125. cparams.pooling_type = hparams.pooling_type;
  10126. }
  10127. }
  10128. if (params.seed == LLAMA_DEFAULT_SEED) {
  10129. params.seed = time(NULL);
  10130. }
  10131. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  10132. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  10133. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  10134. ctx->abort_callback = params.abort_callback;
  10135. ctx->abort_callback_data = params.abort_callback_data;
  10136. ctx->rng = std::mt19937(params.seed);
  10137. ctx->logits_all = params.logits_all;
  10138. const ggml_type type_k = params.type_k;
  10139. const ggml_type type_v = params.type_v;
  10140. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  10141. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  10142. if (!hparams.vocab_only) {
  10143. // initialize backends
  10144. #ifdef GGML_USE_METAL
  10145. if (model->n_gpu_layers > 0) {
  10146. ctx->backend_metal = ggml_backend_metal_init();
  10147. if (ctx->backend_metal == nullptr) {
  10148. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  10149. llama_free(ctx);
  10150. return nullptr;
  10151. }
  10152. ctx->backends.push_back(ctx->backend_metal);
  10153. }
  10154. #elif defined(GGML_USE_CUBLAS)
  10155. if (model->n_gpu_layers > 0) {
  10156. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10157. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10158. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  10159. if (backend == nullptr) {
  10160. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  10161. llama_free(ctx);
  10162. return nullptr;
  10163. }
  10164. ctx->backends.push_back(backend);
  10165. } else {
  10166. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  10167. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  10168. ggml_backend_t backend = ggml_backend_cuda_init(device);
  10169. if (backend == nullptr) {
  10170. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  10171. llama_free(ctx);
  10172. return nullptr;
  10173. }
  10174. ctx->backends.push_back(backend);
  10175. }
  10176. }
  10177. }
  10178. #elif defined(GGML_USE_VULKAN)
  10179. if (model->n_gpu_layers > 0) {
  10180. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  10181. ggml_backend_t backend = ggml_backend_vk_init(device);
  10182. if (backend == nullptr) {
  10183. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  10184. llama_free(ctx);
  10185. return nullptr;
  10186. }
  10187. ctx->backends.push_back(backend);
  10188. }
  10189. }
  10190. #elif defined(GGML_USE_SYCL)
  10191. if (model->n_gpu_layers > 0) {
  10192. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10193. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10194. int main_gpu_index = ggml_backend_sycl_get_device_index(model->main_gpu);
  10195. ggml_backend_t backend = ggml_backend_sycl_init(main_gpu_index);
  10196. if (backend == nullptr) {
  10197. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d)backend\n", __func__, model->main_gpu, main_gpu_index);
  10198. llama_free(ctx);
  10199. return nullptr;
  10200. }
  10201. ctx->backends.push_back(backend);
  10202. } else {
  10203. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  10204. int id_list[GGML_SYCL_MAX_DEVICES];
  10205. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  10206. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  10207. int device_id = id_list[i];
  10208. ggml_backend_t backend = ggml_backend_sycl_init(i);
  10209. if (backend == nullptr) {
  10210. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d)backend\n", __func__, device_id, i);
  10211. llama_free(ctx);
  10212. return nullptr;
  10213. }
  10214. ctx->backends.push_back(backend);
  10215. }
  10216. }
  10217. }
  10218. #elif defined(GGML_USE_KOMPUTE)
  10219. if (model->n_gpu_layers > 0) {
  10220. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  10221. if (backend == nullptr) {
  10222. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  10223. llama_free(ctx);
  10224. return nullptr;
  10225. }
  10226. ctx->backends.push_back(backend);
  10227. }
  10228. #endif
  10229. ctx->backend_cpu = ggml_backend_cpu_init();
  10230. if (ctx->backend_cpu == nullptr) {
  10231. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  10232. llama_free(ctx);
  10233. return nullptr;
  10234. }
  10235. ctx->backends.push_back(ctx->backend_cpu);
  10236. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, cparams.n_ctx, cparams.offload_kqv)) {
  10237. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  10238. llama_free(ctx);
  10239. return nullptr;
  10240. }
  10241. {
  10242. size_t memory_size_k = 0;
  10243. size_t memory_size_v = 0;
  10244. for (auto & k : ctx->kv_self.k_l) {
  10245. memory_size_k += ggml_nbytes(k);
  10246. }
  10247. for (auto & v : ctx->kv_self.v_l) {
  10248. memory_size_v += ggml_nbytes(v);
  10249. }
  10250. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  10251. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  10252. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  10253. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  10254. }
  10255. // resized during inference, reserve maximum
  10256. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  10257. if (params.embeddings) {
  10258. ctx->embd.reserve(hparams.n_embd*cparams.n_batch);
  10259. }
  10260. // graph inputs
  10261. {
  10262. ggml_init_params init_params = {
  10263. /* .mem_size */ ggml_tensor_overhead()*8,
  10264. /* .mem_buffer */ nullptr,
  10265. /* .no_alloc */ true,
  10266. };
  10267. ctx->ctx_input = ggml_init(init_params);
  10268. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10269. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  10270. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10271. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  10272. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  10273. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  10274. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  10275. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10276. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  10277. ggml_set_name(ctx->inp_embd, "inp_embd");
  10278. ggml_set_name(ctx->inp_pos, "inp_pos");
  10279. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  10280. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  10281. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  10282. ggml_set_name(ctx->inp_mean, "inp_mean");
  10283. ggml_set_name(ctx->inp_cls, "inp_cls");
  10284. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  10285. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  10286. ggml_backend_buffer_name(ctx->buf_input),
  10287. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  10288. }
  10289. // scheduler and compute buffers
  10290. {
  10291. // buffer types used for the compute buffer of each backend
  10292. std::vector<ggml_backend_buffer_type_t> backend_buft;
  10293. for (auto * backend : ctx->backends) {
  10294. if (ggml_backend_is_cpu(backend)) {
  10295. // use host buffers for the CPU backend compute buffer
  10296. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  10297. } else {
  10298. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  10299. }
  10300. }
  10301. // buffer used to store the computation graph and the tensor meta data
  10302. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  10303. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  10304. // build worst-case graph
  10305. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  10306. int n_past = cparams.n_ctx - n_tokens;
  10307. 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
  10308. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  10309. // initialize scheduler with the worst-case graph
  10310. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  10311. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  10312. llama_free(ctx);
  10313. return nullptr;
  10314. }
  10315. for (size_t i = 0; i < ctx->backends.size(); i++) {
  10316. ggml_backend_t backend = ctx->backends[i];
  10317. ggml_backend_buffer_type_t buft = backend_buft[i];
  10318. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  10319. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  10320. ggml_backend_buft_name(buft),
  10321. size / 1024.0 / 1024.0);
  10322. }
  10323. // note: the number of splits during measure is higher than during inference due to the kv shift
  10324. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  10325. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  10326. }
  10327. }
  10328. #ifdef GGML_USE_MPI
  10329. ctx->ctx_mpi = ggml_mpi_init();
  10330. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  10331. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  10332. // TODO: needs fix after #3228
  10333. GGML_ASSERT(false && "not implemented");
  10334. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  10335. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  10336. llama_backend_free();
  10337. exit(1);
  10338. }
  10339. #endif
  10340. return ctx;
  10341. }
  10342. void llama_free(struct llama_context * ctx) {
  10343. delete ctx;
  10344. }
  10345. const llama_model * llama_get_model(const struct llama_context * ctx) {
  10346. return &ctx->model;
  10347. }
  10348. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  10349. return ctx->cparams.n_ctx;
  10350. }
  10351. uint32_t llama_n_batch(const struct llama_context * ctx) {
  10352. return ctx->cparams.n_batch;
  10353. }
  10354. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  10355. return model->vocab.type;
  10356. }
  10357. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  10358. switch (model->arch) {
  10359. // these models do not use RoPE
  10360. case LLM_ARCH_GPT2:
  10361. case LLM_ARCH_GPTJ:
  10362. case LLM_ARCH_GPTNEOX:
  10363. case LLM_ARCH_MPT:
  10364. case LLM_ARCH_REFACT:
  10365. case LLM_ARCH_BLOOM:
  10366. return LLAMA_ROPE_TYPE_NONE;
  10367. // use what we call a normal RoPE, operating on pairs of consecutive head values
  10368. case LLM_ARCH_LLAMA:
  10369. case LLM_ARCH_BAICHUAN:
  10370. case LLM_ARCH_STARCODER:
  10371. case LLM_ARCH_PLAMO:
  10372. case LLM_ARCH_CODESHELL:
  10373. case LLM_ARCH_ORION:
  10374. case LLM_ARCH_INTERNLM2:
  10375. case LLM_ARCH_MINICPM:
  10376. return LLAMA_ROPE_TYPE_NORM;
  10377. // the pairs of head values are offset by n_rot/2
  10378. case LLM_ARCH_FALCON:
  10379. case LLM_ARCH_PERSIMMON:
  10380. case LLM_ARCH_BERT:
  10381. case LLM_ARCH_NOMIC_BERT:
  10382. case LLM_ARCH_STABLELM:
  10383. case LLM_ARCH_QWEN:
  10384. case LLM_ARCH_QWEN2:
  10385. case LLM_ARCH_PHI2:
  10386. case LLM_ARCH_GEMMA:
  10387. case LLM_ARCH_STARCODER2:
  10388. return LLAMA_ROPE_TYPE_NEOX;
  10389. // all model arches should be listed explicitly here
  10390. case LLM_ARCH_UNKNOWN:
  10391. GGML_ASSERT(false && "unknown architecture");
  10392. break;
  10393. }
  10394. return LLAMA_ROPE_TYPE_NONE;
  10395. }
  10396. int32_t llama_n_vocab(const struct llama_model * model) {
  10397. return model->vocab.id_to_token.size();
  10398. }
  10399. int32_t llama_n_ctx_train(const struct llama_model * model) {
  10400. return model->hparams.n_ctx_train;
  10401. }
  10402. int32_t llama_n_embd(const struct llama_model * model) {
  10403. return model->hparams.n_embd;
  10404. }
  10405. float llama_rope_freq_scale_train(const struct llama_model * model) {
  10406. return model->hparams.rope_freq_scale_train;
  10407. }
  10408. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  10409. const auto & it = model->gguf_kv.find(key);
  10410. if (it == model->gguf_kv.end()) {
  10411. if (buf_size > 0) {
  10412. buf[0] = '\0';
  10413. }
  10414. return -1;
  10415. }
  10416. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10417. }
  10418. int32_t llama_model_meta_count(const struct llama_model * model) {
  10419. return (int)model->gguf_kv.size();
  10420. }
  10421. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  10422. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10423. if (buf_size > 0) {
  10424. buf[0] = '\0';
  10425. }
  10426. return -1;
  10427. }
  10428. auto it = model->gguf_kv.begin();
  10429. std::advance(it, i);
  10430. return snprintf(buf, buf_size, "%s", it->first.c_str());
  10431. }
  10432. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  10433. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10434. if (buf_size > 0) {
  10435. buf[0] = '\0';
  10436. }
  10437. return -1;
  10438. }
  10439. auto it = model->gguf_kv.begin();
  10440. std::advance(it, i);
  10441. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10442. }
  10443. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  10444. return snprintf(buf, buf_size, "%s %s %s",
  10445. llama_model_arch_name(model->arch),
  10446. llama_model_type_name(model->type),
  10447. llama_model_ftype_name(model->ftype).c_str());
  10448. }
  10449. uint64_t llama_model_size(const struct llama_model * model) {
  10450. uint64_t size = 0;
  10451. for (const auto & it : model->tensors_by_name) {
  10452. size += ggml_nbytes(it.second);
  10453. }
  10454. return size;
  10455. }
  10456. uint64_t llama_model_n_params(const struct llama_model * model) {
  10457. uint64_t nparams = 0;
  10458. for (const auto & it : model->tensors_by_name) {
  10459. nparams += ggml_nelements(it.second);
  10460. }
  10461. return nparams;
  10462. }
  10463. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  10464. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  10465. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  10466. return it.first == name;
  10467. });
  10468. if (it == model->tensors_by_name.end()) {
  10469. return nullptr;
  10470. }
  10471. return it->second;
  10472. }
  10473. uint32_t llama_model_quantize(
  10474. const char * fname_inp,
  10475. const char * fname_out,
  10476. const llama_model_quantize_params * params) {
  10477. try {
  10478. llama_model_quantize_internal(fname_inp, fname_out, params);
  10479. return 0;
  10480. } catch (const std::exception & err) {
  10481. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  10482. return 1;
  10483. }
  10484. }
  10485. 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) {
  10486. try {
  10487. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  10488. } catch (const std::exception & err) {
  10489. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  10490. return 1;
  10491. }
  10492. }
  10493. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  10494. struct llama_kv_cache_view result = {
  10495. /*.n_cells = */ 0,
  10496. /*.n_max_seq = */ n_max_seq,
  10497. /*.token_count = */ 0,
  10498. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  10499. /*.max_contiguous = */ 0,
  10500. /*.max_contiguous_idx = */ -1,
  10501. /*.cells = */ nullptr,
  10502. /*.cells_sequences = */ nullptr,
  10503. };
  10504. return result;
  10505. }
  10506. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  10507. if (view->cells != nullptr) {
  10508. free(view->cells);
  10509. view->cells = nullptr;
  10510. }
  10511. if (view->cells_sequences != nullptr) {
  10512. free(view->cells_sequences);
  10513. view->cells_sequences = nullptr;
  10514. }
  10515. }
  10516. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  10517. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  10518. view->n_cells = int32_t(ctx->kv_self.size);
  10519. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  10520. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  10521. view->cells = (struct llama_kv_cache_view_cell *)p;
  10522. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  10523. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  10524. view->cells_sequences = (llama_seq_id *)p;
  10525. }
  10526. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  10527. llama_kv_cache_view_cell * c_curr = view->cells;
  10528. llama_seq_id * cs_curr = view->cells_sequences;
  10529. int32_t used_cells = 0;
  10530. int32_t token_count = 0;
  10531. int32_t curr_contig_idx = -1;
  10532. uint32_t max_contig = 0;
  10533. int32_t max_contig_idx = -1;
  10534. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10535. const size_t curr_size = kv_cells[i].seq_id.size();
  10536. token_count += curr_size;
  10537. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10538. if (curr_size > 0) {
  10539. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10540. max_contig = i - curr_contig_idx;
  10541. max_contig_idx = curr_contig_idx;
  10542. }
  10543. curr_contig_idx = -1;
  10544. } else if (curr_contig_idx < 0) {
  10545. curr_contig_idx = i;
  10546. }
  10547. int seq_idx = 0;
  10548. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10549. if (seq_idx >= view->n_max_seq) {
  10550. break;
  10551. }
  10552. cs_curr[seq_idx] = it;
  10553. seq_idx++;
  10554. }
  10555. if (seq_idx != 0) {
  10556. used_cells++;
  10557. }
  10558. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10559. cs_curr[seq_idx] = -1;
  10560. }
  10561. }
  10562. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10563. max_contig_idx = curr_contig_idx;
  10564. max_contig = kv_cells.size() - curr_contig_idx;
  10565. }
  10566. view->max_contiguous = max_contig;
  10567. view->max_contiguous_idx = max_contig_idx;
  10568. view->token_count = token_count;
  10569. view->used_cells = used_cells;
  10570. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10571. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10572. __func__, ctx->kv_self.used, used_cells);
  10573. }
  10574. }
  10575. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10576. int result = 0;
  10577. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10578. result += ctx->kv_self.cells[i].seq_id.size();
  10579. }
  10580. return result;
  10581. }
  10582. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10583. return ctx->kv_self.used;
  10584. }
  10585. void llama_kv_cache_clear(struct llama_context * ctx) {
  10586. llama_kv_cache_clear(ctx->kv_self);
  10587. }
  10588. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10589. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10590. }
  10591. 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) {
  10592. if (seq_id_src == seq_id_dst) {
  10593. return;
  10594. }
  10595. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10596. }
  10597. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10598. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10599. }
  10600. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10601. if (delta == 0) {
  10602. return;
  10603. }
  10604. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  10605. }
  10606. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10607. if (d == 1) {
  10608. return;
  10609. }
  10610. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10611. }
  10612. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  10613. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  10614. }
  10615. void llama_kv_cache_defrag(struct llama_context * ctx) {
  10616. llama_kv_cache_defrag(ctx->kv_self);
  10617. }
  10618. void llama_kv_cache_update(struct llama_context * ctx) {
  10619. llama_kv_cache_update_internal(*ctx);
  10620. }
  10621. // Returns the *maximum* size of the state
  10622. size_t llama_get_state_size(const struct llama_context * ctx) {
  10623. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10624. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10625. const size_t s_rng_size = sizeof(size_t);
  10626. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10627. const size_t s_logits_size = sizeof(size_t);
  10628. // assume worst case for logits although only currently set ones are serialized
  10629. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10630. const size_t s_embedding_size = sizeof(size_t);
  10631. const size_t s_embedding = ctx->embd.capacity() * sizeof(float);
  10632. const size_t s_kv_buf_size = sizeof(size_t);
  10633. const size_t s_kv_head = sizeof(uint32_t);
  10634. const size_t s_kv_size = sizeof(uint32_t);
  10635. const size_t s_kv_used = sizeof(uint32_t);
  10636. const size_t s_kv = ctx->kv_self.total_size();
  10637. // TODO: assume the max is more than 1 seq_id per KV cell
  10638. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + sizeof(llama_seq_id);
  10639. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  10640. const size_t s_total = (
  10641. + s_rng_size
  10642. + s_rng
  10643. + s_logits_size
  10644. + s_logits
  10645. + s_embedding_size
  10646. + s_embedding
  10647. + s_kv_buf_size
  10648. + s_kv_head
  10649. + s_kv_size
  10650. + s_kv_used
  10651. + s_kv
  10652. + s_kv_cells
  10653. );
  10654. return s_total;
  10655. }
  10656. // llama_context_data
  10657. struct llama_data_context {
  10658. virtual void write(const void * src, size_t size) = 0;
  10659. virtual size_t get_size_written() = 0;
  10660. virtual ~llama_data_context() = default;
  10661. };
  10662. struct llama_data_buffer_context : llama_data_context {
  10663. uint8_t * ptr;
  10664. size_t size_written = 0;
  10665. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10666. void write(const void * src, size_t size) override {
  10667. memcpy(ptr, src, size);
  10668. ptr += size;
  10669. size_written += size;
  10670. }
  10671. size_t get_size_written() override {
  10672. return size_written;
  10673. }
  10674. };
  10675. struct llama_data_file_context : llama_data_context {
  10676. llama_file * file;
  10677. size_t size_written = 0;
  10678. llama_data_file_context(llama_file * f) : file(f) {}
  10679. void write(const void * src, size_t size) override {
  10680. file->write_raw(src, size);
  10681. size_written += size;
  10682. }
  10683. size_t get_size_written() override {
  10684. return size_written;
  10685. }
  10686. };
  10687. /** copy state data into either a buffer or file depending on the passed in context
  10688. *
  10689. * file context:
  10690. * llama_file file("/path", "wb");
  10691. * llama_data_file_context data_ctx(&file);
  10692. * llama_copy_state_data(ctx, &data_ctx);
  10693. *
  10694. * buffer context:
  10695. * std::vector<uint8_t> buf(max_size, 0);
  10696. * llama_data_buffer_context data_ctx(&buf.data());
  10697. * llama_copy_state_data(ctx, &data_ctx);
  10698. *
  10699. */
  10700. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10701. // copy rng
  10702. {
  10703. std::ostringstream rng_ss;
  10704. rng_ss << ctx->rng;
  10705. const std::string & rng_str = rng_ss.str();
  10706. const size_t rng_size = rng_str.size();
  10707. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10708. data_ctx->write(&rng_size, sizeof(rng_size));
  10709. data_ctx->write(rng_str.data(), rng_size);
  10710. }
  10711. // copy logits
  10712. {
  10713. const size_t logits_size = ctx->logits.size();
  10714. data_ctx->write(&logits_size, sizeof(logits_size));
  10715. if (logits_size) {
  10716. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10717. }
  10718. }
  10719. // copy embeddings
  10720. {
  10721. const size_t embeddings_size = ctx->embd.size();
  10722. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  10723. if (embeddings_size) {
  10724. data_ctx->write(ctx->embd.data(), embeddings_size * sizeof(float));
  10725. }
  10726. }
  10727. // copy kv cache
  10728. {
  10729. const auto & kv_self = ctx->kv_self;
  10730. const auto & hparams = ctx->model.hparams;
  10731. const uint32_t n_layer = hparams.n_layer;
  10732. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10733. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10734. const size_t kv_buf_size = kv_self.total_size();
  10735. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  10736. const uint32_t kv_size = kv_self.size;
  10737. const uint32_t kv_used = kv_self.used;
  10738. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10739. data_ctx->write(&kv_head, sizeof(kv_head));
  10740. data_ctx->write(&kv_size, sizeof(kv_size));
  10741. data_ctx->write(&kv_used, sizeof(kv_used));
  10742. if (kv_buf_size) {
  10743. std::vector<uint8_t> tmp_buf;
  10744. for (int il = 0; il < (int) n_layer; ++il) {
  10745. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10746. tmp_buf.resize(k_size);
  10747. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10748. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10749. // v is not contiguous, copy row by row
  10750. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10751. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  10752. tmp_buf.resize(v_row_size);
  10753. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10754. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10755. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10756. }
  10757. }
  10758. }
  10759. for (uint32_t i = 0; i < kv_head; ++i) {
  10760. const auto & cell = kv_self.cells[i];
  10761. const llama_pos pos = cell.pos;
  10762. const size_t seq_id_size = cell.seq_id.size();
  10763. data_ctx->write(&pos, sizeof(pos));
  10764. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10765. for (auto seq_id : cell.seq_id) {
  10766. data_ctx->write(&seq_id, sizeof(seq_id));
  10767. }
  10768. }
  10769. }
  10770. }
  10771. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10772. llama_data_buffer_context data_ctx(dst);
  10773. llama_copy_state_data_internal(ctx, &data_ctx);
  10774. return data_ctx.get_size_written();
  10775. }
  10776. // Sets the state reading from the specified source address
  10777. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  10778. const uint8_t * inp = src;
  10779. // set rng
  10780. {
  10781. size_t rng_size;
  10782. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10783. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10784. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  10785. std::istringstream rng_ss(rng_str);
  10786. rng_ss >> ctx->rng;
  10787. GGML_ASSERT(!rng_ss.fail());
  10788. }
  10789. // set logits
  10790. {
  10791. size_t logits_size;
  10792. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10793. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10794. if (logits_size) {
  10795. ctx->logits.resize(logits_size);
  10796. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10797. inp += logits_size * sizeof(float);
  10798. }
  10799. }
  10800. // set embeddings
  10801. {
  10802. size_t embeddings_size;
  10803. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  10804. GGML_ASSERT(ctx->embd.capacity() == embeddings_size);
  10805. if (embeddings_size) {
  10806. ctx->embd.resize(embeddings_size);
  10807. memcpy(ctx->embd.data(), inp, embeddings_size * sizeof(float));
  10808. inp += embeddings_size * sizeof(float);
  10809. }
  10810. }
  10811. // set kv cache
  10812. {
  10813. const auto & kv_self = ctx->kv_self;
  10814. const auto & hparams = ctx->model.hparams;
  10815. const uint32_t n_layer = hparams.n_layer;
  10816. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10817. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10818. size_t kv_buf_size;
  10819. uint32_t kv_head;
  10820. uint32_t kv_size;
  10821. uint32_t kv_used;
  10822. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10823. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10824. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10825. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10826. if (kv_buf_size) {
  10827. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10828. for (int il = 0; il < (int) n_layer; ++il) {
  10829. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10830. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10831. inp += k_size;
  10832. // v is not contiguous, copy row by row
  10833. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10834. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  10835. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10836. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10837. inp += v_row_size;
  10838. }
  10839. }
  10840. }
  10841. GGML_ASSERT(kv_self.size == kv_size);
  10842. ctx->kv_self.head = kv_head;
  10843. ctx->kv_self.size = kv_size;
  10844. ctx->kv_self.used = kv_used;
  10845. ctx->kv_self.cells.resize(kv_size);
  10846. for (uint32_t i = 0; i < kv_head; ++i) {
  10847. llama_pos pos;
  10848. size_t seq_id_size;
  10849. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10850. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10851. ctx->kv_self.cells[i].pos = pos;
  10852. llama_seq_id seq_id;
  10853. for (size_t j = 0; j < seq_id_size; ++j) {
  10854. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10855. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10856. }
  10857. }
  10858. for (uint32_t i = kv_head; i < kv_size; ++i) {
  10859. ctx->kv_self.cells[i].pos = -1;
  10860. ctx->kv_self.cells[i].seq_id.clear();
  10861. }
  10862. }
  10863. const size_t nread = inp - src;
  10864. const size_t max_size = llama_get_state_size(ctx);
  10865. GGML_ASSERT(nread <= max_size);
  10866. return nread;
  10867. }
  10868. 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) {
  10869. llama_file file(path_session, "rb");
  10870. // sanity checks
  10871. {
  10872. const uint32_t magic = file.read_u32();
  10873. const uint32_t version = file.read_u32();
  10874. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10875. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10876. return false;
  10877. }
  10878. llama_hparams session_hparams;
  10879. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10880. if (session_hparams != ctx->model.hparams) {
  10881. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10882. return false;
  10883. }
  10884. }
  10885. // load the prompt
  10886. {
  10887. const uint32_t n_token_count = file.read_u32();
  10888. if (n_token_count > n_token_capacity) {
  10889. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10890. return false;
  10891. }
  10892. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10893. *n_token_count_out = n_token_count;
  10894. }
  10895. // restore the context state
  10896. {
  10897. const size_t n_state_size_cur = file.size - file.tell();
  10898. const size_t n_state_size_max = llama_get_state_size(ctx);
  10899. if (n_state_size_cur > n_state_size_max) {
  10900. 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);
  10901. return false;
  10902. }
  10903. std::vector<uint8_t> state_data(n_state_size_max);
  10904. file.read_raw(state_data.data(), n_state_size_cur);
  10905. llama_set_state_data(ctx, state_data.data());
  10906. }
  10907. return true;
  10908. }
  10909. 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) {
  10910. try {
  10911. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10912. } catch (const std::exception & err) {
  10913. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10914. return false;
  10915. }
  10916. }
  10917. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10918. llama_file file(path_session, "wb");
  10919. file.write_u32(LLAMA_SESSION_MAGIC);
  10920. file.write_u32(LLAMA_SESSION_VERSION);
  10921. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10922. // save the prompt
  10923. file.write_u32((uint32_t) n_token_count);
  10924. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10925. // save the context state using stream saving
  10926. llama_data_file_context data_ctx(&file);
  10927. llama_copy_state_data_internal(ctx, &data_ctx);
  10928. return true;
  10929. }
  10930. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10931. ctx->cparams.n_threads = n_threads;
  10932. ctx->cparams.n_threads_batch = n_threads_batch;
  10933. }
  10934. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  10935. ctx->abort_callback = abort_callback;
  10936. ctx->abort_callback_data = abort_callback_data;
  10937. }
  10938. struct llama_batch llama_batch_get_one(
  10939. llama_token * tokens,
  10940. int32_t n_tokens,
  10941. llama_pos pos_0,
  10942. llama_seq_id seq_id) {
  10943. return {
  10944. /*n_tokens =*/ n_tokens,
  10945. /*tokens =*/ tokens,
  10946. /*embd =*/ nullptr,
  10947. /*pos =*/ nullptr,
  10948. /*n_seq_id =*/ nullptr,
  10949. /*seq_id =*/ nullptr,
  10950. /*logits =*/ nullptr,
  10951. /*all_pos_0 =*/ pos_0,
  10952. /*all_pos_1 =*/ 1,
  10953. /*all_seq_id =*/ seq_id,
  10954. };
  10955. }
  10956. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10957. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10958. if (embd) {
  10959. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10960. } else {
  10961. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10962. }
  10963. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10964. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10965. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10966. for (int i = 0; i < n_tokens_alloc; ++i) {
  10967. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10968. }
  10969. batch.seq_id[n_tokens_alloc] = nullptr;
  10970. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10971. return batch;
  10972. }
  10973. void llama_batch_free(struct llama_batch batch) {
  10974. if (batch.token) free(batch.token);
  10975. if (batch.embd) free(batch.embd);
  10976. if (batch.pos) free(batch.pos);
  10977. if (batch.n_seq_id) free(batch.n_seq_id);
  10978. if (batch.seq_id) {
  10979. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10980. free(batch.seq_id[i]);
  10981. }
  10982. free(batch.seq_id);
  10983. }
  10984. if (batch.logits) free(batch.logits);
  10985. }
  10986. int32_t llama_decode(
  10987. struct llama_context * ctx,
  10988. struct llama_batch batch) {
  10989. const int ret = llama_decode_internal(*ctx, batch);
  10990. if (ret < 0) {
  10991. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10992. }
  10993. return ret;
  10994. }
  10995. float * llama_get_logits(struct llama_context * ctx) {
  10996. return ctx->logits.data();
  10997. }
  10998. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10999. assert(ctx->logits_valid.at(i));
  11000. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  11001. }
  11002. float * llama_get_embeddings(struct llama_context * ctx) {
  11003. return ctx->embd.data();
  11004. }
  11005. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  11006. return ctx->embd.data() + i*ctx->model.hparams.n_embd;
  11007. }
  11008. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  11009. auto it = ctx->embd_seq.find(seq_id);
  11010. if (it == ctx->embd_seq.end()) {
  11011. return nullptr;
  11012. }
  11013. return it->second.data();
  11014. }
  11015. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  11016. return model->vocab.id_to_token[token].text.c_str();
  11017. }
  11018. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  11019. return model->vocab.id_to_token[token].score;
  11020. }
  11021. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  11022. return model->vocab.id_to_token[token].type;
  11023. }
  11024. llama_token llama_token_bos(const struct llama_model * model) {
  11025. return model->vocab.special_bos_id;
  11026. }
  11027. llama_token llama_token_eos(const struct llama_model * model) {
  11028. return model->vocab.special_eos_id;
  11029. }
  11030. llama_token llama_token_nl(const struct llama_model * model) {
  11031. return model->vocab.linefeed_id;
  11032. }
  11033. int32_t llama_add_bos_token(const struct llama_model * model) {
  11034. return model->vocab.special_add_bos;
  11035. }
  11036. int32_t llama_add_eos_token(const struct llama_model * model) {
  11037. return model->vocab.special_add_eos;
  11038. }
  11039. llama_token llama_token_prefix(const struct llama_model * model) {
  11040. return model->vocab.special_prefix_id;
  11041. }
  11042. llama_token llama_token_middle(const struct llama_model * model) {
  11043. return model->vocab.special_middle_id;
  11044. }
  11045. llama_token llama_token_suffix(const struct llama_model * model) {
  11046. return model->vocab.special_suffix_id;
  11047. }
  11048. llama_token llama_token_eot(const struct llama_model * model) {
  11049. return model->vocab.special_eot_id;
  11050. }
  11051. int32_t llama_tokenize(
  11052. const struct llama_model * model,
  11053. const char * text,
  11054. int32_t text_len,
  11055. llama_token * tokens,
  11056. int32_t n_max_tokens,
  11057. bool add_bos,
  11058. bool special) {
  11059. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  11060. if (n_max_tokens < (int) res.size()) {
  11061. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  11062. return -((int) res.size());
  11063. }
  11064. for (size_t i = 0; i < res.size(); i++) {
  11065. tokens[i] = res[i];
  11066. }
  11067. return res.size();
  11068. }
  11069. static std::string llama_decode_text(const std::string & text) {
  11070. std::string decoded_text;
  11071. auto unicode_sequences = codepoints_from_utf8(text);
  11072. for (auto& unicode_sequence : unicode_sequences) {
  11073. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  11074. }
  11075. return decoded_text;
  11076. }
  11077. // does not write null-terminator to buf
  11078. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  11079. if (0 <= token && token < llama_n_vocab(model)) {
  11080. switch (llama_vocab_get_type(model->vocab)) {
  11081. case LLAMA_VOCAB_TYPE_WPM:
  11082. case LLAMA_VOCAB_TYPE_SPM: {
  11083. // NOTE: we accept all unsupported token types,
  11084. // suppressing them like CONTROL tokens.
  11085. if (llama_is_normal_token(model->vocab, token)) {
  11086. std::string result = model->vocab.id_to_token[token].text;
  11087. llama_unescape_whitespace(result);
  11088. if (length < (int) result.length()) {
  11089. return -(int) result.length();
  11090. }
  11091. memcpy(buf, result.c_str(), result.length());
  11092. return result.length();
  11093. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11094. std::string result = model->vocab.id_to_token[token].text;
  11095. if (length < (int) result.length()) {
  11096. return -result.length();
  11097. }
  11098. memcpy(buf, result.c_str(), result.length());
  11099. return result.length();
  11100. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  11101. if (length < 3) {
  11102. return -3;
  11103. }
  11104. memcpy(buf, "\xe2\x96\x85", 3);
  11105. return 3;
  11106. } else if (llama_is_control_token(model->vocab, token)) {
  11107. ;
  11108. } else if (llama_is_byte_token(model->vocab, token)) {
  11109. if (length < 1) {
  11110. return -1;
  11111. }
  11112. buf[0] = llama_token_to_byte(model->vocab, token);
  11113. return 1;
  11114. }
  11115. break;
  11116. }
  11117. case LLAMA_VOCAB_TYPE_BPE: {
  11118. // NOTE: we accept all unsupported token types,
  11119. // suppressing them like CONTROL tokens.
  11120. if (llama_is_normal_token(model->vocab, token)) {
  11121. std::string result = model->vocab.id_to_token[token].text;
  11122. result = llama_decode_text(result);
  11123. if (length < (int) result.length()) {
  11124. return -(int) result.length();
  11125. }
  11126. memcpy(buf, result.c_str(), result.length());
  11127. return result.length();
  11128. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11129. std::string result = model->vocab.id_to_token[token].text;
  11130. if (length < (int) result.length()) {
  11131. return -result.length();
  11132. }
  11133. memcpy(buf, result.c_str(), result.length());
  11134. return result.length();
  11135. } else if (llama_is_control_token(model->vocab, token)) {
  11136. ;
  11137. }
  11138. break;
  11139. }
  11140. default:
  11141. GGML_ASSERT(false);
  11142. }
  11143. }
  11144. return 0;
  11145. }
  11146. // trim whitespace from the beginning and end of a string
  11147. static std::string trim(const std::string & str) {
  11148. size_t start = 0;
  11149. size_t end = str.size();
  11150. while (start < end && isspace(str[start])) {
  11151. start += 1;
  11152. }
  11153. while (end > start && isspace(str[end - 1])) {
  11154. end -= 1;
  11155. }
  11156. return str.substr(start, end - start);
  11157. }
  11158. // Simple version of "llama_apply_chat_template" that only works with strings
  11159. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  11160. static int32_t llama_chat_apply_template_internal(
  11161. const std::string & tmpl,
  11162. const std::vector<const llama_chat_message *> & chat,
  11163. std::string & dest, bool add_ass) {
  11164. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  11165. std::stringstream ss;
  11166. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  11167. // chatml template
  11168. for (auto message : chat) {
  11169. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  11170. }
  11171. if (add_ass) {
  11172. ss << "<|im_start|>assistant\n";
  11173. }
  11174. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  11175. // llama2 template and its variants
  11176. // [variant] support system message
  11177. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  11178. // [variant] space before + after response
  11179. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  11180. // [variant] add BOS inside history
  11181. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  11182. // [variant] trim spaces from the input message
  11183. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  11184. // construct the prompt
  11185. bool is_inside_turn = true; // skip BOS at the beginning
  11186. ss << "[INST] ";
  11187. for (auto message : chat) {
  11188. std::string content = strip_message ? trim(message->content) : message->content;
  11189. std::string role(message->role);
  11190. if (!is_inside_turn) {
  11191. is_inside_turn = true;
  11192. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  11193. }
  11194. if (role == "system") {
  11195. if (support_system_message) {
  11196. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  11197. } else {
  11198. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  11199. ss << content << "\n";
  11200. }
  11201. } else if (role == "user") {
  11202. ss << content << " [/INST]";
  11203. } else {
  11204. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  11205. is_inside_turn = false;
  11206. }
  11207. }
  11208. // llama2 templates seem to not care about "add_generation_prompt"
  11209. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  11210. // zephyr template
  11211. for (auto message : chat) {
  11212. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  11213. }
  11214. if (add_ass) {
  11215. ss << "<|assistant|>\n";
  11216. }
  11217. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  11218. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  11219. for (auto message : chat) {
  11220. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  11221. ss << bos << message->role << "\n" << message->content << "</s>\n";
  11222. }
  11223. if (add_ass) {
  11224. ss << "<s>assistant\n";
  11225. }
  11226. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  11227. // google/gemma-7b-it
  11228. std::string system_prompt = "";
  11229. for (auto message : chat) {
  11230. std::string role(message->role);
  11231. if (role == "system") {
  11232. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  11233. system_prompt = trim(message->content);
  11234. continue;
  11235. }
  11236. // in gemma, "assistant" is "model"
  11237. role = role == "assistant" ? "model" : message->role;
  11238. ss << "<start_of_turn>" << role << "\n";
  11239. if (!system_prompt.empty() && role != "model") {
  11240. ss << system_prompt << "\n\n";
  11241. system_prompt = "";
  11242. }
  11243. ss << trim(message->content) << "<end_of_turn>\n";
  11244. }
  11245. if (add_ass) {
  11246. ss << "<start_of_turn>model\n";
  11247. }
  11248. } else {
  11249. // template not supported
  11250. return -1;
  11251. }
  11252. dest = ss.str();
  11253. return dest.size();
  11254. }
  11255. LLAMA_API int32_t llama_chat_apply_template(
  11256. const struct llama_model * model,
  11257. const char * tmpl,
  11258. const struct llama_chat_message * chat,
  11259. size_t n_msg,
  11260. bool add_ass,
  11261. char * buf,
  11262. int32_t length) {
  11263. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  11264. if (tmpl == nullptr) {
  11265. GGML_ASSERT(model != nullptr);
  11266. // load template from model
  11267. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  11268. std::string template_key = "tokenizer.chat_template";
  11269. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  11270. if (res < 0) {
  11271. // worst case: there is no information about template, we will use chatml by default
  11272. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  11273. } else {
  11274. curr_tmpl = std::string(model_template.data(), model_template.size());
  11275. }
  11276. }
  11277. // format the chat to string
  11278. std::vector<const llama_chat_message *> chat_vec;
  11279. chat_vec.resize(n_msg);
  11280. for (size_t i = 0; i < n_msg; i++) {
  11281. chat_vec[i] = &chat[i];
  11282. }
  11283. std::string formatted_chat;
  11284. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  11285. if (res < 0) {
  11286. return res;
  11287. }
  11288. strncpy(buf, formatted_chat.c_str(), length);
  11289. return res;
  11290. }
  11291. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  11292. struct llama_timings result = {
  11293. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  11294. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  11295. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  11296. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  11297. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  11298. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  11299. /*.n_sample =*/ std::max(1, ctx->n_sample),
  11300. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  11301. /*.n_eval =*/ std::max(1, ctx->n_eval),
  11302. };
  11303. return result;
  11304. }
  11305. void llama_print_timings(struct llama_context * ctx) {
  11306. const llama_timings timings = llama_get_timings(ctx);
  11307. LLAMA_LOG_INFO("\n");
  11308. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  11309. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11310. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  11311. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  11312. __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);
  11313. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11314. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  11315. 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));
  11316. }
  11317. void llama_reset_timings(struct llama_context * ctx) {
  11318. ctx->t_start_us = ggml_time_us();
  11319. ctx->t_sample_us = ctx->n_sample = 0;
  11320. ctx->t_eval_us = ctx->n_eval = 0;
  11321. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  11322. }
  11323. const char * llama_print_system_info(void) {
  11324. static std::string s;
  11325. s = "";
  11326. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  11327. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  11328. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  11329. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  11330. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  11331. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  11332. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  11333. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  11334. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  11335. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  11336. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  11337. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  11338. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  11339. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  11340. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  11341. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  11342. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  11343. return s.c_str();
  11344. }
  11345. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  11346. fprintf(stream, "\n");
  11347. fprintf(stream, "###########\n");
  11348. fprintf(stream, "# Timings #\n");
  11349. fprintf(stream, "###########\n");
  11350. fprintf(stream, "\n");
  11351. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  11352. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  11353. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  11354. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  11355. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  11356. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  11357. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  11358. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  11359. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  11360. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  11361. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  11362. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  11363. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  11364. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  11365. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  11366. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  11367. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  11368. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  11369. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  11370. }
  11371. // For internal test use
  11372. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  11373. struct llama_context * ctx
  11374. ) {
  11375. return ctx->model.tensors_by_name;
  11376. }
  11377. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  11378. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  11379. g_state.log_callback_user_data = user_data;
  11380. #ifdef GGML_USE_METAL
  11381. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  11382. #endif
  11383. }
  11384. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  11385. va_list args_copy;
  11386. va_copy(args_copy, args);
  11387. char buffer[128];
  11388. int len = vsnprintf(buffer, 128, format, args);
  11389. if (len < 128) {
  11390. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  11391. } else {
  11392. char* buffer2 = new char[len+1];
  11393. vsnprintf(buffer2, len+1, format, args_copy);
  11394. buffer2[len] = 0;
  11395. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  11396. delete[] buffer2;
  11397. }
  11398. va_end(args_copy);
  11399. }
  11400. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  11401. va_list args;
  11402. va_start(args, format);
  11403. llama_log_internal_v(level, format, args);
  11404. va_end(args);
  11405. }
  11406. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  11407. (void) level;
  11408. (void) user_data;
  11409. fputs(text, stderr);
  11410. fflush(stderr);
  11411. }