llama.cpp 506 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <forward_list>
  65. #include <fstream>
  66. #include <functional>
  67. #include <initializer_list>
  68. #include <map>
  69. #include <memory>
  70. #include <mutex>
  71. #include <numeric>
  72. #include <queue>
  73. #include <random>
  74. #include <regex>
  75. #include <set>
  76. #include <sstream>
  77. #include <thread>
  78. #include <type_traits>
  79. #include <unordered_map>
  80. #if defined(_MSC_VER)
  81. #pragma warning(disable: 4244 4267) // possible loss of data
  82. #endif
  83. #ifdef __GNUC__
  84. #ifdef __MINGW32__
  85. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  86. #else
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  88. #endif
  89. #else
  90. #define LLAMA_ATTRIBUTE_FORMAT(...)
  91. #endif
  92. #define LLAMA_MAX_NODES 8192
  93. #define LLAMA_MAX_EXPERTS 8
  94. //
  95. // logging
  96. //
  97. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  98. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  99. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  100. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  101. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  102. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  103. //
  104. // helpers
  105. //
  106. static size_t utf8_len(char src) {
  107. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  108. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  109. return lookup[highbits];
  110. }
  111. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  112. std::string result;
  113. for (size_t pos = 0; ; pos += search.length()) {
  114. auto new_pos = s.find(search, pos);
  115. if (new_pos == std::string::npos) {
  116. result += s.substr(pos, s.size() - pos);
  117. break;
  118. }
  119. result += s.substr(pos, new_pos - pos) + replace;
  120. pos = new_pos;
  121. }
  122. s = std::move(result);
  123. }
  124. static bool is_float_close(float a, float b, float abs_tol) {
  125. // Check for non-negative tolerance
  126. if (abs_tol < 0.0) {
  127. throw std::invalid_argument("Tolerance must be non-negative");
  128. }
  129. // Exact equality check
  130. if (a == b) {
  131. return true;
  132. }
  133. // Check for infinities
  134. if (std::isinf(a) || std::isinf(b)) {
  135. return false;
  136. }
  137. // Regular comparison using the provided absolute tolerance
  138. return std::fabs(b - a) <= abs_tol;
  139. }
  140. static void zeros(std::ofstream & file, size_t n) {
  141. char zero = 0;
  142. for (size_t i = 0; i < n; ++i) {
  143. file.write(&zero, 1);
  144. }
  145. }
  146. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  147. static std::string format(const char * fmt, ...) {
  148. va_list ap;
  149. va_list ap2;
  150. va_start(ap, fmt);
  151. va_copy(ap2, ap);
  152. int size = vsnprintf(NULL, 0, fmt, ap);
  153. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  154. std::vector<char> buf(size + 1);
  155. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  156. GGML_ASSERT(size2 == size);
  157. va_end(ap2);
  158. va_end(ap);
  159. return std::string(buf.data(), size);
  160. }
  161. //
  162. // gguf constants (sync with gguf.py)
  163. //
  164. enum llm_arch {
  165. LLM_ARCH_LLAMA,
  166. LLM_ARCH_FALCON,
  167. LLM_ARCH_BAICHUAN,
  168. LLM_ARCH_GPT2,
  169. LLM_ARCH_GPTJ,
  170. LLM_ARCH_GPTNEOX,
  171. LLM_ARCH_MPT,
  172. LLM_ARCH_STARCODER,
  173. LLM_ARCH_PERSIMMON,
  174. LLM_ARCH_REFACT,
  175. LLM_ARCH_BERT,
  176. LLM_ARCH_NOMIC_BERT,
  177. LLM_ARCH_BLOOM,
  178. LLM_ARCH_STABLELM,
  179. LLM_ARCH_QWEN,
  180. LLM_ARCH_QWEN2,
  181. LLM_ARCH_PHI2,
  182. LLM_ARCH_PLAMO,
  183. LLM_ARCH_CODESHELL,
  184. LLM_ARCH_ORION,
  185. LLM_ARCH_INTERNLM2,
  186. LLM_ARCH_MINICPM,
  187. LLM_ARCH_GEMMA,
  188. LLM_ARCH_UNKNOWN,
  189. };
  190. static std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  191. { LLM_ARCH_LLAMA, "llama" },
  192. { LLM_ARCH_FALCON, "falcon" },
  193. { LLM_ARCH_GPT2, "gpt2" },
  194. { LLM_ARCH_GPTJ, "gptj" },
  195. { LLM_ARCH_GPTNEOX, "gptneox" },
  196. { LLM_ARCH_MPT, "mpt" },
  197. { LLM_ARCH_BAICHUAN, "baichuan" },
  198. { LLM_ARCH_STARCODER, "starcoder" },
  199. { LLM_ARCH_PERSIMMON, "persimmon" },
  200. { LLM_ARCH_REFACT, "refact" },
  201. { LLM_ARCH_BERT, "bert" },
  202. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  203. { LLM_ARCH_BLOOM, "bloom" },
  204. { LLM_ARCH_STABLELM, "stablelm" },
  205. { LLM_ARCH_QWEN, "qwen" },
  206. { LLM_ARCH_QWEN2, "qwen2" },
  207. { LLM_ARCH_PHI2, "phi2" },
  208. { LLM_ARCH_PLAMO, "plamo" },
  209. { LLM_ARCH_CODESHELL, "codeshell" },
  210. { LLM_ARCH_ORION, "orion" },
  211. { LLM_ARCH_INTERNLM2, "internlm2" },
  212. { LLM_ARCH_MINICPM, "minicpm" },
  213. { LLM_ARCH_GEMMA, "gemma" },
  214. };
  215. enum llm_kv {
  216. LLM_KV_GENERAL_ARCHITECTURE,
  217. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  218. LLM_KV_GENERAL_ALIGNMENT,
  219. LLM_KV_GENERAL_NAME,
  220. LLM_KV_GENERAL_AUTHOR,
  221. LLM_KV_GENERAL_URL,
  222. LLM_KV_GENERAL_DESCRIPTION,
  223. LLM_KV_GENERAL_LICENSE,
  224. LLM_KV_GENERAL_SOURCE_URL,
  225. LLM_KV_GENERAL_SOURCE_HF_REPO,
  226. LLM_KV_CONTEXT_LENGTH,
  227. LLM_KV_EMBEDDING_LENGTH,
  228. LLM_KV_BLOCK_COUNT,
  229. LLM_KV_FEED_FORWARD_LENGTH,
  230. LLM_KV_USE_PARALLEL_RESIDUAL,
  231. LLM_KV_TENSOR_DATA_LAYOUT,
  232. LLM_KV_EXPERT_COUNT,
  233. LLM_KV_EXPERT_USED_COUNT,
  234. LLM_KV_POOLING_TYPE,
  235. LLM_KV_ATTENTION_HEAD_COUNT,
  236. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  237. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  238. LLM_KV_ATTENTION_CLAMP_KQV,
  239. LLM_KV_ATTENTION_KEY_LENGTH,
  240. LLM_KV_ATTENTION_VALUE_LENGTH,
  241. LLM_KV_ATTENTION_LAYERNORM_EPS,
  242. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  243. LLM_KV_ATTENTION_CAUSAL,
  244. LLM_KV_ROPE_DIMENSION_COUNT,
  245. LLM_KV_ROPE_FREQ_BASE,
  246. LLM_KV_ROPE_SCALE_LINEAR,
  247. LLM_KV_ROPE_SCALING_TYPE,
  248. LLM_KV_ROPE_SCALING_FACTOR,
  249. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  250. LLM_KV_ROPE_SCALING_FINETUNED,
  251. LLM_KV_TOKENIZER_MODEL,
  252. LLM_KV_TOKENIZER_LIST,
  253. LLM_KV_TOKENIZER_TOKEN_TYPE,
  254. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  255. LLM_KV_TOKENIZER_SCORES,
  256. LLM_KV_TOKENIZER_MERGES,
  257. LLM_KV_TOKENIZER_BOS_ID,
  258. LLM_KV_TOKENIZER_EOS_ID,
  259. LLM_KV_TOKENIZER_UNK_ID,
  260. LLM_KV_TOKENIZER_SEP_ID,
  261. LLM_KV_TOKENIZER_PAD_ID,
  262. LLM_KV_TOKENIZER_ADD_BOS,
  263. LLM_KV_TOKENIZER_ADD_EOS,
  264. LLM_KV_TOKENIZER_ADD_PREFIX,
  265. LLM_KV_TOKENIZER_HF_JSON,
  266. LLM_KV_TOKENIZER_RWKV,
  267. };
  268. static std::map<llm_kv, const char *> LLM_KV_NAMES = {
  269. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  270. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  271. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  272. { LLM_KV_GENERAL_NAME, "general.name" },
  273. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  274. { LLM_KV_GENERAL_URL, "general.url" },
  275. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  276. { LLM_KV_GENERAL_LICENSE, "general.license" },
  277. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  278. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  279. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  280. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  281. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  282. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  283. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  284. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  285. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  286. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  287. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  288. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  289. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  290. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  291. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  292. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  293. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  294. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  295. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  296. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  297. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  298. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  299. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  300. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  301. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  302. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  303. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  304. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  305. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  306. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  307. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  308. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  309. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  310. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  311. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  312. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  313. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  314. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  315. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  316. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  317. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  318. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  319. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  320. };
  321. struct LLM_KV {
  322. LLM_KV(llm_arch arch) : arch(arch) {}
  323. llm_arch arch;
  324. std::string operator()(llm_kv kv) const {
  325. return ::format(LLM_KV_NAMES[kv], LLM_ARCH_NAMES[arch]);
  326. }
  327. };
  328. enum llm_tensor {
  329. LLM_TENSOR_TOKEN_EMBD,
  330. LLM_TENSOR_TOKEN_EMBD_NORM,
  331. LLM_TENSOR_TOKEN_TYPES,
  332. LLM_TENSOR_POS_EMBD,
  333. LLM_TENSOR_OUTPUT,
  334. LLM_TENSOR_OUTPUT_NORM,
  335. LLM_TENSOR_ROPE_FREQS,
  336. LLM_TENSOR_ATTN_Q,
  337. LLM_TENSOR_ATTN_K,
  338. LLM_TENSOR_ATTN_V,
  339. LLM_TENSOR_ATTN_QKV,
  340. LLM_TENSOR_ATTN_OUT,
  341. LLM_TENSOR_ATTN_NORM,
  342. LLM_TENSOR_ATTN_NORM_2,
  343. LLM_TENSOR_ATTN_OUT_NORM,
  344. LLM_TENSOR_ATTN_ROT_EMBD,
  345. LLM_TENSOR_FFN_GATE_INP,
  346. LLM_TENSOR_FFN_NORM,
  347. LLM_TENSOR_FFN_GATE,
  348. LLM_TENSOR_FFN_DOWN,
  349. LLM_TENSOR_FFN_UP,
  350. LLM_TENSOR_FFN_ACT,
  351. LLM_TENSOR_FFN_DOWN_EXP,
  352. LLM_TENSOR_FFN_GATE_EXP,
  353. LLM_TENSOR_FFN_UP_EXP,
  354. LLM_TENSOR_ATTN_Q_NORM,
  355. LLM_TENSOR_ATTN_K_NORM,
  356. LLM_TENSOR_LAYER_OUT_NORM,
  357. };
  358. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  359. {
  360. LLM_ARCH_LLAMA,
  361. {
  362. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  363. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  364. { LLM_TENSOR_OUTPUT, "output" },
  365. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  366. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  367. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  368. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  369. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  370. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  371. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  372. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  373. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  374. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  375. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  376. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  377. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  378. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  379. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  380. },
  381. },
  382. {
  383. LLM_ARCH_BAICHUAN,
  384. {
  385. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  386. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  387. { LLM_TENSOR_OUTPUT, "output" },
  388. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  389. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  390. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  391. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  392. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  393. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  394. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  395. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  396. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  397. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  398. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  399. },
  400. },
  401. {
  402. LLM_ARCH_FALCON,
  403. {
  404. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  405. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  406. { LLM_TENSOR_OUTPUT, "output" },
  407. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  408. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  409. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  410. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  411. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  412. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  413. },
  414. },
  415. {
  416. LLM_ARCH_GPT2,
  417. {
  418. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  419. { LLM_TENSOR_POS_EMBD, "position_embd" },
  420. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  421. { LLM_TENSOR_OUTPUT, "output" },
  422. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  423. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  424. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  425. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  426. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  427. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  428. },
  429. },
  430. {
  431. LLM_ARCH_GPTJ,
  432. {
  433. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  434. },
  435. },
  436. {
  437. LLM_ARCH_GPTNEOX,
  438. {
  439. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  440. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  441. { LLM_TENSOR_OUTPUT, "output" },
  442. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  443. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  444. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  445. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  446. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  447. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  448. },
  449. },
  450. {
  451. LLM_ARCH_PERSIMMON,
  452. {
  453. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  454. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  455. { LLM_TENSOR_OUTPUT, "output"},
  456. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  457. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  458. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  459. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  460. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  461. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  462. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  463. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  464. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  465. },
  466. },
  467. {
  468. LLM_ARCH_MPT,
  469. {
  470. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  471. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  472. { LLM_TENSOR_OUTPUT, "output" },
  473. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  474. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  475. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  476. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  477. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  478. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  479. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  480. },
  481. },
  482. {
  483. LLM_ARCH_STARCODER,
  484. {
  485. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  486. { LLM_TENSOR_POS_EMBD, "position_embd" },
  487. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  488. { LLM_TENSOR_OUTPUT, "output" },
  489. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  490. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  491. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  492. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  493. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  494. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  495. },
  496. },
  497. {
  498. LLM_ARCH_REFACT,
  499. {
  500. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  501. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  502. { LLM_TENSOR_OUTPUT, "output" },
  503. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  504. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  505. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  506. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  507. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  508. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  509. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  510. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  511. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  512. },
  513. },
  514. {
  515. LLM_ARCH_BERT,
  516. {
  517. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  518. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  519. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  520. { LLM_TENSOR_POS_EMBD, "position_embd" },
  521. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  522. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  523. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  524. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  525. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  526. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  527. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  528. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  529. },
  530. },
  531. {
  532. LLM_ARCH_NOMIC_BERT,
  533. {
  534. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  535. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  536. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  537. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  538. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  539. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  540. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  541. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  542. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  543. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  544. },
  545. },
  546. {
  547. LLM_ARCH_BLOOM,
  548. {
  549. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  550. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  551. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  552. { LLM_TENSOR_OUTPUT, "output" },
  553. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  554. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  555. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  556. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  557. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  558. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  559. },
  560. },
  561. {
  562. LLM_ARCH_STABLELM,
  563. {
  564. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  565. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  566. { LLM_TENSOR_OUTPUT, "output" },
  567. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  568. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  569. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  570. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  571. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  572. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  573. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  574. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  575. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  576. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  577. },
  578. },
  579. {
  580. LLM_ARCH_QWEN,
  581. {
  582. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  583. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  584. { LLM_TENSOR_OUTPUT, "output" },
  585. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  586. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  587. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  588. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  589. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  590. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  591. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  592. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  593. },
  594. },
  595. {
  596. LLM_ARCH_QWEN2,
  597. {
  598. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  599. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  600. { LLM_TENSOR_OUTPUT, "output" },
  601. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  602. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  603. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  604. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  605. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  606. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  607. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  608. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  609. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  610. },
  611. },
  612. {
  613. LLM_ARCH_PHI2,
  614. {
  615. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  616. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  617. { LLM_TENSOR_OUTPUT, "output" },
  618. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  619. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  620. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  621. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  622. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  623. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  624. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  625. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  626. },
  627. },
  628. {
  629. LLM_ARCH_PLAMO,
  630. {
  631. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  632. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  633. { LLM_TENSOR_OUTPUT, "output" },
  634. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  635. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  636. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  637. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  638. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  639. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  640. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  641. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  642. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  643. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  644. },
  645. },
  646. {
  647. LLM_ARCH_CODESHELL,
  648. {
  649. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  650. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  651. { LLM_TENSOR_OUTPUT, "output" },
  652. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  653. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  654. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  655. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  656. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  657. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  658. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  659. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  660. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  661. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  662. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  663. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  664. },
  665. },
  666. {
  667. LLM_ARCH_ORION,
  668. {
  669. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  670. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  671. { LLM_TENSOR_OUTPUT, "output" },
  672. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  673. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  674. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  675. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  676. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  677. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  678. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  679. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  680. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  681. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  682. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  683. },
  684. },
  685. {
  686. LLM_ARCH_INTERNLM2,
  687. {
  688. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  689. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  690. { LLM_TENSOR_OUTPUT, "output" },
  691. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  692. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  693. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  694. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  695. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  696. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  697. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  698. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  699. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  700. },
  701. },
  702. {
  703. LLM_ARCH_MINICPM,
  704. {
  705. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  706. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  707. { LLM_TENSOR_OUTPUT, "output" },
  708. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  709. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  710. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  711. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  712. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  713. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  714. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  715. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  716. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  717. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  718. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  719. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  720. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  721. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  722. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  723. },
  724. },
  725. {
  726. LLM_ARCH_GEMMA,
  727. {
  728. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  729. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  730. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  731. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  732. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  733. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  734. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  735. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  736. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  737. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  738. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  739. },
  740. },
  741. {
  742. LLM_ARCH_UNKNOWN,
  743. {
  744. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  745. },
  746. },
  747. };
  748. static llm_arch llm_arch_from_string(const std::string & name) {
  749. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  750. if (kv.second == name) {
  751. return kv.first;
  752. }
  753. }
  754. return LLM_ARCH_UNKNOWN;
  755. }
  756. // helper to handle gguf constants
  757. // usage:
  758. //
  759. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  760. //
  761. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  762. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  763. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  764. //
  765. struct LLM_TN {
  766. LLM_TN(llm_arch arch) : arch(arch) {}
  767. llm_arch arch;
  768. std::string operator()(llm_tensor tensor) const {
  769. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  770. return "__missing__";
  771. }
  772. return LLM_TENSOR_NAMES[arch].at(tensor);
  773. }
  774. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  775. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  776. return "__missing__";
  777. }
  778. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  779. }
  780. std::string operator()(llm_tensor tensor, int bid) const {
  781. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  782. return "__missing__";
  783. }
  784. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  785. }
  786. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  787. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  788. return "__missing__";
  789. }
  790. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  791. }
  792. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  793. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  794. return "__missing__";
  795. }
  796. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  797. }
  798. };
  799. //
  800. // gguf helpers
  801. //
  802. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  803. { LLAMA_ROPE_SCALING_NONE, "none" },
  804. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  805. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  806. };
  807. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  808. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  809. if (kv.second == name) {
  810. return kv.first;
  811. }
  812. }
  813. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  814. }
  815. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  816. switch (type) {
  817. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  818. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  819. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  820. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  821. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  822. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  823. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  824. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  825. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  826. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  827. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  828. default: return format("unknown type %d", type);
  829. }
  830. }
  831. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  832. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  833. switch (type) {
  834. case GGUF_TYPE_STRING:
  835. return gguf_get_val_str(ctx_gguf, i);
  836. case GGUF_TYPE_ARRAY:
  837. {
  838. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  839. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  840. const void * data = gguf_get_arr_data(ctx_gguf, i);
  841. std::stringstream ss;
  842. ss << "[";
  843. for (int j = 0; j < arr_n; j++) {
  844. if (arr_type == GGUF_TYPE_STRING) {
  845. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  846. // escape quotes
  847. replace_all(val, "\\", "\\\\");
  848. replace_all(val, "\"", "\\\"");
  849. ss << '"' << val << '"';
  850. } else if (arr_type == GGUF_TYPE_ARRAY) {
  851. ss << "???";
  852. } else {
  853. ss << gguf_data_to_str(arr_type, data, j);
  854. }
  855. if (j < arr_n - 1) {
  856. ss << ", ";
  857. }
  858. }
  859. ss << "]";
  860. return ss.str();
  861. }
  862. default:
  863. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  864. }
  865. }
  866. //
  867. // ggml helpers
  868. //
  869. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  870. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  871. if (plan.work_size > 0) {
  872. buf.resize(plan.work_size);
  873. plan.work_data = buf.data();
  874. }
  875. ggml_graph_compute(graph, &plan);
  876. }
  877. //
  878. // llama helpers
  879. //
  880. #if defined(_WIN32)
  881. static std::string llama_format_win_err(DWORD err) {
  882. LPSTR buf;
  883. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  884. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  885. if (!size) {
  886. return "FormatMessageA failed";
  887. }
  888. std::string ret(buf, size);
  889. LocalFree(buf);
  890. return ret;
  891. }
  892. #endif
  893. template <typename T>
  894. struct no_init {
  895. T value;
  896. no_init() { /* do nothing */ }
  897. };
  898. struct llama_file {
  899. // use FILE * so we don't have to re-open the file to mmap
  900. FILE * fp;
  901. size_t size;
  902. llama_file(const char * fname, const char * mode) {
  903. fp = std::fopen(fname, mode);
  904. if (fp == NULL) {
  905. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  906. }
  907. seek(0, SEEK_END);
  908. size = tell();
  909. seek(0, SEEK_SET);
  910. }
  911. size_t tell() const {
  912. #ifdef _WIN32
  913. __int64 ret = _ftelli64(fp);
  914. #else
  915. long ret = std::ftell(fp);
  916. #endif
  917. GGML_ASSERT(ret != -1); // this really shouldn't fail
  918. return (size_t) ret;
  919. }
  920. void seek(size_t offset, int whence) const {
  921. #ifdef _WIN32
  922. int ret = _fseeki64(fp, (__int64) offset, whence);
  923. #else
  924. int ret = std::fseek(fp, (long) offset, whence);
  925. #endif
  926. GGML_ASSERT(ret == 0); // same
  927. }
  928. void read_raw(void * ptr, size_t len) const {
  929. if (len == 0) {
  930. return;
  931. }
  932. errno = 0;
  933. std::size_t ret = std::fread(ptr, len, 1, fp);
  934. if (ferror(fp)) {
  935. throw std::runtime_error(format("read error: %s", strerror(errno)));
  936. }
  937. if (ret != 1) {
  938. throw std::runtime_error("unexpectedly reached end of file");
  939. }
  940. }
  941. uint32_t read_u32() const {
  942. uint32_t ret;
  943. read_raw(&ret, sizeof(ret));
  944. return ret;
  945. }
  946. void write_raw(const void * ptr, size_t len) const {
  947. if (len == 0) {
  948. return;
  949. }
  950. errno = 0;
  951. size_t ret = std::fwrite(ptr, len, 1, fp);
  952. if (ret != 1) {
  953. throw std::runtime_error(format("write error: %s", strerror(errno)));
  954. }
  955. }
  956. void write_u32(std::uint32_t val) const {
  957. write_raw(&val, sizeof(val));
  958. }
  959. ~llama_file() {
  960. if (fp) {
  961. std::fclose(fp);
  962. }
  963. }
  964. };
  965. struct llama_mmap {
  966. void * addr;
  967. size_t size;
  968. llama_mmap(const llama_mmap &) = delete;
  969. #ifdef _POSIX_MAPPED_FILES
  970. static constexpr bool SUPPORTED = true;
  971. // list of mapped fragments (first_offset, last_offset)
  972. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  973. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  974. size = file->size;
  975. int fd = fileno(file->fp);
  976. int flags = MAP_SHARED;
  977. // prefetch/readahead impairs performance on NUMA systems
  978. if (numa) { prefetch = 0; }
  979. #ifdef __linux__
  980. // advise the kernel to read the file sequentially (increases readahead)
  981. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  982. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  983. strerror(errno));
  984. }
  985. if (prefetch) { flags |= MAP_POPULATE; }
  986. #endif
  987. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  988. if (addr == MAP_FAILED) { // NOLINT
  989. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  990. }
  991. if (prefetch > 0) {
  992. // advise the kernel to preload the mapped memory
  993. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  994. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  995. strerror(errno));
  996. }
  997. }
  998. if (numa) {
  999. // advise the kernel not to use readahead
  1000. // (because the next page might not belong on the same node)
  1001. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1002. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1003. strerror(errno));
  1004. }
  1005. }
  1006. // initialize list of mapped_fragments
  1007. mapped_fragments.emplace_back(0, file->size);
  1008. }
  1009. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1010. // align first to the next page
  1011. size_t offset_in_page = *first & (page_size - 1);
  1012. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1013. *first += offset_to_page;
  1014. // align last to the previous page
  1015. *last = *last & ~(page_size - 1);
  1016. if (*last <= *first) {
  1017. *last = *first;
  1018. }
  1019. }
  1020. // partially unmap the file in the range [first, last)
  1021. void unmap_fragment(size_t first, size_t last) {
  1022. // note: this function must not be called multiple times with overlapping ranges
  1023. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1024. int page_size = sysconf(_SC_PAGESIZE);
  1025. align_range(&first, &last, page_size);
  1026. size_t len = last - first;
  1027. if (len == 0) {
  1028. return;
  1029. }
  1030. GGML_ASSERT(first % page_size == 0);
  1031. GGML_ASSERT(last % page_size == 0);
  1032. GGML_ASSERT(last > first);
  1033. void * next_page_start = (uint8_t *) addr + first;
  1034. // unmap the range
  1035. if (munmap(next_page_start, len)) {
  1036. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1037. }
  1038. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1039. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1040. for (const auto & frag : mapped_fragments) {
  1041. if (frag.first < first && frag.second > last) {
  1042. // the range is in the middle of the fragment, split it
  1043. new_mapped_fragments.emplace_back(frag.first, first);
  1044. new_mapped_fragments.emplace_back(last, frag.second);
  1045. } else if (frag.first < first && frag.second > first) {
  1046. // the range starts in the middle of the fragment
  1047. new_mapped_fragments.emplace_back(frag.first, first);
  1048. } else if (frag.first < last && frag.second > last) {
  1049. // the range ends in the middle of the fragment
  1050. new_mapped_fragments.emplace_back(last, frag.second);
  1051. } else if (frag.first >= first && frag.second <= last) {
  1052. // the range covers the entire fragment
  1053. } else {
  1054. // the range is outside the fragment
  1055. new_mapped_fragments.push_back(frag);
  1056. }
  1057. }
  1058. mapped_fragments = std::move(new_mapped_fragments);
  1059. }
  1060. ~llama_mmap() {
  1061. for (const auto & frag : mapped_fragments) {
  1062. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1063. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1064. }
  1065. }
  1066. }
  1067. #elif defined(_WIN32)
  1068. static constexpr bool SUPPORTED = true;
  1069. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1070. GGML_UNUSED(numa);
  1071. size = file->size;
  1072. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1073. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1074. if (hMapping == NULL) {
  1075. DWORD error = GetLastError();
  1076. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1077. }
  1078. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1079. DWORD error = GetLastError();
  1080. CloseHandle(hMapping);
  1081. if (addr == NULL) {
  1082. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1083. }
  1084. if (prefetch > 0) {
  1085. #if _WIN32_WINNT >= 0x602
  1086. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1087. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1088. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1089. // may fail on pre-Windows 8 systems
  1090. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1091. if (pPrefetchVirtualMemory) {
  1092. // advise the kernel to preload the mapped memory
  1093. WIN32_MEMORY_RANGE_ENTRY range;
  1094. range.VirtualAddress = addr;
  1095. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1096. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1097. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1098. llama_format_win_err(GetLastError()).c_str());
  1099. }
  1100. }
  1101. #else
  1102. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1103. #endif
  1104. }
  1105. }
  1106. void unmap_fragment(size_t first, size_t last) {
  1107. // not supported
  1108. GGML_UNUSED(first);
  1109. GGML_UNUSED(last);
  1110. }
  1111. ~llama_mmap() {
  1112. if (!UnmapViewOfFile(addr)) {
  1113. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1114. llama_format_win_err(GetLastError()).c_str());
  1115. }
  1116. }
  1117. #else
  1118. static constexpr bool SUPPORTED = false;
  1119. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1120. GGML_UNUSED(file);
  1121. GGML_UNUSED(prefetch);
  1122. GGML_UNUSED(numa);
  1123. throw std::runtime_error("mmap not supported");
  1124. }
  1125. void unmap_fragment(size_t first, size_t last) {
  1126. GGML_UNUSED(first);
  1127. GGML_UNUSED(last);
  1128. throw std::runtime_error("mmap not supported");
  1129. }
  1130. #endif
  1131. };
  1132. // Represents some region of memory being locked using mlock or VirtualLock;
  1133. // will automatically unlock on destruction.
  1134. struct llama_mlock {
  1135. void * addr = NULL;
  1136. size_t size = 0;
  1137. bool failed_already = false;
  1138. llama_mlock() {}
  1139. llama_mlock(const llama_mlock &) = delete;
  1140. ~llama_mlock() {
  1141. if (size) {
  1142. raw_unlock(addr, size);
  1143. }
  1144. }
  1145. void init(void * ptr) {
  1146. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1147. addr = ptr;
  1148. }
  1149. void grow_to(size_t target_size) {
  1150. GGML_ASSERT(addr);
  1151. if (failed_already) {
  1152. return;
  1153. }
  1154. size_t granularity = lock_granularity();
  1155. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1156. if (target_size > size) {
  1157. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1158. size = target_size;
  1159. } else {
  1160. failed_already = true;
  1161. }
  1162. }
  1163. }
  1164. #ifdef _POSIX_MEMLOCK_RANGE
  1165. static constexpr bool SUPPORTED = true;
  1166. static size_t lock_granularity() {
  1167. return (size_t) sysconf(_SC_PAGESIZE);
  1168. }
  1169. #ifdef __APPLE__
  1170. #define MLOCK_SUGGESTION \
  1171. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1172. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1173. #else
  1174. #define MLOCK_SUGGESTION \
  1175. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1176. #endif
  1177. bool raw_lock(const void * addr, size_t size) const {
  1178. if (!mlock(addr, size)) {
  1179. return true;
  1180. }
  1181. char* errmsg = std::strerror(errno);
  1182. bool suggest = (errno == ENOMEM);
  1183. // Check if the resource limit is fine after all
  1184. struct rlimit lock_limit;
  1185. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1186. suggest = false;
  1187. }
  1188. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1189. suggest = false;
  1190. }
  1191. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1192. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1193. return false;
  1194. }
  1195. #undef MLOCK_SUGGESTION
  1196. static void raw_unlock(void * addr, size_t size) {
  1197. if (munlock(addr, size)) {
  1198. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1199. }
  1200. }
  1201. #elif defined(_WIN32)
  1202. static constexpr bool SUPPORTED = true;
  1203. static size_t lock_granularity() {
  1204. SYSTEM_INFO si;
  1205. GetSystemInfo(&si);
  1206. return (size_t) si.dwPageSize;
  1207. }
  1208. bool raw_lock(void * ptr, size_t len) const {
  1209. for (int tries = 1; ; tries++) {
  1210. if (VirtualLock(ptr, len)) {
  1211. return true;
  1212. }
  1213. if (tries == 2) {
  1214. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1215. len, size, llama_format_win_err(GetLastError()).c_str());
  1216. return false;
  1217. }
  1218. // It failed but this was only the first try; increase the working
  1219. // set size and try again.
  1220. SIZE_T min_ws_size, max_ws_size;
  1221. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1222. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1223. llama_format_win_err(GetLastError()).c_str());
  1224. return false;
  1225. }
  1226. // Per MSDN: "The maximum number of pages that a process can lock
  1227. // is equal to the number of pages in its minimum working set minus
  1228. // a small overhead."
  1229. // Hopefully a megabyte is enough overhead:
  1230. size_t increment = len + 1048576;
  1231. // The minimum must be <= the maximum, so we need to increase both:
  1232. min_ws_size += increment;
  1233. max_ws_size += increment;
  1234. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1235. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1236. llama_format_win_err(GetLastError()).c_str());
  1237. return false;
  1238. }
  1239. }
  1240. }
  1241. static void raw_unlock(void * ptr, size_t len) {
  1242. if (!VirtualUnlock(ptr, len)) {
  1243. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1244. llama_format_win_err(GetLastError()).c_str());
  1245. }
  1246. }
  1247. #else
  1248. static constexpr bool SUPPORTED = false;
  1249. static size_t lock_granularity() {
  1250. return (size_t) 65536;
  1251. }
  1252. bool raw_lock(const void * addr, size_t len) const {
  1253. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1254. return false;
  1255. }
  1256. static void raw_unlock(const void * addr, size_t len) {}
  1257. #endif
  1258. };
  1259. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1260. std::vector<char> result(8, 0);
  1261. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1262. if (n_tokens < 0) {
  1263. result.resize(-n_tokens);
  1264. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1265. GGML_ASSERT(check == -n_tokens);
  1266. }
  1267. else {
  1268. result.resize(n_tokens);
  1269. }
  1270. return std::string(result.data(), result.size());
  1271. }
  1272. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1273. ggml_backend_buffer_type_t buft = nullptr;
  1274. #if defined(GGML_USE_CUBLAS)
  1275. // host buffers should only be used when data is expected to be copied to/from the GPU
  1276. if (host_buffer) {
  1277. buft = ggml_backend_cuda_host_buffer_type();
  1278. }
  1279. #elif defined(GGML_USE_SYCL)
  1280. buft = ggml_backend_sycl_host_buffer_type();
  1281. #elif defined(GGML_USE_CPU_HBM)
  1282. buft = ggml_backend_cpu_hbm_buffer_type();
  1283. #elif defined(GGML_USE_VULKAN)
  1284. if (host_buffer) {
  1285. buft = ggml_backend_vk_host_buffer_type();
  1286. }
  1287. #endif
  1288. if (buft == nullptr) {
  1289. buft = ggml_backend_cpu_buffer_type();
  1290. }
  1291. return buft;
  1292. GGML_UNUSED(host_buffer);
  1293. }
  1294. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1295. ggml_backend_buffer_type_t buft = nullptr;
  1296. #ifdef GGML_USE_METAL
  1297. buft = ggml_backend_metal_buffer_type();
  1298. #elif defined(GGML_USE_CUBLAS)
  1299. buft = ggml_backend_cuda_buffer_type(gpu);
  1300. #elif defined(GGML_USE_VULKAN)
  1301. buft = ggml_backend_vk_buffer_type(gpu);
  1302. #elif defined(GGML_USE_SYCL)
  1303. buft = ggml_backend_sycl_buffer_type(gpu);
  1304. #elif defined(GGML_USE_CLBLAST)
  1305. buft = ggml_backend_opencl_buffer_type();
  1306. #elif defined(GGML_USE_KOMPUTE)
  1307. buft = ggml_backend_kompute_buffer_type(gpu);
  1308. if (buft == nullptr) {
  1309. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1310. }
  1311. #endif
  1312. if (buft == nullptr) {
  1313. buft = llama_default_buffer_type_cpu(true);
  1314. }
  1315. return buft;
  1316. GGML_UNUSED(gpu);
  1317. }
  1318. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1319. ggml_backend_buffer_type_t buft = nullptr;
  1320. #ifdef GGML_USE_CUBLAS
  1321. if (ggml_backend_cuda_get_device_count() > 1) {
  1322. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1323. }
  1324. #endif
  1325. if (buft == nullptr) {
  1326. buft = llama_default_buffer_type_offload(fallback_gpu);
  1327. }
  1328. return buft;
  1329. GGML_UNUSED(tensor_split);
  1330. }
  1331. static size_t llama_get_device_count() {
  1332. #if defined(GGML_USE_CUBLAS)
  1333. return ggml_backend_cuda_get_device_count();
  1334. #elif defined(GGML_USE_VULKAN)
  1335. return ggml_backend_vk_get_device_count();
  1336. #else
  1337. return 1;
  1338. #endif
  1339. }
  1340. static size_t llama_get_device_memory(int device) {
  1341. #if defined(GGML_USE_CUBLAS)
  1342. size_t total;
  1343. size_t free;
  1344. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1345. return free;
  1346. #elif defined(GGML_USE_VULKAN)
  1347. size_t total;
  1348. size_t free;
  1349. ggml_backend_vk_get_device_memory(device, &total, &free);
  1350. return free;
  1351. #else
  1352. return 1;
  1353. GGML_UNUSED(device);
  1354. #endif
  1355. }
  1356. //
  1357. // globals
  1358. //
  1359. struct llama_state {
  1360. llama_state() {
  1361. #ifdef GGML_USE_METAL
  1362. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1363. #endif
  1364. }
  1365. // We save the log callback globally
  1366. ggml_log_callback log_callback = llama_log_callback_default;
  1367. void * log_callback_user_data = nullptr;
  1368. };
  1369. static llama_state g_state;
  1370. // available llama models
  1371. enum e_model {
  1372. MODEL_UNKNOWN,
  1373. MODEL_17M,
  1374. MODEL_22M,
  1375. MODEL_33M,
  1376. MODEL_109M,
  1377. MODEL_137M,
  1378. MODEL_335M,
  1379. MODEL_0_5B,
  1380. MODEL_1B,
  1381. MODEL_2B,
  1382. MODEL_3B,
  1383. MODEL_4B,
  1384. MODEL_7B,
  1385. MODEL_8B,
  1386. MODEL_13B,
  1387. MODEL_14B,
  1388. MODEL_15B,
  1389. MODEL_20B,
  1390. MODEL_30B,
  1391. MODEL_34B,
  1392. MODEL_40B,
  1393. MODEL_65B,
  1394. MODEL_70B,
  1395. MODEL_SMALL,
  1396. MODEL_MEDIUM,
  1397. MODEL_LARGE,
  1398. MODEL_XL,
  1399. };
  1400. static const size_t kiB = 1024;
  1401. static const size_t MiB = 1024*kiB;
  1402. static const size_t GiB = 1024*MiB;
  1403. struct llama_hparams {
  1404. bool vocab_only;
  1405. bool rope_finetuned;
  1406. uint32_t n_vocab;
  1407. uint32_t n_ctx_train; // context size the model was trained on
  1408. uint32_t n_embd;
  1409. uint32_t n_head;
  1410. uint32_t n_head_kv;
  1411. uint32_t n_layer;
  1412. uint32_t n_rot;
  1413. 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
  1414. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1415. uint32_t n_ff;
  1416. uint32_t n_expert = 0;
  1417. uint32_t n_expert_used = 0;
  1418. uint32_t n_vocab_type = 0; // for BERT-style token types
  1419. float f_norm_eps;
  1420. float f_norm_rms_eps;
  1421. float rope_freq_base_train;
  1422. float rope_freq_scale_train;
  1423. uint32_t n_yarn_orig_ctx;
  1424. int32_t rope_scaling_type_train;
  1425. float f_clamp_kqv = 0.0f;
  1426. float f_max_alibi_bias = 0.0f;
  1427. bool causal_attn = true;
  1428. bool need_kq_pos = false;
  1429. uint32_t pooling_type = LLAMA_POOLING_NONE;
  1430. bool operator!=(const llama_hparams & other) const {
  1431. if (this->vocab_only != other.vocab_only) return true;
  1432. if (this->n_vocab != other.n_vocab) return true;
  1433. if (this->n_ctx_train != other.n_ctx_train) return true;
  1434. if (this->n_embd != other.n_embd) return true;
  1435. if (this->n_head != other.n_head) return true;
  1436. if (this->n_head_kv != other.n_head_kv) return true;
  1437. if (this->n_layer != other.n_layer) return true;
  1438. if (this->n_rot != other.n_rot) return true;
  1439. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1440. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1441. if (this->n_ff != other.n_ff) return true;
  1442. if (this->n_expert != other.n_expert) return true;
  1443. if (this->n_expert_used != other.n_expert_used) return true;
  1444. if (this->rope_finetuned != other.rope_finetuned) return true;
  1445. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1446. const float EPSILON = 1e-9f;
  1447. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1448. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1449. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1450. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1451. return false;
  1452. }
  1453. uint32_t n_gqa() const {
  1454. return n_head/n_head_kv;
  1455. }
  1456. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1457. return n_embd_head_k * n_head_kv;
  1458. }
  1459. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1460. return n_embd_head_v * n_head_kv;
  1461. }
  1462. };
  1463. struct llama_cparams {
  1464. uint32_t n_ctx; // context size used during inference
  1465. uint32_t n_batch;
  1466. uint32_t n_threads; // number of threads to use for generation
  1467. uint32_t n_threads_batch; // number of threads to use for batch processing
  1468. float rope_freq_base;
  1469. float rope_freq_scale;
  1470. uint32_t n_yarn_orig_ctx;
  1471. // These hyperparameters are not exposed in GGUF, because all
  1472. // existing YaRN models use the same values for them.
  1473. float yarn_ext_factor;
  1474. float yarn_attn_factor;
  1475. float yarn_beta_fast;
  1476. float yarn_beta_slow;
  1477. bool mul_mat_q;
  1478. bool offload_kqv;
  1479. bool do_pooling;
  1480. ggml_backend_sched_eval_callback cb_eval;
  1481. void * cb_eval_user_data;
  1482. };
  1483. struct llama_layer {
  1484. // normalization
  1485. struct ggml_tensor * attn_norm;
  1486. struct ggml_tensor * attn_norm_b;
  1487. struct ggml_tensor * attn_norm_2;
  1488. struct ggml_tensor * attn_norm_2_b;
  1489. struct ggml_tensor * attn_q_norm;
  1490. struct ggml_tensor * attn_q_norm_b;
  1491. struct ggml_tensor * attn_k_norm;
  1492. struct ggml_tensor * attn_k_norm_b;
  1493. struct ggml_tensor * attn_out_norm;
  1494. struct ggml_tensor * attn_out_norm_b;
  1495. // attention
  1496. struct ggml_tensor * wq;
  1497. struct ggml_tensor * wk;
  1498. struct ggml_tensor * wv;
  1499. struct ggml_tensor * wo;
  1500. struct ggml_tensor * wqkv;
  1501. // attention bias
  1502. struct ggml_tensor * bq;
  1503. struct ggml_tensor * bk;
  1504. struct ggml_tensor * bv;
  1505. struct ggml_tensor * bo;
  1506. struct ggml_tensor * bqkv;
  1507. // normalization
  1508. struct ggml_tensor * ffn_norm;
  1509. struct ggml_tensor * ffn_norm_b;
  1510. struct ggml_tensor * layer_out_norm;
  1511. struct ggml_tensor * layer_out_norm_b;
  1512. // ff
  1513. struct ggml_tensor * ffn_gate; // w1
  1514. struct ggml_tensor * ffn_down; // w2
  1515. struct ggml_tensor * ffn_up; // w3
  1516. // ff MoE
  1517. struct ggml_tensor * ffn_gate_inp;
  1518. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1519. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1520. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1521. // ff bias
  1522. struct ggml_tensor * ffn_down_b; // b2
  1523. struct ggml_tensor * ffn_up_b; // b3
  1524. struct ggml_tensor * ffn_act;
  1525. };
  1526. struct llama_kv_cell {
  1527. llama_pos pos = -1;
  1528. llama_pos delta = 0;
  1529. std::set<llama_seq_id> seq_id;
  1530. bool has_seq_id(const llama_seq_id & id) const {
  1531. return seq_id.find(id) != seq_id.end();
  1532. }
  1533. };
  1534. // ring-buffer of cached KV data
  1535. struct llama_kv_cache {
  1536. bool has_shift = false;
  1537. // Note: The value of head isn't only used to optimize searching
  1538. // for a free KV slot. llama_decode_internal also uses it, so it
  1539. // cannot be freely changed after a slot has been allocated.
  1540. uint32_t head = 0;
  1541. uint32_t size = 0;
  1542. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1543. // computed before each graph build
  1544. uint32_t n = 0;
  1545. std::vector<llama_kv_cell> cells;
  1546. std::vector<struct ggml_tensor *> k_l; // per layer
  1547. std::vector<struct ggml_tensor *> v_l;
  1548. std::vector<struct ggml_context *> ctxs;
  1549. std::vector<ggml_backend_buffer_t> bufs;
  1550. size_t total_size() const {
  1551. size_t size = 0;
  1552. for (ggml_backend_buffer_t buf : bufs) {
  1553. size += ggml_backend_buffer_get_size(buf);
  1554. }
  1555. return size;
  1556. }
  1557. ~llama_kv_cache() {
  1558. for (struct ggml_context * ctx : ctxs) {
  1559. ggml_free(ctx);
  1560. }
  1561. for (ggml_backend_buffer_t buf : bufs) {
  1562. ggml_backend_buffer_free(buf);
  1563. }
  1564. }
  1565. };
  1566. struct llama_vocab {
  1567. using id = int32_t;
  1568. using token = std::string;
  1569. using ttype = llama_token_type;
  1570. struct token_data {
  1571. token text;
  1572. float score;
  1573. ttype type;
  1574. };
  1575. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1576. std::unordered_map<token, id> token_to_id;
  1577. std::vector<token_data> id_to_token;
  1578. std::unordered_map<token, id> special_tokens_cache;
  1579. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1580. // default LLaMA special tokens
  1581. id special_bos_id = 1;
  1582. id special_eos_id = 2;
  1583. id special_unk_id = 0;
  1584. id special_sep_id = -1;
  1585. id special_pad_id = -1;
  1586. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1587. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1588. id linefeed_id = 13;
  1589. id special_prefix_id = 32007;
  1590. id special_middle_id = 32009;
  1591. id special_suffix_id = 32008;
  1592. id special_eot_id = 32010;
  1593. bool add_space_prefix = true;
  1594. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1595. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1596. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1597. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1598. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1599. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1600. if (it == bpe_ranks.end()) {
  1601. return -1;
  1602. }
  1603. return it->second;
  1604. }
  1605. };
  1606. struct llama_model {
  1607. e_model type = MODEL_UNKNOWN;
  1608. llm_arch arch = LLM_ARCH_UNKNOWN;
  1609. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1610. std::string name = "n/a";
  1611. llama_hparams hparams = {};
  1612. llama_vocab vocab;
  1613. struct ggml_tensor * tok_embd;
  1614. struct ggml_tensor * type_embd;
  1615. struct ggml_tensor * pos_embd;
  1616. struct ggml_tensor * tok_norm;
  1617. struct ggml_tensor * tok_norm_b;
  1618. struct ggml_tensor * output_norm;
  1619. struct ggml_tensor * output_norm_b;
  1620. struct ggml_tensor * output;
  1621. struct ggml_tensor * output_b;
  1622. std::vector<llama_layer> layers;
  1623. llama_split_mode split_mode;
  1624. int main_gpu;
  1625. int n_gpu_layers;
  1626. // gguf metadata
  1627. std::unordered_map<std::string, std::string> gguf_kv;
  1628. // layer -> buffer type mapping
  1629. struct layer_buft {
  1630. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1631. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1632. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1633. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1634. ggml_backend_buffer_type_t buft; // everything else
  1635. };
  1636. layer_buft buft_input;
  1637. layer_buft buft_output;
  1638. std::vector<layer_buft> buft_layer;
  1639. // contexts where the model tensors metadata is stored
  1640. std::vector<struct ggml_context *> ctxs;
  1641. // the model memory buffers for the tensor data
  1642. std::vector<ggml_backend_buffer_t> bufs;
  1643. // model memory mapped file
  1644. std::unique_ptr<llama_mmap> mapping;
  1645. // objects representing data potentially being locked in memory
  1646. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1647. llama_mlock mlock_mmap;
  1648. // for quantize-stats only
  1649. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1650. int64_t t_load_us = 0;
  1651. int64_t t_start_us = 0;
  1652. ~llama_model() {
  1653. for (struct ggml_context * ctx : ctxs) {
  1654. ggml_free(ctx);
  1655. }
  1656. for (ggml_backend_buffer_t buf : bufs) {
  1657. ggml_backend_buffer_free(buf);
  1658. }
  1659. }
  1660. };
  1661. struct llama_context {
  1662. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1663. ~llama_context() {
  1664. ggml_backend_sched_free(sched);
  1665. for (ggml_backend_t backend : backends) {
  1666. ggml_backend_free(backend);
  1667. }
  1668. #ifdef GGML_USE_VULKAN
  1669. ggml_vk_free_cpu_assist();
  1670. #endif
  1671. ggml_backend_buffer_free(buf_input);
  1672. ggml_free(ctx_input);
  1673. }
  1674. llama_cparams cparams;
  1675. std::vector<ggml_backend_t> backends;
  1676. #ifdef GGML_USE_METAL
  1677. ggml_backend_t backend_metal = nullptr;
  1678. #endif
  1679. ggml_backend_t backend_cpu = nullptr;
  1680. const llama_model & model;
  1681. // key + value cache for the self attention
  1682. struct llama_kv_cache kv_self;
  1683. std::mt19937 rng;
  1684. bool has_evaluated_once = false;
  1685. int64_t t_start_us;
  1686. int64_t t_load_us;
  1687. int64_t t_sample_us = 0;
  1688. int64_t t_p_eval_us = 0;
  1689. int64_t t_eval_us = 0;
  1690. int32_t n_sample = 0; // number of tokens sampled
  1691. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1692. int32_t n_eval = 0; // number of eval calls
  1693. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1694. std::vector<float> logits;
  1695. #ifndef NDEBUG
  1696. // guard against access to unset logits
  1697. std::vector<bool> logits_valid;
  1698. #endif
  1699. bool logits_all = false;
  1700. // input embedding (1-dimensional array: [n_embd])
  1701. std::vector<float> embedding;
  1702. // memory buffers used to evaluate the model
  1703. std::vector<uint8_t> buf_compute_meta;
  1704. ggml_backend_sched_t sched = nullptr;
  1705. // input tensors
  1706. ggml_backend_buffer_t buf_input = nullptr;
  1707. ggml_context * ctx_input = nullptr;
  1708. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1709. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1710. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1711. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1712. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1713. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1714. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1715. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1716. #ifdef GGML_USE_MPI
  1717. ggml_mpi_context * ctx_mpi = NULL;
  1718. #endif
  1719. };
  1720. //
  1721. // kv cache helpers
  1722. //
  1723. static bool llama_kv_cache_init(
  1724. struct llama_kv_cache & cache,
  1725. const llama_model & model,
  1726. ggml_type ktype,
  1727. ggml_type vtype,
  1728. uint32_t n_ctx,
  1729. bool offload) {
  1730. const struct llama_hparams & hparams = model.hparams;
  1731. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1732. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1733. const int64_t n_layer = hparams.n_layer;
  1734. cache.has_shift = false;
  1735. cache.head = 0;
  1736. cache.size = n_ctx;
  1737. cache.used = 0;
  1738. cache.cells.clear();
  1739. cache.cells.resize(n_ctx);
  1740. #ifdef GGML_USE_CLBLAST
  1741. offload = false;
  1742. #endif
  1743. // count used buffer types
  1744. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1745. if (offload) {
  1746. for (int64_t i = 0; i < n_layer; ++i) {
  1747. buft_layer_count[model.buft_layer[i].buft]++;
  1748. }
  1749. } else {
  1750. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1751. }
  1752. // create a context for each buffer type
  1753. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1754. for (auto & it : buft_layer_count) {
  1755. int n_layers = it.second;
  1756. struct ggml_init_params params = {
  1757. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1758. /*.mem_buffer =*/ NULL,
  1759. /*.no_alloc =*/ true,
  1760. };
  1761. ggml_context * ctx = ggml_init(params);
  1762. if (!ctx) {
  1763. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1764. return false;
  1765. }
  1766. ctx_map[it.first] = ctx;
  1767. cache.ctxs.push_back(ctx);
  1768. }
  1769. cache.k_l.reserve(n_layer);
  1770. cache.v_l.reserve(n_layer);
  1771. for (int i = 0; i < (int) n_layer; i++) {
  1772. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1773. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1774. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1775. ggml_format_name(k, "cache_k_l%d", i);
  1776. ggml_format_name(v, "cache_v_l%d", i);
  1777. cache.k_l.push_back(k);
  1778. cache.v_l.push_back(v);
  1779. }
  1780. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1781. for (auto it : ctx_map) {
  1782. ggml_backend_buffer_type_t buft = it.first;
  1783. ggml_context * ctx = it.second;
  1784. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1785. if (!buf) {
  1786. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1787. return false;
  1788. }
  1789. ggml_backend_buffer_clear(buf, 0);
  1790. 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);
  1791. cache.bufs.push_back(buf);
  1792. }
  1793. return true;
  1794. }
  1795. // find an empty slot of size "n_tokens" in the cache
  1796. // updates the cache head
  1797. // Note: On success, it's important that cache.head points
  1798. // to the first cell of the slot.
  1799. static bool llama_kv_cache_find_slot(
  1800. struct llama_kv_cache & cache,
  1801. const struct llama_batch & batch) {
  1802. const uint32_t n_ctx = cache.size;
  1803. const uint32_t n_tokens = batch.n_tokens;
  1804. if (n_tokens > n_ctx) {
  1805. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1806. return false;
  1807. }
  1808. uint32_t n_tested = 0;
  1809. while (true) {
  1810. if (cache.head + n_tokens > n_ctx) {
  1811. n_tested += n_ctx - cache.head;
  1812. cache.head = 0;
  1813. continue;
  1814. }
  1815. bool found = true;
  1816. for (uint32_t i = 0; i < n_tokens; i++) {
  1817. if (cache.cells[cache.head + i].pos >= 0) {
  1818. found = false;
  1819. cache.head += i + 1;
  1820. n_tested += i + 1;
  1821. break;
  1822. }
  1823. }
  1824. if (found) {
  1825. break;
  1826. }
  1827. if (n_tested >= n_ctx) {
  1828. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1829. return false;
  1830. }
  1831. }
  1832. for (uint32_t i = 0; i < n_tokens; i++) {
  1833. cache.cells[cache.head + i].pos = batch.pos[i];
  1834. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1835. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1836. }
  1837. }
  1838. cache.used += n_tokens;
  1839. return true;
  1840. }
  1841. // find how many cells are currently in use
  1842. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1843. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1844. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1845. return i + 1;
  1846. }
  1847. }
  1848. return 0;
  1849. }
  1850. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1851. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1852. cache.cells[i].pos = -1;
  1853. cache.cells[i].seq_id.clear();
  1854. }
  1855. cache.head = 0;
  1856. cache.used = 0;
  1857. }
  1858. static void llama_kv_cache_seq_rm(
  1859. struct llama_kv_cache & cache,
  1860. llama_seq_id seq_id,
  1861. llama_pos p0,
  1862. llama_pos p1) {
  1863. uint32_t new_head = cache.size;
  1864. if (p0 < 0) p0 = 0;
  1865. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1866. for (uint32_t i = 0; i < cache.size; ++i) {
  1867. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1868. if (seq_id < 0) {
  1869. cache.cells[i].seq_id.clear();
  1870. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1871. cache.cells[i].seq_id.erase(seq_id);
  1872. } else {
  1873. continue;
  1874. }
  1875. if (cache.cells[i].seq_id.empty()) {
  1876. // keep count of the number of used cells
  1877. if (cache.cells[i].pos >= 0) cache.used--;
  1878. cache.cells[i].pos = -1;
  1879. if (new_head == cache.size) new_head = i;
  1880. }
  1881. }
  1882. }
  1883. // If we freed up a slot, set head to it so searching can start there.
  1884. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1885. }
  1886. static void llama_kv_cache_seq_cp(
  1887. struct llama_kv_cache & cache,
  1888. llama_seq_id seq_id_src,
  1889. llama_seq_id seq_id_dst,
  1890. llama_pos p0,
  1891. llama_pos p1) {
  1892. if (p0 < 0) p0 = 0;
  1893. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1894. cache.head = 0;
  1895. for (uint32_t i = 0; i < cache.size; ++i) {
  1896. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1897. cache.cells[i].seq_id.insert(seq_id_dst);
  1898. }
  1899. }
  1900. }
  1901. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1902. uint32_t new_head = cache.size;
  1903. for (uint32_t i = 0; i < cache.size; ++i) {
  1904. if (!cache.cells[i].has_seq_id(seq_id)) {
  1905. if (cache.cells[i].pos >= 0) cache.used--;
  1906. cache.cells[i].pos = -1;
  1907. cache.cells[i].seq_id.clear();
  1908. if (new_head == cache.size) new_head = i;
  1909. } else {
  1910. cache.cells[i].seq_id.clear();
  1911. cache.cells[i].seq_id.insert(seq_id);
  1912. }
  1913. }
  1914. // If we freed up a slot, set head to it so searching can start there.
  1915. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1916. }
  1917. static void llama_kv_cache_seq_shift(
  1918. struct llama_kv_cache & cache,
  1919. llama_seq_id seq_id,
  1920. llama_pos p0,
  1921. llama_pos p1,
  1922. llama_pos delta) {
  1923. uint32_t new_head = cache.size;
  1924. if (p0 < 0) p0 = 0;
  1925. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1926. for (uint32_t i = 0; i < cache.size; ++i) {
  1927. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1928. cache.has_shift = true;
  1929. cache.cells[i].pos += delta;
  1930. cache.cells[i].delta += delta;
  1931. if (cache.cells[i].pos < 0) {
  1932. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1933. cache.cells[i].pos = -1;
  1934. cache.cells[i].seq_id.clear();
  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. // Otherwise we just start the next search from the beginning.
  1941. cache.head = new_head != cache.size ? new_head : 0;
  1942. }
  1943. static void llama_kv_cache_seq_div(
  1944. struct llama_kv_cache & cache,
  1945. llama_seq_id seq_id,
  1946. llama_pos p0,
  1947. llama_pos p1,
  1948. int d) {
  1949. if (p0 < 0) p0 = 0;
  1950. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1951. for (uint32_t i = 0; i < cache.size; ++i) {
  1952. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1953. cache.has_shift = true;
  1954. {
  1955. llama_pos p_old = cache.cells[i].pos;
  1956. cache.cells[i].pos /= d;
  1957. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1958. }
  1959. }
  1960. }
  1961. }
  1962. //
  1963. // model loading and saving
  1964. //
  1965. enum llama_fver {
  1966. GGUF_FILE_VERSION_V1 = 1,
  1967. GGUF_FILE_VERSION_V2 = 2,
  1968. GGUF_FILE_VERSION_V3 = 3,
  1969. };
  1970. static const char * llama_file_version_name(llama_fver version) {
  1971. switch (version) {
  1972. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1973. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1974. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1975. }
  1976. return "unknown";
  1977. }
  1978. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1979. char buf[256];
  1980. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1981. for (size_t i = 1; i < ne.size(); i++) {
  1982. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1983. }
  1984. return buf;
  1985. }
  1986. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1987. char buf[256];
  1988. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1989. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1990. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1991. }
  1992. return buf;
  1993. }
  1994. namespace GGUFMeta {
  1995. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1996. struct GKV_Base_Type {
  1997. static constexpr gguf_type gt = gt_;
  1998. static T getter(const gguf_context * ctx, const int kid) {
  1999. return gfun(ctx, kid);
  2000. }
  2001. };
  2002. template<typename T> struct GKV_Base;
  2003. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2004. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2005. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2006. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2007. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2008. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2009. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2010. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2011. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2012. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2013. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2014. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2015. template<> struct GKV_Base<std::string> {
  2016. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2017. static std::string getter(const gguf_context * ctx, const int kid) {
  2018. return gguf_get_val_str(ctx, kid);
  2019. }
  2020. };
  2021. struct ArrayInfo{
  2022. const gguf_type gt;
  2023. const size_t length;
  2024. const void * data;
  2025. };
  2026. template<> struct GKV_Base<ArrayInfo> {
  2027. public:
  2028. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2029. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2030. return ArrayInfo {
  2031. gguf_get_arr_type(ctx, k),
  2032. size_t(gguf_get_arr_n(ctx, k)),
  2033. gguf_get_arr_data(ctx, k),
  2034. };
  2035. }
  2036. };
  2037. template<typename T>
  2038. class GKV: public GKV_Base<T> {
  2039. GKV() = delete;
  2040. public:
  2041. static T get_kv(const gguf_context * ctx, const int k) {
  2042. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2043. if (kt != GKV::gt) {
  2044. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2045. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2046. }
  2047. return GKV::getter(ctx, k);
  2048. }
  2049. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2050. switch (ty) {
  2051. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  2052. case LLAMA_KV_OVERRIDE_INT: return "int";
  2053. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  2054. }
  2055. return "unknown";
  2056. }
  2057. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  2058. if (!override) { return false; }
  2059. if (override->tag == expected_type) {
  2060. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2061. __func__, override_type_to_str(override->tag), override->key);
  2062. switch (override->tag) {
  2063. case LLAMA_KV_OVERRIDE_BOOL: {
  2064. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  2065. } break;
  2066. case LLAMA_KV_OVERRIDE_INT: {
  2067. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  2068. } break;
  2069. case LLAMA_KV_OVERRIDE_FLOAT: {
  2070. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  2071. } break;
  2072. default:
  2073. // Shouldn't be possible to end up here, but just in case...
  2074. throw std::runtime_error(
  2075. format("Unsupported attempt to override %s type for metadata key %s\n",
  2076. override_type_to_str(override->tag), override->key));
  2077. }
  2078. return true;
  2079. }
  2080. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2081. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  2082. return false;
  2083. }
  2084. template<typename OT>
  2085. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2086. try_override(OT & target, const struct llama_model_kv_override *override) {
  2087. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  2088. target = override->bool_value;
  2089. return true;
  2090. }
  2091. return false;
  2092. }
  2093. template<typename OT>
  2094. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2095. try_override(OT & target, const struct llama_model_kv_override *override) {
  2096. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  2097. target = override->int_value;
  2098. return true;
  2099. }
  2100. return false;
  2101. }
  2102. template<typename OT>
  2103. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2104. try_override(T & target, const struct llama_model_kv_override *override) {
  2105. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  2106. target = override->float_value;
  2107. return true;
  2108. }
  2109. return false;
  2110. }
  2111. template<typename OT>
  2112. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2113. try_override(T & target, const struct llama_model_kv_override *override) {
  2114. (void)target;
  2115. (void)override;
  2116. if (!override) { return false; }
  2117. // Currently, we should never end up here so it would be a bug if we do.
  2118. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2119. override ? override->key : "NULL"));
  2120. }
  2121. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  2122. if (try_override<T>(target, override)) {
  2123. return true;
  2124. }
  2125. if (k < 0) { return false; }
  2126. target = get_kv(ctx, k);
  2127. return true;
  2128. }
  2129. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2130. return set(ctx, gguf_find_key(ctx, key), target, override);
  2131. }
  2132. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2133. return set(ctx, key.c_str(), target, override);
  2134. }
  2135. };
  2136. }
  2137. struct llama_model_loader {
  2138. int n_kv = 0;
  2139. int n_tensors = 0;
  2140. int n_created = 0;
  2141. int64_t n_elements = 0;
  2142. size_t n_bytes = 0;
  2143. bool use_mmap = false;
  2144. llama_file file;
  2145. llama_ftype ftype;
  2146. llama_fver fver;
  2147. std::unique_ptr<llama_mmap> mapping;
  2148. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2149. struct gguf_context * ctx_gguf = NULL;
  2150. struct ggml_context * ctx_meta = NULL;
  2151. std::string arch_name;
  2152. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2153. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2154. int trace = 0;
  2155. if (getenv("LLAMA_TRACE")) {
  2156. trace = atoi(getenv("LLAMA_TRACE"));
  2157. }
  2158. struct gguf_init_params params = {
  2159. /*.no_alloc = */ true,
  2160. /*.ctx = */ &ctx_meta,
  2161. };
  2162. if (param_overrides_p != nullptr) {
  2163. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2164. kv_overrides.insert({std::string(p->key), *p});
  2165. }
  2166. }
  2167. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2168. if (!ctx_gguf) {
  2169. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2170. }
  2171. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2172. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2173. n_kv = gguf_get_n_kv(ctx_gguf);
  2174. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2175. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2176. for (int i = 0; i < n_tensors; i++) {
  2177. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2178. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2179. n_elements += ggml_nelements(t);
  2180. n_bytes += ggml_nbytes(t);
  2181. }
  2182. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2183. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2184. // determine file type based on the number of tensors for each quantization and print meta data
  2185. // TODO: make optional
  2186. {
  2187. std::map<enum ggml_type, uint32_t> n_type;
  2188. uint32_t n_type_max = 0;
  2189. enum ggml_type type_max = GGML_TYPE_F32;
  2190. for (int i = 0; i < n_tensors; i++) {
  2191. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2192. n_type[type]++;
  2193. if (n_type_max < n_type[type]) {
  2194. n_type_max = n_type[type];
  2195. type_max = type;
  2196. }
  2197. if (trace > 0) {
  2198. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2199. 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());
  2200. }
  2201. }
  2202. switch (type_max) {
  2203. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2204. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2205. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2206. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2207. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2208. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2209. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2210. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2211. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2212. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2213. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2214. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2215. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2216. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2217. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2218. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2219. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2220. default:
  2221. {
  2222. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2223. ftype = LLAMA_FTYPE_ALL_F32;
  2224. } break;
  2225. }
  2226. // this is a way to mark that we have "guessed" the file type
  2227. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2228. {
  2229. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2230. if (kid >= 0) {
  2231. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2232. }
  2233. }
  2234. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2235. for (int i = 0; i < n_kv; i++) {
  2236. const char * name = gguf_get_key(ctx_gguf, i);
  2237. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2238. const std::string type_name =
  2239. type == GGUF_TYPE_ARRAY
  2240. ? 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))
  2241. : gguf_type_name(type);
  2242. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2243. const size_t MAX_VALUE_LEN = 40;
  2244. if (value.size() > MAX_VALUE_LEN) {
  2245. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2246. }
  2247. replace_all(value, "\n", "\\n");
  2248. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2249. }
  2250. // print type counts
  2251. for (auto & kv : n_type) {
  2252. if (kv.second == 0) {
  2253. continue;
  2254. }
  2255. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2256. }
  2257. }
  2258. if (!llama_mmap::SUPPORTED) {
  2259. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2260. use_mmap = false;
  2261. }
  2262. this->use_mmap = use_mmap;
  2263. }
  2264. ~llama_model_loader() {
  2265. if (ctx_gguf) {
  2266. gguf_free(ctx_gguf);
  2267. }
  2268. if (ctx_meta) {
  2269. ggml_free(ctx_meta);
  2270. }
  2271. }
  2272. template<typename T>
  2273. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2274. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2275. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2276. if (kid < 0) {
  2277. if (required) {
  2278. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2279. }
  2280. return false;
  2281. }
  2282. struct GGUFMeta::ArrayInfo arr_info =
  2283. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2284. result = arr_info.length;
  2285. return true;
  2286. }
  2287. template<typename T>
  2288. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2289. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2290. return get_arr_n(llm_kv(kid), result, required);
  2291. }
  2292. template<typename T>
  2293. bool get_key(const std::string & key, T & result, const bool required = true) {
  2294. auto it = kv_overrides.find(key);
  2295. const struct llama_model_kv_override * override =
  2296. it != kv_overrides.end() ? &it->second : nullptr;
  2297. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2298. if (required && !found) {
  2299. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2300. }
  2301. return found;
  2302. }
  2303. template<typename T>
  2304. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2305. return get_key(llm_kv(kid), result, required);
  2306. }
  2307. std::string get_arch_name() const {
  2308. return arch_name;
  2309. }
  2310. enum llm_arch get_arch() const {
  2311. return llm_kv.arch;
  2312. }
  2313. const char * get_tensor_name(int i) const {
  2314. return gguf_get_tensor_name(ctx_gguf, i);
  2315. }
  2316. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2317. return ggml_get_tensor(ctx_meta, name);
  2318. }
  2319. struct ggml_tensor * get_tensor_meta(int i) const {
  2320. return get_tensor_meta(get_tensor_name(i));
  2321. }
  2322. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2323. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2324. ggml_set_name(tensor, ggml_get_name(meta));
  2325. n_created++;
  2326. return tensor;
  2327. }
  2328. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2329. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2330. if (cur == NULL) {
  2331. if (!required) {
  2332. return NULL;
  2333. }
  2334. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2335. }
  2336. {
  2337. bool is_ok = true;
  2338. for (size_t i = 0; i < ne.size(); ++i) {
  2339. if (ne[i] != cur->ne[i]) {
  2340. is_ok = false;
  2341. break;
  2342. }
  2343. }
  2344. if (!is_ok) {
  2345. throw std::runtime_error(
  2346. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2347. __func__, name.c_str(),
  2348. llama_format_tensor_shape(ne).c_str(),
  2349. llama_format_tensor_shape(cur).c_str()));
  2350. }
  2351. }
  2352. return create_tensor_for(ctx, cur);
  2353. }
  2354. void done_getting_tensors() const {
  2355. if (n_created != n_tensors) {
  2356. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2357. }
  2358. }
  2359. size_t file_offset(const char * name) const {
  2360. const int idx = gguf_find_tensor(ctx_gguf, name);
  2361. if (idx < 0) {
  2362. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2363. }
  2364. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2365. }
  2366. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2367. // prefetch the whole file - all the data is needed anyway
  2368. if (use_mmap) {
  2369. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2370. }
  2371. // compute the total size of all tensors for progress reporting
  2372. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2373. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2374. size_data += ggml_nbytes(cur);
  2375. }
  2376. if (use_mmap && mapping) {
  2377. if (lmlock) {
  2378. lmlock->init(mapping->addr);
  2379. }
  2380. mmap_used_first = mapping->size;
  2381. }
  2382. }
  2383. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2384. GGML_ASSERT(mapping);
  2385. *first = mapping->size;
  2386. *last = 0;
  2387. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2388. const size_t offs = file_offset(ggml_get_name(tensor));
  2389. *first = std::min(*first, offs);
  2390. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2391. }
  2392. }
  2393. // for backwards compatibility, does not support ggml-backend
  2394. void load_data_for(struct ggml_tensor * cur) const {
  2395. const size_t offs = file_offset(ggml_get_name(cur));
  2396. if (use_mmap && mapping) {
  2397. if (cur->data == nullptr) {
  2398. cur->data = (uint8_t *)mapping->addr + offs;
  2399. } else {
  2400. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2401. }
  2402. } else {
  2403. GGML_ASSERT(cur->data != nullptr);
  2404. file.seek(offs, SEEK_SET);
  2405. file.read_raw(cur->data, ggml_nbytes(cur));
  2406. }
  2407. }
  2408. size_t size_done = 0;
  2409. size_t size_data = 0;
  2410. size_t mmap_used_first = -1;
  2411. size_t mmap_used_last = 0;
  2412. // Returns false if cancelled by progress_callback
  2413. 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) {
  2414. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2415. std::vector<no_init<uint8_t>> read_buf;
  2416. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2417. if (progress_callback) {
  2418. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2419. return false;
  2420. }
  2421. }
  2422. const size_t offs = file_offset(ggml_get_name(cur));
  2423. if (use_mmap && mapping) {
  2424. if (buf_mmap && cur->data == nullptr) {
  2425. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2426. if (lmlock) {
  2427. lmlock->grow_to(offs + ggml_nbytes(cur));
  2428. }
  2429. mmap_used_first = std::min(mmap_used_first, offs);
  2430. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2431. } else {
  2432. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2433. }
  2434. } else {
  2435. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2436. file.seek(offs, SEEK_SET);
  2437. file.read_raw(cur->data, ggml_nbytes(cur));
  2438. } else {
  2439. read_buf.resize(ggml_nbytes(cur));
  2440. file.seek(offs, SEEK_SET);
  2441. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2442. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2443. }
  2444. }
  2445. size_done += ggml_nbytes(cur);
  2446. }
  2447. // check if this is the last call and do final cleanup
  2448. if (size_done >= size_data) {
  2449. // unmap offloaded tensors and metadata
  2450. if (use_mmap && mapping) {
  2451. mapping->unmap_fragment(0, mmap_used_first);
  2452. if (mmap_used_last != 0) {
  2453. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2454. }
  2455. }
  2456. if (progress_callback) {
  2457. // Even though the model is done loading, we still honor
  2458. // cancellation since we need to free allocations.
  2459. return progress_callback(1.0f, progress_callback_user_data);
  2460. }
  2461. }
  2462. return true;
  2463. }
  2464. };
  2465. //
  2466. // load LLaMA models
  2467. //
  2468. static const char * llama_model_arch_name(llm_arch arch) {
  2469. auto it = LLM_ARCH_NAMES.find(arch);
  2470. if (it == LLM_ARCH_NAMES.end()) {
  2471. return "unknown";
  2472. }
  2473. return it->second;
  2474. }
  2475. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2476. if (ftype & LLAMA_FTYPE_GUESSED) {
  2477. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2478. }
  2479. switch (ftype) {
  2480. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2481. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2482. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2483. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2484. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2485. return "Q4_1, some F16";
  2486. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2487. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2488. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2489. // K-quants
  2490. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2491. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2492. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2493. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2494. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2495. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2496. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2497. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2498. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2499. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2500. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2501. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2502. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2503. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2504. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2505. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2506. default: return "unknown, may not work";
  2507. }
  2508. }
  2509. static const char * llama_model_type_name(e_model type) {
  2510. switch (type) {
  2511. case MODEL_22M: return "22M";
  2512. case MODEL_33M: return "33M";
  2513. case MODEL_109M: return "109M";
  2514. case MODEL_137M: return "137M";
  2515. case MODEL_0_5B: return "0.5B";
  2516. case MODEL_1B: return "1B";
  2517. case MODEL_2B: return "2B";
  2518. case MODEL_3B: return "3B";
  2519. case MODEL_7B: return "7B";
  2520. case MODEL_8B: return "8B";
  2521. case MODEL_13B: return "13B";
  2522. case MODEL_14B: return "14B";
  2523. case MODEL_15B: return "15B";
  2524. case MODEL_20B: return "20B";
  2525. case MODEL_30B: return "30B";
  2526. case MODEL_34B: return "34B";
  2527. case MODEL_40B: return "40B";
  2528. case MODEL_65B: return "65B";
  2529. case MODEL_70B: return "70B";
  2530. case MODEL_SMALL: return "0.1B";
  2531. case MODEL_MEDIUM: return "0.4B";
  2532. case MODEL_LARGE: return "0.8B";
  2533. case MODEL_XL: return "1.5B";
  2534. default: return "?B";
  2535. }
  2536. }
  2537. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2538. switch (type) {
  2539. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2540. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2541. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2542. default: return "unknown";
  2543. }
  2544. }
  2545. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2546. model.arch = ml.get_arch();
  2547. if (model.arch == LLM_ARCH_UNKNOWN) {
  2548. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2549. }
  2550. }
  2551. static void llm_load_hparams(
  2552. llama_model_loader & ml,
  2553. llama_model & model) {
  2554. auto & hparams = model.hparams;
  2555. const gguf_context * ctx = ml.ctx_gguf;
  2556. // get metadata as string
  2557. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2558. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2559. if (type == GGUF_TYPE_ARRAY) {
  2560. continue;
  2561. }
  2562. const char * name = gguf_get_key(ctx, i);
  2563. const std::string value = gguf_kv_to_str(ctx, i);
  2564. model.gguf_kv.emplace(name, value);
  2565. }
  2566. // get general kv
  2567. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2568. // get hparams kv
  2569. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2570. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2571. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2572. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2573. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2574. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2575. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2576. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2577. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2578. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2579. if (hparams.n_expert > 0) {
  2580. GGML_ASSERT(hparams.n_expert_used > 0);
  2581. } else {
  2582. GGML_ASSERT(hparams.n_expert_used == 0);
  2583. }
  2584. // n_head_kv is optional, default to n_head
  2585. hparams.n_head_kv = hparams.n_head;
  2586. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2587. bool rope_finetuned = false;
  2588. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2589. hparams.rope_finetuned = rope_finetuned;
  2590. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2591. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2592. // rope_freq_base (optional)
  2593. hparams.rope_freq_base_train = 10000.0f;
  2594. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2595. std::string rope_scaling("linear");
  2596. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2597. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2598. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2599. // rope_freq_scale (inverse of the kv) is optional
  2600. float ropescale = 0.0f;
  2601. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2602. // try the old key name
  2603. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2604. }
  2605. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2606. // sanity check for n_rot (optional)
  2607. {
  2608. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2609. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2610. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2611. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2612. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2613. }
  2614. }
  2615. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2616. // gpt-j n_rot = rotary_dim
  2617. }
  2618. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2619. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2620. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2621. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2622. // arch-specific KVs
  2623. switch (model.arch) {
  2624. case LLM_ARCH_LLAMA:
  2625. {
  2626. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2627. switch (hparams.n_layer) {
  2628. case 22: model.type = e_model::MODEL_1B; break;
  2629. case 26: model.type = e_model::MODEL_3B; break;
  2630. case 32: model.type = e_model::MODEL_7B; break;
  2631. case 40: model.type = e_model::MODEL_13B; break;
  2632. case 48: model.type = e_model::MODEL_34B; break;
  2633. case 60: model.type = e_model::MODEL_30B; break;
  2634. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2635. default: model.type = e_model::MODEL_UNKNOWN;
  2636. }
  2637. } break;
  2638. case LLM_ARCH_MINICPM:
  2639. {
  2640. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2641. switch (hparams.n_layer) {
  2642. case 40: model.type = e_model::MODEL_2B; break;
  2643. default: model.type = e_model::MODEL_UNKNOWN;
  2644. }
  2645. } break;
  2646. case LLM_ARCH_FALCON:
  2647. {
  2648. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2649. switch (hparams.n_layer) {
  2650. case 32: model.type = e_model::MODEL_7B; break;
  2651. case 60: model.type = e_model::MODEL_40B; break;
  2652. default: model.type = e_model::MODEL_UNKNOWN;
  2653. }
  2654. } break;
  2655. case LLM_ARCH_BAICHUAN:
  2656. {
  2657. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2658. switch (hparams.n_layer) {
  2659. case 32: model.type = e_model::MODEL_7B; break;
  2660. case 40: model.type = e_model::MODEL_13B; break;
  2661. default: model.type = e_model::MODEL_UNKNOWN;
  2662. }
  2663. if (model.type == e_model::MODEL_13B) {
  2664. // TODO: become GGUF KV parameter
  2665. hparams.f_max_alibi_bias = 8.0f;
  2666. }
  2667. } break;
  2668. case LLM_ARCH_STARCODER:
  2669. {
  2670. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2671. switch (hparams.n_layer) {
  2672. case 24: model.type = e_model::MODEL_1B; break;
  2673. case 36: model.type = e_model::MODEL_3B; break;
  2674. case 42: model.type = e_model::MODEL_7B; break;
  2675. case 40: model.type = e_model::MODEL_15B; break;
  2676. default: model.type = e_model::MODEL_UNKNOWN;
  2677. }
  2678. } break;
  2679. case LLM_ARCH_PERSIMMON:
  2680. {
  2681. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2682. switch (hparams.n_layer) {
  2683. case 36: model.type = e_model::MODEL_8B; break;
  2684. default: model.type = e_model::MODEL_UNKNOWN;
  2685. }
  2686. } break;
  2687. case LLM_ARCH_REFACT:
  2688. {
  2689. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2690. switch (hparams.n_layer) {
  2691. case 32: model.type = e_model::MODEL_1B; break;
  2692. default: model.type = e_model::MODEL_UNKNOWN;
  2693. }
  2694. // TODO: become GGUF KV parameter
  2695. hparams.f_max_alibi_bias = 8.0f;
  2696. } break;
  2697. case LLM_ARCH_BERT:
  2698. {
  2699. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2700. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2701. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2702. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2703. switch (hparams.n_layer) {
  2704. case 3:
  2705. model.type = e_model::MODEL_17M; break; // bge-micro
  2706. case 6:
  2707. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2708. case 12:
  2709. switch (hparams.n_embd) {
  2710. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2711. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2712. } break;
  2713. case 24:
  2714. model.type = e_model::MODEL_335M; break; // bge-large
  2715. }
  2716. } break;
  2717. case LLM_ARCH_NOMIC_BERT:
  2718. {
  2719. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2720. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2721. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2722. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2723. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2724. model.type = e_model::MODEL_137M;
  2725. }
  2726. } break;
  2727. case LLM_ARCH_BLOOM:
  2728. {
  2729. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2730. switch (hparams.n_layer) {
  2731. case 24: model.type = e_model::MODEL_1B; break;
  2732. case 30:
  2733. switch (hparams.n_embd) {
  2734. case 2560: model.type = e_model::MODEL_3B; break;
  2735. case 4096: model.type = e_model::MODEL_7B; break;
  2736. } break;
  2737. }
  2738. // TODO: become GGUF KV parameter
  2739. hparams.f_max_alibi_bias = 8.0f;
  2740. } break;
  2741. case LLM_ARCH_MPT:
  2742. {
  2743. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2744. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2745. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2746. switch (hparams.n_layer) {
  2747. case 32: model.type = e_model::MODEL_7B; break;
  2748. case 48: model.type = e_model::MODEL_30B; break;
  2749. default: model.type = e_model::MODEL_UNKNOWN;
  2750. }
  2751. } break;
  2752. case LLM_ARCH_STABLELM:
  2753. {
  2754. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2755. switch (hparams.n_layer) {
  2756. case 24: model.type = e_model::MODEL_1B; break;
  2757. case 32: model.type = e_model::MODEL_3B; break;
  2758. default: model.type = e_model::MODEL_UNKNOWN;
  2759. }
  2760. } break;
  2761. case LLM_ARCH_QWEN:
  2762. {
  2763. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2764. switch (hparams.n_layer) {
  2765. case 32: model.type = e_model::MODEL_7B; break;
  2766. case 40: model.type = e_model::MODEL_13B; break;
  2767. default: model.type = e_model::MODEL_UNKNOWN;
  2768. }
  2769. } break;
  2770. case LLM_ARCH_QWEN2:
  2771. {
  2772. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2773. switch (hparams.n_layer) {
  2774. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2775. case 32: model.type = e_model::MODEL_7B; break;
  2776. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2777. case 80: model.type = e_model::MODEL_70B; break;
  2778. default: model.type = e_model::MODEL_UNKNOWN;
  2779. }
  2780. } break;
  2781. case LLM_ARCH_PHI2:
  2782. {
  2783. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2784. switch (hparams.n_layer) {
  2785. case 24: model.type = e_model::MODEL_1B; break;
  2786. case 32: model.type = e_model::MODEL_3B; break;
  2787. default: model.type = e_model::MODEL_UNKNOWN;
  2788. }
  2789. } break;
  2790. case LLM_ARCH_PLAMO:
  2791. {
  2792. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2793. switch (hparams.n_layer) {
  2794. case 40: model.type = e_model::MODEL_13B; break;
  2795. default: model.type = e_model::MODEL_UNKNOWN;
  2796. }
  2797. } break;
  2798. case LLM_ARCH_GPT2:
  2799. {
  2800. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2801. switch (hparams.n_layer) {
  2802. case 12: model.type = e_model::MODEL_SMALL; break;
  2803. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2804. case 36: model.type = e_model::MODEL_LARGE; break;
  2805. case 48: model.type = e_model::MODEL_XL; break;
  2806. default: model.type = e_model::MODEL_UNKNOWN;
  2807. }
  2808. } break;
  2809. case LLM_ARCH_CODESHELL:
  2810. {
  2811. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2812. switch (hparams.n_layer) {
  2813. case 42: model.type = e_model::MODEL_SMALL; break;
  2814. default: model.type = e_model::MODEL_UNKNOWN;
  2815. }
  2816. } break;
  2817. case LLM_ARCH_ORION:
  2818. {
  2819. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2820. switch (hparams.n_layer) {
  2821. case 40: model.type = e_model::MODEL_14B; break;
  2822. default: model.type = e_model::MODEL_UNKNOWN;
  2823. }
  2824. } break;
  2825. case LLM_ARCH_INTERNLM2:
  2826. {
  2827. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2828. switch (hparams.n_layer) {
  2829. case 32: model.type = e_model::MODEL_7B; break;
  2830. case 48: model.type = e_model::MODEL_20B; break;
  2831. default: model.type = e_model::MODEL_UNKNOWN;
  2832. }
  2833. } break;
  2834. case LLM_ARCH_GEMMA:
  2835. {
  2836. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2837. switch (hparams.n_layer) {
  2838. case 18: model.type = e_model::MODEL_2B; break;
  2839. case 28: model.type = e_model::MODEL_7B; break;
  2840. default: model.type = e_model::MODEL_UNKNOWN;
  2841. }
  2842. } break;
  2843. default: (void)0;
  2844. }
  2845. model.ftype = ml.ftype;
  2846. if (hparams.f_max_alibi_bias > 0.0f) {
  2847. hparams.need_kq_pos = true;
  2848. }
  2849. }
  2850. // TODO: This should probably be in llama.h
  2851. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2852. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2853. static void llm_load_vocab(
  2854. llama_model_loader & ml,
  2855. llama_model & model) {
  2856. auto & vocab = model.vocab;
  2857. struct gguf_context * ctx = ml.ctx_gguf;
  2858. const auto kv = LLM_KV(model.arch);
  2859. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2860. if (token_idx == -1) {
  2861. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2862. }
  2863. const float * scores = nullptr;
  2864. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2865. if (score_idx != -1) {
  2866. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2867. }
  2868. const int * toktypes = nullptr;
  2869. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2870. if (toktype_idx != -1) {
  2871. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2872. }
  2873. // determine vocab type
  2874. {
  2875. std::string tokenizer_name;
  2876. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2877. if (tokenizer_name == "llama") {
  2878. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2879. // default special tokens
  2880. vocab.special_bos_id = 1;
  2881. vocab.special_eos_id = 2;
  2882. vocab.special_unk_id = 0;
  2883. vocab.special_sep_id = -1;
  2884. vocab.special_pad_id = -1;
  2885. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2886. if (add_space_prefix_keyidx != -1) {
  2887. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2888. } // The default value of add_space_prefix is true.
  2889. } else if (tokenizer_name == "gpt2") {
  2890. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2891. // read bpe merges and populate bpe ranks
  2892. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2893. if (merges_keyidx == -1) {
  2894. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2895. }
  2896. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2897. for (int i = 0; i < n_merges; i++) {
  2898. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2899. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2900. std::string first;
  2901. std::string second;
  2902. const size_t pos = word.find(' ', 1);
  2903. if (pos != std::string::npos) {
  2904. first = word.substr(0, pos);
  2905. second = word.substr(pos + 1);
  2906. }
  2907. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2908. }
  2909. // default special tokens
  2910. vocab.special_bos_id = 11;
  2911. vocab.special_eos_id = 11;
  2912. vocab.special_unk_id = -1;
  2913. vocab.special_sep_id = -1;
  2914. vocab.special_pad_id = -1;
  2915. } else if (tokenizer_name == "bert") {
  2916. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  2917. // default special tokens
  2918. vocab.special_bos_id = 101;
  2919. vocab.special_eos_id = 102;
  2920. vocab.special_unk_id = 100;
  2921. vocab.special_sep_id = -1;
  2922. vocab.special_pad_id = -1;
  2923. vocab.add_space_prefix = false;
  2924. } else {
  2925. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2926. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2927. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2928. }
  2929. }
  2930. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2931. vocab.id_to_token.resize(n_vocab);
  2932. for (uint32_t i = 0; i < n_vocab; i++) {
  2933. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2934. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2935. vocab.token_to_id[word] = i;
  2936. auto & token_data = vocab.id_to_token[i];
  2937. token_data.text = std::move(word);
  2938. token_data.score = scores ? scores[i] : 0.0f;
  2939. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2940. }
  2941. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2942. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2943. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2944. try {
  2945. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2946. } catch (const std::exception & e) {
  2947. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  2948. vocab.linefeed_id = vocab.special_pad_id;
  2949. }
  2950. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  2951. vocab.linefeed_id = vocab.special_pad_id;
  2952. } else {
  2953. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2954. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2955. vocab.linefeed_id = ids[0];
  2956. }
  2957. // special tokens
  2958. {
  2959. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2960. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2961. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2962. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2963. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2964. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2965. };
  2966. for (const auto & it : special_token_types) {
  2967. const std::string & key = kv(std::get<0>(it));
  2968. int32_t & id = std::get<1>(it);
  2969. uint32_t new_id;
  2970. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2971. continue;
  2972. }
  2973. if (new_id >= vocab.id_to_token.size()) {
  2974. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2975. __func__, key.c_str(), new_id, id);
  2976. } else {
  2977. id = new_id;
  2978. }
  2979. }
  2980. // Handle add_bos_token and add_eos_token
  2981. {
  2982. bool temp = true;
  2983. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2984. vocab.special_add_bos = int(temp);
  2985. }
  2986. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2987. vocab.special_add_eos = int(temp);
  2988. }
  2989. }
  2990. }
  2991. // build special tokens cache
  2992. {
  2993. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2994. // and will always be correctly labeled in 'added_tokens.json' etc.
  2995. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2996. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2997. // are special tokens.
  2998. // From testing, this appears to correlate 1:1 with special tokens.
  2999. //
  3000. // Counting special tokens and verifying in only one direction
  3001. // is sufficient to detect difference in those two sets.
  3002. //
  3003. uint32_t special_tokens_count_by_type = 0;
  3004. uint32_t special_tokens_count_from_verification = 0;
  3005. bool special_tokens_definition_mismatch = false;
  3006. for (const auto & t : vocab.token_to_id) {
  3007. const auto & token = t.first;
  3008. const auto & id = t.second;
  3009. // Count all non-normal tokens in the vocab while iterating
  3010. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3011. special_tokens_count_by_type++;
  3012. }
  3013. // Skip single character tokens
  3014. if (token.length() > 1) {
  3015. bool is_tokenizable = false;
  3016. // Split token string representation in two, in all possible ways
  3017. // and check if both halves can be matched to a valid token
  3018. for (unsigned i = 1; i < token.length();) {
  3019. const auto left = token.substr(0, i);
  3020. const auto right = token.substr(i);
  3021. // check if we didnt partition in the middle of a utf sequence
  3022. auto utf = utf8_len(left.at(left.length() - 1));
  3023. if (utf == 1) {
  3024. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3025. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3026. is_tokenizable = true;
  3027. break;
  3028. }
  3029. i++;
  3030. } else {
  3031. // skip over the rest of multibyte utf sequence
  3032. i += utf - 1;
  3033. }
  3034. }
  3035. if (!is_tokenizable) {
  3036. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3037. // it's faster to re-filter them here, since there are way less candidates now
  3038. // Calculate a total "utf" length of a token string representation
  3039. size_t utf8_str_len = 0;
  3040. for (unsigned i = 0; i < token.length();) {
  3041. utf8_str_len++;
  3042. i += utf8_len(token.at(i));
  3043. }
  3044. // And skip the ones which are one character
  3045. if (utf8_str_len > 1) {
  3046. // At this point what we have left are special tokens only
  3047. vocab.special_tokens_cache[token] = id;
  3048. // Count manually found special tokens
  3049. special_tokens_count_from_verification++;
  3050. // If this manually found special token is not marked as such, flag a mismatch
  3051. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3052. special_tokens_definition_mismatch = true;
  3053. }
  3054. }
  3055. }
  3056. }
  3057. }
  3058. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3059. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3060. __func__,
  3061. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3062. special_tokens_count_by_type, vocab.id_to_token.size()
  3063. );
  3064. } else {
  3065. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3066. __func__,
  3067. special_tokens_count_from_verification, vocab.id_to_token.size()
  3068. );
  3069. }
  3070. }
  3071. }
  3072. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3073. const auto & hparams = model.hparams;
  3074. const auto & vocab = model.vocab;
  3075. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3076. // hparams
  3077. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3078. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3079. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3080. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3081. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3082. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3083. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3084. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3085. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3086. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3087. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3088. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3089. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3090. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3091. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3092. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3093. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3094. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3095. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3096. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3097. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3098. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3099. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3100. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3101. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3102. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3103. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3104. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3105. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3106. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3107. if (ml.n_elements >= 1e12) {
  3108. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3109. } else if (ml.n_elements >= 1e9) {
  3110. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3111. } else if (ml.n_elements >= 1e6) {
  3112. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3113. } else {
  3114. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3115. }
  3116. if (ml.n_bytes < GiB) {
  3117. 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);
  3118. } else {
  3119. 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);
  3120. }
  3121. // general kv
  3122. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3123. // special tokens
  3124. 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() ); }
  3125. 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() ); }
  3126. 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() ); }
  3127. 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() ); }
  3128. 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() ); }
  3129. 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() ); }
  3130. }
  3131. // Returns false if cancelled by progress_callback
  3132. static bool llm_load_tensors(
  3133. llama_model_loader & ml,
  3134. llama_model & model,
  3135. int n_gpu_layers,
  3136. enum llama_split_mode split_mode,
  3137. int main_gpu,
  3138. const float * tensor_split,
  3139. bool use_mlock,
  3140. llama_progress_callback progress_callback,
  3141. void * progress_callback_user_data) {
  3142. model.t_start_us = ggml_time_us();
  3143. auto & hparams = model.hparams;
  3144. model.split_mode = split_mode;
  3145. model.main_gpu = main_gpu;
  3146. model.n_gpu_layers = n_gpu_layers;
  3147. const int64_t n_layer = hparams.n_layer;
  3148. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3149. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3150. model.buft_input = llama_default_buffer_type_cpu(true);
  3151. model.buft_layer.resize(n_layer);
  3152. // assign cpu layers
  3153. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3154. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3155. }
  3156. if (split_mode == LLAMA_SPLIT_LAYER) {
  3157. // calculate the split points
  3158. int device_count = llama_get_device_count();
  3159. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3160. std::vector<float> splits(device_count);
  3161. if (all_zero) {
  3162. // default split, by free memory
  3163. for (int i = 0; i < device_count; ++i) {
  3164. splits[i] = llama_get_device_memory(i);
  3165. }
  3166. } else {
  3167. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3168. }
  3169. // sum and normalize the splits to get the split points
  3170. float split_sum = 0.0f;
  3171. for (int i = 0; i < device_count; ++i) {
  3172. split_sum += splits[i];
  3173. splits[i] = split_sum;
  3174. }
  3175. for (int i = 0; i < device_count; ++i) {
  3176. splits[i] /= split_sum;
  3177. }
  3178. // assign the repeating layers to the devices according to the splits
  3179. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3180. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3181. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3182. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3183. }
  3184. // assign the output layer
  3185. if (n_gpu_layers > n_layer) {
  3186. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3187. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3188. } else {
  3189. model.buft_output = llama_default_buffer_type_cpu(true);
  3190. }
  3191. } else {
  3192. ggml_backend_buffer_type_t split_buft;
  3193. if (split_mode == LLAMA_SPLIT_ROW) {
  3194. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3195. } else {
  3196. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  3197. split_buft = llama_default_buffer_type_offload(main_gpu);
  3198. }
  3199. // assign the repeating layers
  3200. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3201. model.buft_layer[i] = {
  3202. split_buft,
  3203. llama_default_buffer_type_offload(main_gpu)
  3204. };
  3205. }
  3206. // assign the output layer
  3207. if (n_gpu_layers > n_layer) {
  3208. model.buft_output = {
  3209. split_buft,
  3210. llama_default_buffer_type_offload(main_gpu)
  3211. };
  3212. } else {
  3213. model.buft_output = llama_default_buffer_type_cpu(true);
  3214. }
  3215. }
  3216. // count used buffer types
  3217. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3218. buft_layer_count[model.buft_input.buft]++;
  3219. buft_layer_count[model.buft_input.buft_matrix]++;
  3220. buft_layer_count[model.buft_output.buft]++;
  3221. buft_layer_count[model.buft_output.buft_matrix]++;
  3222. for (int64_t i = 0; i < n_layer; ++i) {
  3223. buft_layer_count[model.buft_layer[i].buft]++;
  3224. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3225. }
  3226. // create one context per buffer type
  3227. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3228. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3229. for (auto & it : buft_layer_count) {
  3230. struct ggml_init_params params = {
  3231. /*.mem_size =*/ ctx_size,
  3232. /*.mem_buffer =*/ NULL,
  3233. /*.no_alloc =*/ true,
  3234. };
  3235. ggml_context * ctx = ggml_init(params);
  3236. if (!ctx) {
  3237. throw std::runtime_error(format("failed to create context"));
  3238. }
  3239. ctx_map[it.first] = ctx;
  3240. model.ctxs.push_back(ctx);
  3241. }
  3242. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3243. // create tensors for the weights
  3244. {
  3245. const int64_t n_embd = hparams.n_embd;
  3246. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3247. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3248. const int64_t n_embd_gqa = n_embd_v_gqa;
  3249. const int64_t n_vocab = hparams.n_vocab;
  3250. const int64_t n_vocab_type = hparams.n_vocab_type;
  3251. const int64_t n_ff = hparams.n_ff;
  3252. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3253. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3254. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3255. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3256. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3257. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3258. model.layers.resize(n_layer);
  3259. const auto tn = LLM_TN(model.arch);
  3260. switch (model.arch) {
  3261. case LLM_ARCH_LLAMA:
  3262. case LLM_ARCH_REFACT:
  3263. case LLM_ARCH_MINICPM:
  3264. {
  3265. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3266. // output
  3267. {
  3268. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3269. if (model.arch != LLM_ARCH_MINICPM){
  3270. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3271. }
  3272. }
  3273. for (int i = 0; i < n_layer; ++i) {
  3274. ggml_context * ctx_layer = ctx_for_layer(i);
  3275. ggml_context * ctx_split = ctx_for_layer_split(i);
  3276. auto & layer = model.layers[i];
  3277. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3278. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3279. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3280. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3281. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3282. // optional bias tensors
  3283. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3284. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3285. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3286. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3287. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3288. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3289. if (layer.ffn_gate_inp == nullptr) {
  3290. GGML_ASSERT(hparams.n_expert == 0);
  3291. GGML_ASSERT(hparams.n_expert_used == 0);
  3292. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3293. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3294. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3295. } else {
  3296. GGML_ASSERT(hparams.n_expert > 0);
  3297. GGML_ASSERT(hparams.n_expert_used > 0);
  3298. // MoE branch
  3299. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3300. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3301. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3302. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3303. }
  3304. }
  3305. }
  3306. } break;
  3307. case LLM_ARCH_BAICHUAN:
  3308. {
  3309. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3310. {
  3311. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3312. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3313. }
  3314. for (int i = 0; i < n_layer; ++i) {
  3315. ggml_context * ctx_layer = ctx_for_layer(i);
  3316. ggml_context * ctx_split = ctx_for_layer_split(i);
  3317. auto & layer = model.layers[i];
  3318. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3319. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3320. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3321. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3322. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3323. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3324. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3325. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3326. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3327. }
  3328. } break;
  3329. case LLM_ARCH_FALCON:
  3330. {
  3331. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3332. // output
  3333. {
  3334. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3335. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3336. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3337. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3338. } else {
  3339. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3340. ml.n_created--; // artificial tensor
  3341. ml.size_data += ggml_nbytes(model.output);
  3342. }
  3343. }
  3344. for (int i = 0; i < n_layer; ++i) {
  3345. ggml_context * ctx_layer = ctx_for_layer(i);
  3346. ggml_context * ctx_split = ctx_for_layer_split(i);
  3347. auto & layer = model.layers[i];
  3348. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3349. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3350. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3351. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3352. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3353. }
  3354. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3355. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3356. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3357. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3358. }
  3359. } break;
  3360. case LLM_ARCH_STARCODER:
  3361. {
  3362. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3363. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3364. // output
  3365. {
  3366. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3367. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3368. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3369. }
  3370. for (int i = 0; i < n_layer; ++i) {
  3371. ggml_context * ctx_layer = ctx_for_layer(i);
  3372. ggml_context * ctx_split = ctx_for_layer_split(i);
  3373. auto & layer = model.layers[i];
  3374. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3375. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3376. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3377. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3378. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3379. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3380. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3381. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3382. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3383. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3384. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3385. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3386. }
  3387. } break;
  3388. case LLM_ARCH_PERSIMMON:
  3389. {
  3390. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3391. {
  3392. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3393. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3394. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3395. }
  3396. for (int i = 0; i < n_layer; ++i) {
  3397. ggml_context * ctx_layer = ctx_for_layer(i);
  3398. ggml_context * ctx_split = ctx_for_layer_split(i);
  3399. auto & layer = model.layers[i];
  3400. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3401. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3402. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3403. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3404. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3405. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3406. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3407. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3408. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3409. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3410. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3411. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3412. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3413. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3414. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3415. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3416. }
  3417. } break;
  3418. case LLM_ARCH_BERT:
  3419. case LLM_ARCH_NOMIC_BERT:
  3420. {
  3421. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3422. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3423. if (model.arch == LLM_ARCH_BERT) {
  3424. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3425. }
  3426. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3427. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3428. for (int i = 0; i < n_layer; ++i) {
  3429. ggml_context * ctx_layer = ctx_for_layer(i);
  3430. ggml_context * ctx_split = ctx_for_layer_split(i);
  3431. auto & layer = model.layers[i];
  3432. if (model.arch == LLM_ARCH_BERT) {
  3433. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3434. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3435. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3436. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3437. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3438. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3439. } else {
  3440. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3441. }
  3442. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3443. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3444. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3445. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3446. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3447. if (model.arch == LLM_ARCH_BERT) {
  3448. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3449. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3450. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3451. } else {
  3452. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3453. }
  3454. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3455. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3456. }
  3457. } break;
  3458. case LLM_ARCH_BLOOM:
  3459. {
  3460. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3461. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3462. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3463. // output
  3464. {
  3465. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3466. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3467. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3468. }
  3469. for (int i = 0; i < n_layer; ++i) {
  3470. ggml_context * ctx_layer = ctx_for_layer(i);
  3471. ggml_context * ctx_split = ctx_for_layer_split(i);
  3472. auto & layer = model.layers[i];
  3473. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3474. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3475. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3476. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3477. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3478. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3479. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3480. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3481. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3482. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3483. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3484. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3485. }
  3486. } break;
  3487. case LLM_ARCH_MPT:
  3488. {
  3489. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3490. // output
  3491. {
  3492. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3493. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3494. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3495. }
  3496. for (int i = 0; i < n_layer; ++i) {
  3497. ggml_context * ctx_layer = ctx_for_layer(i);
  3498. ggml_context * ctx_split = ctx_for_layer_split(i);
  3499. auto & layer = model.layers[i];
  3500. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3501. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3502. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3503. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3504. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3505. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3506. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3507. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3508. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3509. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3510. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3511. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3512. // AWQ ScaleActivation layer
  3513. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3514. }
  3515. } break;
  3516. case LLM_ARCH_STABLELM:
  3517. {
  3518. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3519. // output
  3520. {
  3521. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3522. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3523. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3524. }
  3525. for (int i = 0; i < n_layer; ++i) {
  3526. ggml_context * ctx_layer = ctx_for_layer(i);
  3527. ggml_context * ctx_split = ctx_for_layer_split(i);
  3528. auto & layer = model.layers[i];
  3529. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3530. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3531. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3532. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3533. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3534. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3535. // optional bias tensors, present in Stable LM 2 1.6B
  3536. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3537. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3538. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3539. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3540. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3541. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3542. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3543. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3544. }
  3545. } break;
  3546. case LLM_ARCH_QWEN:
  3547. {
  3548. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3549. // output
  3550. {
  3551. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3552. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3553. }
  3554. for (int i = 0; i < n_layer; ++i) {
  3555. ggml_context * ctx_layer = ctx_for_layer(i);
  3556. ggml_context * ctx_split = ctx_for_layer_split(i);
  3557. auto & layer = model.layers[i];
  3558. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3559. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3560. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3561. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3562. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3563. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3564. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3565. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3566. }
  3567. } break;
  3568. case LLM_ARCH_QWEN2:
  3569. {
  3570. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3571. // output
  3572. {
  3573. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3574. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3575. }
  3576. for (int i = 0; i < n_layer; ++i) {
  3577. ggml_context * ctx_layer = ctx_for_layer(i);
  3578. ggml_context * ctx_split = ctx_for_layer_split(i);
  3579. auto & layer = model.layers[i];
  3580. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3581. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3582. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3583. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3584. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3585. // optional bias tensors
  3586. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3587. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3588. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3589. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3590. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3591. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3592. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3593. }
  3594. } break;
  3595. case LLM_ARCH_PHI2:
  3596. {
  3597. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3598. // output
  3599. {
  3600. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3601. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3602. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3603. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3604. }
  3605. for (int i = 0; i < n_layer; ++i) {
  3606. ggml_context * ctx_layer = ctx_for_layer(i);
  3607. ggml_context * ctx_split = ctx_for_layer_split(i);
  3608. auto & layer = model.layers[i];
  3609. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3610. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3611. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3612. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3613. if (layer.wqkv == nullptr) {
  3614. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3615. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3616. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3617. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3618. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3619. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3620. }
  3621. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3622. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3623. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3624. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3625. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3626. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3627. }
  3628. } break;
  3629. case LLM_ARCH_PLAMO:
  3630. {
  3631. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3632. // output
  3633. {
  3634. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3635. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3636. }
  3637. for (int i = 0; i < n_layer; ++i) {
  3638. ggml_context * ctx_layer = ctx_for_layer(i);
  3639. ggml_context * ctx_split = ctx_for_layer_split(i);
  3640. auto & layer = model.layers[i];
  3641. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3642. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3643. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3644. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3645. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3646. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3647. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3648. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3649. }
  3650. } break;
  3651. case LLM_ARCH_GPT2:
  3652. {
  3653. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3654. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3655. // output
  3656. {
  3657. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3658. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {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.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3667. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3668. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3669. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3670. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3671. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3672. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3673. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3674. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3675. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3676. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3677. }
  3678. } break;
  3679. case LLM_ARCH_CODESHELL:
  3680. {
  3681. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3682. // output
  3683. {
  3684. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3685. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3686. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3687. }
  3688. for (int i = 0; i < n_layer; ++i) {
  3689. ggml_context * ctx_layer = ctx_for_layer(i);
  3690. ggml_context * ctx_split = ctx_for_layer_split(i);
  3691. auto & layer = model.layers[i];
  3692. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3693. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3694. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3695. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3696. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3697. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3698. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3699. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3700. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3701. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3702. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3703. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3704. }
  3705. } break;
  3706. case LLM_ARCH_ORION:
  3707. {
  3708. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3709. {
  3710. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3711. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3712. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3713. }
  3714. for (int i = 0; i < n_layer; ++i) {
  3715. ggml_context * ctx_layer = ctx_for_layer(i);
  3716. ggml_context * ctx_split = ctx_for_layer_split(i);
  3717. auto & layer = model.layers[i];
  3718. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3719. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3720. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3721. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3722. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3723. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3724. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3725. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3726. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3727. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3728. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3729. }
  3730. } break;
  3731. case LLM_ARCH_INTERNLM2:
  3732. {
  3733. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3734. // output
  3735. {
  3736. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3737. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3738. }
  3739. for (int i = 0; i < n_layer; ++i) {
  3740. ggml_context * ctx_layer = ctx_for_layer(i);
  3741. ggml_context * ctx_split = ctx_for_layer_split(i);
  3742. auto & layer = model.layers[i];
  3743. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3744. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3745. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3746. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3747. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3748. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3749. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3750. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3751. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3752. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3753. }
  3754. } break;
  3755. case LLM_ARCH_GEMMA:
  3756. {
  3757. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3758. // output
  3759. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3760. 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
  3761. ml.n_created--; // artificial tensor
  3762. ml.size_data += ggml_nbytes(model.output);
  3763. const int64_t n_ff = hparams.n_ff;
  3764. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3765. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3766. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3767. for (uint32_t i = 0; i < n_layer; ++i) {
  3768. ggml_context * ctx_layer = ctx_for_layer(i);
  3769. ggml_context * ctx_split = ctx_for_layer_split(i);
  3770. auto & layer = model.layers[i];
  3771. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3772. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3773. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3774. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3775. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3776. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3777. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3778. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3779. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3780. }
  3781. } break;
  3782. default:
  3783. throw std::runtime_error("unknown architecture");
  3784. }
  3785. }
  3786. ml.done_getting_tensors();
  3787. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3788. // create the backend buffers
  3789. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3790. for (auto & it : ctx_map) {
  3791. ggml_backend_buffer_type_t buft = it.first;
  3792. ggml_context * ctx = it.second;
  3793. ggml_backend_buffer_t buf = nullptr;
  3794. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3795. // 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
  3796. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3797. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3798. size_t first, last;
  3799. ml.get_mapping_range(&first, &last, ctx);
  3800. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3801. }
  3802. #ifdef GGML_USE_METAL
  3803. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3804. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3805. size_t first, last;
  3806. ml.get_mapping_range(&first, &last, ctx);
  3807. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3808. }
  3809. #endif
  3810. else {
  3811. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3812. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3813. model.mlock_bufs.emplace_back(new llama_mlock);
  3814. auto & mlock_buf = model.mlock_bufs.back();
  3815. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3816. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3817. }
  3818. }
  3819. if (buf == nullptr) {
  3820. throw std::runtime_error("failed to allocate buffer");
  3821. }
  3822. // indicate that this buffer contains weights
  3823. // 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
  3824. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3825. model.bufs.push_back(buf);
  3826. ctx_bufs.emplace_back(ctx, buf);
  3827. }
  3828. if (llama_supports_gpu_offload()) {
  3829. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3830. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3831. if (n_gpu_layers > (int) hparams.n_layer) {
  3832. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3833. }
  3834. const int max_backend_supported_layers = hparams.n_layer + 1;
  3835. const int max_offloadable_layers = hparams.n_layer + 1;
  3836. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3837. }
  3838. // print memory requirements
  3839. for (ggml_backend_buffer_t buf : model.bufs) {
  3840. 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);
  3841. }
  3842. // populate tensors_by_name
  3843. for (ggml_context * ctx : model.ctxs) {
  3844. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3845. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3846. }
  3847. }
  3848. // load tensor data
  3849. for (auto & it : ctx_bufs) {
  3850. ggml_context * ctx = it.first;
  3851. ggml_backend_buffer_t buf = it.second;
  3852. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3853. return false;
  3854. }
  3855. }
  3856. model.mapping = std::move(ml.mapping);
  3857. // loading time will be recalculate after the first eval, so
  3858. // we take page faults deferred by mmap() into consideration
  3859. model.t_load_us = ggml_time_us() - model.t_start_us;
  3860. return true;
  3861. }
  3862. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3863. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3864. try {
  3865. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3866. model.hparams.vocab_only = params.vocab_only;
  3867. try {
  3868. llm_load_arch(ml, model);
  3869. } catch(const std::exception & e) {
  3870. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  3871. }
  3872. try {
  3873. llm_load_hparams(ml, model);
  3874. } catch(const std::exception & e) {
  3875. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  3876. }
  3877. try {
  3878. llm_load_vocab(ml, model);
  3879. } catch(const std::exception & e) {
  3880. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  3881. }
  3882. llm_load_print_meta(ml, model);
  3883. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3884. throw std::runtime_error("vocab size mismatch");
  3885. }
  3886. if (params.vocab_only) {
  3887. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3888. return 0;
  3889. }
  3890. #ifdef GGML_USE_KOMPUTE
  3891. if (params.n_gpu_layers > 0 && (
  3892. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3893. || !(
  3894. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3895. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3896. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3897. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3898. )
  3899. )) {
  3900. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3901. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3902. params.n_gpu_layers = 0;
  3903. }
  3904. #endif
  3905. if (!llm_load_tensors(
  3906. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3907. params.progress_callback, params.progress_callback_user_data
  3908. )) {
  3909. return -2;
  3910. }
  3911. } catch (const std::exception & err) {
  3912. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3913. return -1;
  3914. }
  3915. return 0;
  3916. }
  3917. //
  3918. // llm_build
  3919. //
  3920. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3921. enum llm_rope_type {
  3922. LLM_ROPE,
  3923. LLM_ROPE_NEOX,
  3924. LLM_ROPE_GLM,
  3925. };
  3926. enum llm_ffn_op_type {
  3927. LLM_FFN_SILU,
  3928. LLM_FFN_GELU,
  3929. LLM_FFN_RELU,
  3930. LLM_FFN_RELU_SQR,
  3931. };
  3932. enum llm_ffn_gate_type {
  3933. LLM_FFN_SEQ,
  3934. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3935. };
  3936. enum llm_norm_type {
  3937. LLM_NORM,
  3938. LLM_NORM_RMS,
  3939. };
  3940. static struct ggml_tensor * llm_build_inp_embd(
  3941. struct ggml_context * ctx,
  3942. const llama_hparams & hparams,
  3943. const llama_batch & batch,
  3944. struct ggml_tensor * tok_embd,
  3945. struct ggml_tensor * inp_tokens,
  3946. struct ggml_tensor * inp_embd,
  3947. const llm_build_cb & cb) {
  3948. const int64_t n_embd = hparams.n_embd;
  3949. struct ggml_tensor * inpL;
  3950. if (batch.token) {
  3951. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3952. cb(inp_tokens, "inp_tokens", -1);
  3953. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3954. } else {
  3955. #ifdef GGML_USE_MPI
  3956. GGML_ASSERT(false && "not implemented");
  3957. #endif
  3958. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3959. }
  3960. return inpL;
  3961. }
  3962. // Persimmon: n_rot = n_embd_head_k/2
  3963. // Other: n_rot = n_embd_head_k
  3964. static void llm_build_k_shift(
  3965. struct ggml_context * ctx,
  3966. const llama_hparams & hparams,
  3967. const llama_cparams & cparams,
  3968. const llama_kv_cache & kv,
  3969. struct ggml_cgraph * graph,
  3970. struct ggml_tensor * K_shift,
  3971. llm_rope_type type,
  3972. int64_t n_ctx,
  3973. float freq_base,
  3974. float freq_scale,
  3975. const llm_build_cb & cb) {
  3976. const int64_t n_layer = hparams.n_layer;
  3977. const int64_t n_head_kv = hparams.n_head_kv;
  3978. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3979. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3980. const int32_t n_rot = hparams.n_rot;
  3981. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3982. const float ext_factor = cparams.yarn_ext_factor;
  3983. const float attn_factor = cparams.yarn_attn_factor;
  3984. const float beta_fast = cparams.yarn_beta_fast;
  3985. const float beta_slow = cparams.yarn_beta_slow;
  3986. int rope_type = 0;
  3987. switch (type) {
  3988. case LLM_ROPE: rope_type = 0; break;
  3989. case LLM_ROPE_NEOX: rope_type = 2; break;
  3990. case LLM_ROPE_GLM: rope_type = 4; break;
  3991. }
  3992. for (int il = 0; il < n_layer; ++il) {
  3993. struct ggml_tensor * tmp =
  3994. // we rotate only the first n_rot dimensions
  3995. ggml_rope_custom_inplace(ctx,
  3996. ggml_view_3d(ctx, kv.k_l[il],
  3997. n_embd_head_k, n_head_kv, n_ctx,
  3998. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3999. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4000. 0),
  4001. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4002. ext_factor, attn_factor, beta_fast, beta_slow);
  4003. cb(tmp, "K_shifted", il);
  4004. ggml_build_forward_expand(graph, tmp);
  4005. }
  4006. }
  4007. static void llm_build_kv_store(
  4008. struct ggml_context * ctx,
  4009. const llama_hparams & hparams,
  4010. const llama_kv_cache & kv,
  4011. struct ggml_cgraph * graph,
  4012. struct ggml_tensor * k_cur,
  4013. struct ggml_tensor * v_cur,
  4014. int64_t n_ctx,
  4015. int32_t n_tokens,
  4016. int32_t kv_head,
  4017. const llm_build_cb & cb,
  4018. int64_t il) {
  4019. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4020. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4021. // compute the transposed [n_tokens, n_embd] V matrix
  4022. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4023. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4024. cb(v_cur_t, "v_cur_t", il);
  4025. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4026. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4027. cb(k_cache_view, "k_cache_view", il);
  4028. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4029. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4030. (kv_head)*ggml_element_size(kv.v_l[il]));
  4031. cb(v_cache_view, "v_cache_view", il);
  4032. // important: storing RoPE-ed version of K in the KV cache!
  4033. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4034. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4035. }
  4036. static struct ggml_tensor * llm_build_norm(
  4037. struct ggml_context * ctx,
  4038. struct ggml_tensor * cur,
  4039. const llama_hparams & hparams,
  4040. struct ggml_tensor * mw,
  4041. struct ggml_tensor * mb,
  4042. llm_norm_type type,
  4043. const llm_build_cb & cb,
  4044. int il) {
  4045. switch (type) {
  4046. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4047. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4048. }
  4049. if (mw || mb) {
  4050. cb(cur, "norm", il);
  4051. }
  4052. if (mw) {
  4053. cur = ggml_mul(ctx, cur, mw);
  4054. if (mb) {
  4055. cb(cur, "norm_w", il);
  4056. }
  4057. }
  4058. if (mb) {
  4059. cur = ggml_add(ctx, cur, mb);
  4060. }
  4061. return cur;
  4062. }
  4063. static struct ggml_tensor * llm_build_ffn(
  4064. struct ggml_context * ctx,
  4065. struct ggml_tensor * cur,
  4066. struct ggml_tensor * up,
  4067. struct ggml_tensor * up_b,
  4068. struct ggml_tensor * gate,
  4069. struct ggml_tensor * gate_b,
  4070. struct ggml_tensor * down,
  4071. struct ggml_tensor * down_b,
  4072. struct ggml_tensor * act_scales,
  4073. llm_ffn_op_type type_op,
  4074. llm_ffn_gate_type type_gate,
  4075. const llm_build_cb & cb,
  4076. int il) {
  4077. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4078. cb(tmp, "ffn_up", il);
  4079. if (up_b) {
  4080. tmp = ggml_add(ctx, tmp, up_b);
  4081. cb(tmp, "ffn_up_b", il);
  4082. }
  4083. if (gate) {
  4084. switch (type_gate) {
  4085. case LLM_FFN_SEQ:
  4086. {
  4087. cur = ggml_mul_mat(ctx, gate, tmp);
  4088. cb(cur, "ffn_gate", il);
  4089. } break;
  4090. case LLM_FFN_PAR:
  4091. {
  4092. cur = ggml_mul_mat(ctx, gate, cur);
  4093. cb(cur, "ffn_gate", il);
  4094. } break;
  4095. }
  4096. if (gate_b) {
  4097. cur = ggml_add(ctx, cur, gate_b);
  4098. cb(cur, "ffn_gate_b", il);
  4099. }
  4100. } else {
  4101. cur = tmp;
  4102. }
  4103. switch (type_op) {
  4104. case LLM_FFN_SILU:
  4105. {
  4106. cur = ggml_silu(ctx, cur);
  4107. cb(cur, "ffn_silu", il);
  4108. } break;
  4109. case LLM_FFN_GELU:
  4110. {
  4111. cur = ggml_gelu(ctx, cur);
  4112. cb(cur, "ffn_gelu", il);
  4113. if (act_scales != NULL) {
  4114. cur = ggml_div(ctx, cur, act_scales);
  4115. cb(cur, "ffn_act", il);
  4116. }
  4117. } break;
  4118. case LLM_FFN_RELU:
  4119. {
  4120. cur = ggml_relu(ctx, cur);
  4121. cb(cur, "ffn_relu", il);
  4122. } break;
  4123. case LLM_FFN_RELU_SQR:
  4124. {
  4125. cur = ggml_relu(ctx, cur);
  4126. cb(cur, "ffn_relu", il);
  4127. cur = ggml_sqr(ctx, cur);
  4128. cb(cur, "ffn_sqr(relu)", il);
  4129. } break;
  4130. }
  4131. if (type_gate == LLM_FFN_PAR) {
  4132. cur = ggml_mul(ctx, cur, tmp);
  4133. cb(cur, "ffn_gate_par", il);
  4134. }
  4135. cur = ggml_mul_mat(ctx, down, cur);
  4136. if (down_b) {
  4137. cb(cur, "ffn_down", il);
  4138. }
  4139. if (down_b) {
  4140. cur = ggml_add(ctx, cur, down_b);
  4141. }
  4142. return cur;
  4143. }
  4144. // if max_alibi_bias > 0 then apply ALiBi
  4145. static struct ggml_tensor * llm_build_kqv(
  4146. struct ggml_context * ctx,
  4147. const llama_model & model,
  4148. const llama_hparams & hparams,
  4149. const llama_kv_cache & kv,
  4150. struct ggml_cgraph * graph,
  4151. struct ggml_tensor * wo,
  4152. struct ggml_tensor * wo_b,
  4153. struct ggml_tensor * q_cur,
  4154. struct ggml_tensor * kq_mask,
  4155. struct ggml_tensor * kq_pos,
  4156. int64_t n_ctx,
  4157. int32_t n_tokens,
  4158. int32_t n_kv,
  4159. float kq_scale,
  4160. const llm_build_cb & cb,
  4161. int il) {
  4162. const int64_t n_head = hparams.n_head;
  4163. const int64_t n_head_kv = hparams.n_head_kv;
  4164. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4165. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4166. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4167. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4168. cb(q, "q", il);
  4169. struct ggml_tensor * k =
  4170. ggml_view_3d(ctx, kv.k_l[il],
  4171. n_embd_head_k, n_kv, n_head_kv,
  4172. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4173. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4174. 0);
  4175. cb(k, "k", il);
  4176. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4177. cb(kq, "kq", il);
  4178. if (model.arch == LLM_ARCH_PHI2) {
  4179. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4180. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4181. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4182. }
  4183. #if defined(GGML_USE_VULKAN) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_SYCL)
  4184. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Vulkan, Kompute, and SYCL")
  4185. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4186. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4187. if (hparams.f_max_alibi_bias > 0.0f) {
  4188. kq = ggml_scale(ctx, kq, kq_scale);
  4189. cb(kq, "kq_scaled", il);
  4190. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4191. cb(kq, "kq_scaled_alibi", il);
  4192. kq = ggml_add(ctx, kq, kq_mask);
  4193. cb(kq, "kq_masked", il);
  4194. kq = ggml_soft_max(ctx, kq);
  4195. cb(kq, "kq_soft_max", il);
  4196. } else
  4197. #endif
  4198. {
  4199. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4200. cb(kq, "kq_soft_max_ext", il);
  4201. }
  4202. // split cached v into n_head heads
  4203. struct ggml_tensor * v =
  4204. ggml_view_3d(ctx, kv.v_l[il],
  4205. n_kv, n_embd_head_v, n_head_kv,
  4206. ggml_element_size(kv.v_l[il])*n_ctx,
  4207. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4208. 0);
  4209. cb(v, "v", il);
  4210. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4211. cb(kqv, "kqv", il);
  4212. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4213. cb(kqv_merged, "kqv_merged", il);
  4214. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4215. cb(cur, "kqv_merged_cont", il);
  4216. ggml_build_forward_expand(graph, cur);
  4217. cur = ggml_mul_mat(ctx, wo, cur);
  4218. if (wo_b) {
  4219. cb(cur, "kqv_wo", il);
  4220. }
  4221. if (wo_b) {
  4222. cur = ggml_add(ctx, cur, wo_b);
  4223. }
  4224. return cur;
  4225. }
  4226. static struct ggml_tensor * llm_build_kv(
  4227. struct ggml_context * ctx,
  4228. const llama_model & model,
  4229. const llama_hparams & hparams,
  4230. const llama_kv_cache & kv,
  4231. struct ggml_cgraph * graph,
  4232. struct ggml_tensor * wo,
  4233. struct ggml_tensor * wo_b,
  4234. struct ggml_tensor * k_cur,
  4235. struct ggml_tensor * v_cur,
  4236. struct ggml_tensor * q_cur,
  4237. struct ggml_tensor * kq_mask,
  4238. struct ggml_tensor * kq_pos,
  4239. int64_t n_ctx,
  4240. int32_t n_tokens,
  4241. int32_t kv_head,
  4242. int32_t n_kv,
  4243. float kq_scale,
  4244. const llm_build_cb & cb,
  4245. int il) {
  4246. // these nodes are added to the graph together so that they are not reordered
  4247. // by doing so, the number of splits in the graph is reduced
  4248. ggml_build_forward_expand(graph, q_cur);
  4249. ggml_build_forward_expand(graph, k_cur);
  4250. ggml_build_forward_expand(graph, v_cur);
  4251. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4252. struct ggml_tensor * cur;
  4253. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4254. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4255. cb(cur, "kqv_out", il);
  4256. return cur;
  4257. }
  4258. struct llm_build_context {
  4259. const llama_model & model;
  4260. const llama_context & lctx;
  4261. const llama_hparams & hparams;
  4262. const llama_cparams & cparams;
  4263. const llama_batch & batch;
  4264. const llama_kv_cache & kv_self;
  4265. const int64_t n_embd;
  4266. const int64_t n_layer;
  4267. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4268. const int64_t n_head;
  4269. const int64_t n_head_kv;
  4270. const int64_t n_embd_head_k;
  4271. const int64_t n_embd_k_gqa;
  4272. const int64_t n_embd_head_v;
  4273. const int64_t n_embd_v_gqa;
  4274. const int64_t n_expert;
  4275. const int64_t n_expert_used;
  4276. const float freq_base;
  4277. const float freq_scale;
  4278. const float ext_factor;
  4279. const float attn_factor;
  4280. const float beta_fast;
  4281. const float beta_slow;
  4282. const float norm_eps;
  4283. const float norm_rms_eps;
  4284. const int32_t n_tokens;
  4285. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4286. const int32_t kv_head; // index of where we store new KV data in the cache
  4287. const int32_t n_orig_ctx;
  4288. const bool do_rope_shift;
  4289. const uint32_t pooling_type;
  4290. const llm_build_cb & cb;
  4291. std::vector<uint8_t> & buf_compute_meta;
  4292. struct ggml_context * ctx0 = nullptr;
  4293. // TODO: consider making the entire interface noexcept
  4294. llm_build_context(
  4295. llama_context & lctx,
  4296. const llama_batch & batch,
  4297. const llm_build_cb & cb,
  4298. bool worst_case) :
  4299. model (lctx.model),
  4300. lctx (lctx),
  4301. hparams (model.hparams),
  4302. cparams (lctx.cparams),
  4303. batch (batch),
  4304. kv_self (lctx.kv_self),
  4305. n_embd (hparams.n_embd),
  4306. n_layer (hparams.n_layer),
  4307. n_ctx (cparams.n_ctx),
  4308. n_head (hparams.n_head),
  4309. n_head_kv (hparams.n_head_kv),
  4310. n_embd_head_k (hparams.n_embd_head_k),
  4311. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4312. n_embd_head_v (hparams.n_embd_head_v),
  4313. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4314. n_expert (hparams.n_expert),
  4315. n_expert_used (hparams.n_expert_used),
  4316. freq_base (cparams.rope_freq_base),
  4317. freq_scale (cparams.rope_freq_scale),
  4318. ext_factor (cparams.yarn_ext_factor),
  4319. attn_factor (cparams.yarn_attn_factor),
  4320. beta_fast (cparams.yarn_beta_fast),
  4321. beta_slow (cparams.yarn_beta_slow),
  4322. norm_eps (hparams.f_norm_eps),
  4323. norm_rms_eps (hparams.f_norm_rms_eps),
  4324. n_tokens (batch.n_tokens),
  4325. n_kv (worst_case ? n_ctx : kv_self.n),
  4326. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4327. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4328. do_rope_shift (worst_case || kv_self.has_shift),
  4329. pooling_type (cparams.do_pooling ? hparams.pooling_type : (uint32_t)LLAMA_POOLING_NONE),
  4330. cb (cb),
  4331. buf_compute_meta (lctx.buf_compute_meta) {
  4332. // all initializations should be done in init()
  4333. }
  4334. void init() {
  4335. struct ggml_init_params params = {
  4336. /*.mem_size =*/ buf_compute_meta.size(),
  4337. /*.mem_buffer =*/ buf_compute_meta.data(),
  4338. /*.no_alloc =*/ true,
  4339. };
  4340. ctx0 = ggml_init(params);
  4341. }
  4342. void free() {
  4343. if (ctx0) {
  4344. ggml_free(ctx0);
  4345. ctx0 = nullptr;
  4346. }
  4347. }
  4348. struct ggml_cgraph * build_llama() {
  4349. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4350. const int64_t n_embd_head = hparams.n_embd_head_v;
  4351. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4352. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4353. struct ggml_tensor * cur;
  4354. struct ggml_tensor * inpL;
  4355. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4356. cb(inpL, "inp_embd", -1);
  4357. // inp_pos - contains the positions
  4358. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4359. cb(inp_pos, "inp_pos", -1);
  4360. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4361. 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);
  4362. cb(KQ_mask, "KQ_mask", -1);
  4363. // shift the entire K-cache if needed
  4364. if (do_rope_shift) {
  4365. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4366. }
  4367. for (int il = 0; il < n_layer; ++il) {
  4368. struct ggml_tensor * inpSA = inpL;
  4369. // norm
  4370. cur = llm_build_norm(ctx0, inpL, hparams,
  4371. model.layers[il].attn_norm, NULL,
  4372. LLM_NORM_RMS, cb, il);
  4373. cb(cur, "attn_norm", il);
  4374. // self-attention
  4375. {
  4376. // compute Q and K and RoPE them
  4377. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4378. cb(Qcur, "Qcur", il);
  4379. if (model.layers[il].bq) {
  4380. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4381. cb(Qcur, "Qcur", il);
  4382. }
  4383. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4384. cb(Kcur, "Kcur", il);
  4385. if (model.layers[il].bk) {
  4386. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4387. cb(Kcur, "Kcur", il);
  4388. }
  4389. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4390. cb(Vcur, "Vcur", il);
  4391. if (model.layers[il].bv) {
  4392. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4393. cb(Vcur, "Vcur", il);
  4394. }
  4395. Qcur = ggml_rope_custom(
  4396. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4397. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4398. ext_factor, attn_factor, beta_fast, beta_slow
  4399. );
  4400. cb(Qcur, "Qcur", il);
  4401. Kcur = ggml_rope_custom(
  4402. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4403. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4404. ext_factor, attn_factor, beta_fast, beta_slow
  4405. );
  4406. cb(Kcur, "Kcur", il);
  4407. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4408. model.layers[il].wo, model.layers[il].bo,
  4409. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4410. cb(cur, "kqv_out", il);
  4411. }
  4412. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4413. cb(ffn_inp, "ffn_inp", il);
  4414. // feed-forward network
  4415. if (model.layers[il].ffn_gate_inp == nullptr) {
  4416. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4417. model.layers[il].ffn_norm, NULL,
  4418. LLM_NORM_RMS, cb, il);
  4419. cb(cur, "ffn_norm", il);
  4420. cur = llm_build_ffn(ctx0, cur,
  4421. model.layers[il].ffn_up, NULL,
  4422. model.layers[il].ffn_gate, NULL,
  4423. model.layers[il].ffn_down, NULL,
  4424. NULL,
  4425. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4426. cb(cur, "ffn_out", il);
  4427. } else {
  4428. // MoE branch
  4429. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4430. model.layers[il].ffn_norm, NULL,
  4431. LLM_NORM_RMS, cb, il);
  4432. cb(cur, "ffn_norm", il);
  4433. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4434. cb(logits, "ffn_moe_logits", il);
  4435. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4436. cb(probs, "ffn_moe_probs", il);
  4437. // select experts
  4438. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4439. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4440. ggml_tensor * weights = ggml_get_rows(ctx0,
  4441. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4442. cb(weights, "ffn_moe_weights", il);
  4443. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4444. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4445. cb(weights_sum, "ffn_moe_weights_sum", il);
  4446. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4447. cb(weights, "ffn_moe_weights_norm", il);
  4448. // compute expert outputs
  4449. ggml_tensor * moe_out = nullptr;
  4450. for (int i = 0; i < n_expert_used; ++i) {
  4451. ggml_tensor * cur_expert;
  4452. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4453. cb(cur_up, "ffn_moe_up", il);
  4454. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4455. cb(cur_gate, "ffn_moe_gate", il);
  4456. cur_gate = ggml_silu(ctx0, cur_gate);
  4457. cb(cur_gate, "ffn_moe_silu", il);
  4458. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4459. cb(cur_expert, "ffn_moe_gate_par", il);
  4460. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4461. cb(cur_expert, "ffn_moe_down", il);
  4462. cur_expert = ggml_mul(ctx0, cur_expert,
  4463. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4464. cb(cur_expert, "ffn_moe_weighted", il);
  4465. if (i == 0) {
  4466. moe_out = cur_expert;
  4467. } else {
  4468. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4469. cb(moe_out, "ffn_moe_out", il);
  4470. }
  4471. }
  4472. cur = moe_out;
  4473. }
  4474. cur = ggml_add(ctx0, cur, ffn_inp);
  4475. cb(cur, "l_out", il);
  4476. // input for next layer
  4477. inpL = cur;
  4478. }
  4479. cur = inpL;
  4480. cur = llm_build_norm(ctx0, cur, hparams,
  4481. model.output_norm, NULL,
  4482. LLM_NORM_RMS, cb, -1);
  4483. cb(cur, "result_norm", -1);
  4484. // lm_head
  4485. cur = ggml_mul_mat(ctx0, model.output, cur);
  4486. cb(cur, "result_output", -1);
  4487. ggml_build_forward_expand(gf, cur);
  4488. return gf;
  4489. }
  4490. struct ggml_cgraph * build_baichuan() {
  4491. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4492. const int64_t n_embd_head = hparams.n_embd_head_v;
  4493. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4494. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4495. struct ggml_tensor * cur;
  4496. struct ggml_tensor * inpL;
  4497. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4498. cb(inpL, "inp_embd", -1);
  4499. // inp_pos - contains the positions
  4500. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4501. cb(inp_pos, "inp_pos", -1);
  4502. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4503. 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);
  4504. cb(KQ_mask, "KQ_mask", -1);
  4505. // positions of the tokens in the KV cache
  4506. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4507. cb(KQ_pos, "KQ_pos", -1);
  4508. // shift the entire K-cache if needed
  4509. if (do_rope_shift) {
  4510. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4511. }
  4512. for (int il = 0; il < n_layer; ++il) {
  4513. struct ggml_tensor * inpSA = inpL;
  4514. cur = llm_build_norm(ctx0, inpL, hparams,
  4515. model.layers[il].attn_norm, NULL,
  4516. LLM_NORM_RMS, cb, il);
  4517. cb(cur, "attn_norm", il);
  4518. // self-attention
  4519. {
  4520. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4521. cb(Qcur, "Qcur", il);
  4522. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4523. cb(Kcur, "Kcur", il);
  4524. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4525. cb(Vcur, "Vcur", il);
  4526. switch (model.type) {
  4527. case MODEL_7B:
  4528. Qcur = ggml_rope_custom(
  4529. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4530. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4531. ext_factor, attn_factor, beta_fast, beta_slow
  4532. );
  4533. Kcur = ggml_rope_custom(
  4534. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4535. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4536. ext_factor, attn_factor, beta_fast, beta_slow
  4537. );
  4538. break;
  4539. case MODEL_13B:
  4540. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4541. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4542. break;
  4543. default:
  4544. GGML_ASSERT(false);
  4545. }
  4546. cb(Qcur, "Qcur", il);
  4547. cb(Kcur, "Kcur", il);
  4548. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4549. model.layers[il].wo, NULL,
  4550. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4551. cb(cur, "kqv_out", il);
  4552. }
  4553. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4554. cb(ffn_inp, "ffn_inp", il);
  4555. // feed-forward network
  4556. {
  4557. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4558. model.layers[il].ffn_norm, NULL,
  4559. LLM_NORM_RMS, cb, il);
  4560. cb(cur, "ffn_norm", il);
  4561. cur = llm_build_ffn(ctx0, cur,
  4562. model.layers[il].ffn_up, NULL,
  4563. model.layers[il].ffn_gate, NULL,
  4564. model.layers[il].ffn_down, NULL,
  4565. NULL,
  4566. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4567. cb(cur, "ffn_out", il);
  4568. }
  4569. cur = ggml_add(ctx0, cur, ffn_inp);
  4570. cb(cur, "l_out", il);
  4571. // input for next layer
  4572. inpL = cur;
  4573. }
  4574. cur = inpL;
  4575. cur = llm_build_norm(ctx0, cur, hparams,
  4576. model.output_norm, NULL,
  4577. LLM_NORM_RMS, cb, -1);
  4578. cb(cur, "result_norm", -1);
  4579. // lm_head
  4580. cur = ggml_mul_mat(ctx0, model.output, cur);
  4581. cb(cur, "result_output", -1);
  4582. ggml_build_forward_expand(gf, cur);
  4583. return gf;
  4584. }
  4585. struct ggml_cgraph * build_falcon() {
  4586. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4587. const int64_t n_embd_head = hparams.n_embd_head_v;
  4588. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4589. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4590. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4591. struct ggml_tensor * cur;
  4592. struct ggml_tensor * inpL;
  4593. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4594. cb(inpL, "inp_embd", -1);
  4595. // inp_pos - contains the positions
  4596. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4597. cb(inp_pos, "inp_pos", -1);
  4598. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4599. 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);
  4600. cb(KQ_mask, "KQ_mask", -1);
  4601. // shift the entire K-cache if needed
  4602. if (do_rope_shift) {
  4603. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4604. }
  4605. for (int il = 0; il < n_layer; ++il) {
  4606. struct ggml_tensor * attn_norm;
  4607. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4608. model.layers[il].attn_norm,
  4609. model.layers[il].attn_norm_b,
  4610. LLM_NORM, cb, il);
  4611. cb(attn_norm, "attn_norm", il);
  4612. // self-attention
  4613. {
  4614. if (model.layers[il].attn_norm_2) {
  4615. // Falcon-40B
  4616. cur = llm_build_norm(ctx0, inpL, hparams,
  4617. model.layers[il].attn_norm_2,
  4618. model.layers[il].attn_norm_2_b,
  4619. LLM_NORM, cb, il);
  4620. cb(cur, "attn_norm_2", il);
  4621. } else {
  4622. cur = attn_norm;
  4623. }
  4624. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4625. cb(cur, "wqkv", il);
  4626. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4627. 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)));
  4628. 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)));
  4629. cb(Qcur, "Qcur", il);
  4630. cb(Kcur, "Kcur", il);
  4631. cb(Vcur, "Vcur", il);
  4632. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4633. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4634. // using mode = 2 for neox mode
  4635. Qcur = ggml_rope_custom(
  4636. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4637. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4638. );
  4639. cb(Qcur, "Qcur", il);
  4640. Kcur = ggml_rope_custom(
  4641. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4642. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4643. );
  4644. cb(Kcur, "Kcur", il);
  4645. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4646. model.layers[il].wo, NULL,
  4647. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4648. cb(cur, "kqv_out", il);
  4649. }
  4650. struct ggml_tensor * ffn_inp = cur;
  4651. // feed forward
  4652. {
  4653. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4654. model.layers[il].ffn_up, NULL,
  4655. NULL, NULL,
  4656. model.layers[il].ffn_down, NULL,
  4657. NULL,
  4658. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4659. cb(cur, "ffn_out", il);
  4660. }
  4661. cur = ggml_add(ctx0, cur, ffn_inp);
  4662. cb(cur, "l_out", il);
  4663. cur = ggml_add(ctx0, cur, inpL);
  4664. cb(cur, "l_out", il);
  4665. // input for next layer
  4666. inpL = cur;
  4667. }
  4668. cur = inpL;
  4669. // norm
  4670. cur = llm_build_norm(ctx0, cur, hparams,
  4671. model.output_norm,
  4672. model.output_norm_b,
  4673. LLM_NORM, cb, -1);
  4674. cb(cur, "result_norm", -1);
  4675. cur = ggml_mul_mat(ctx0, model.output, cur);
  4676. cb(cur, "result_output", -1);
  4677. ggml_build_forward_expand(gf, cur);
  4678. return gf;
  4679. }
  4680. struct ggml_cgraph * build_starcoder() {
  4681. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4682. const int64_t n_embd_head = hparams.n_embd_head_v;
  4683. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4684. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4685. struct ggml_tensor * cur;
  4686. struct ggml_tensor * pos;
  4687. struct ggml_tensor * inpL;
  4688. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4689. cb(inpL, "inp_embd", -1);
  4690. // inp_pos - contains the positions
  4691. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4692. cb(inp_pos, "inp_pos", -1);
  4693. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4694. 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);
  4695. cb(KQ_mask, "KQ_mask", -1);
  4696. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4697. cb(pos, "pos_embd", -1);
  4698. inpL = ggml_add(ctx0, inpL, pos);
  4699. cb(inpL, "inpL", -1);
  4700. for (int il = 0; il < n_layer; ++il) {
  4701. cur = llm_build_norm(ctx0, inpL, hparams,
  4702. model.layers[il].attn_norm,
  4703. model.layers[il].attn_norm_b,
  4704. LLM_NORM, cb, il);
  4705. cb(cur, "attn_norm", il);
  4706. // self-attention
  4707. {
  4708. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4709. cb(cur, "wqkv", il);
  4710. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4711. cb(cur, "bqkv", il);
  4712. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4713. 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)));
  4714. 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)));
  4715. cb(Qcur, "Qcur", il);
  4716. cb(Kcur, "Kcur", il);
  4717. cb(Vcur, "Vcur", il);
  4718. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4719. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4720. model.layers[il].wo, model.layers[il].bo,
  4721. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4722. cb(cur, "kqv_out", il);
  4723. }
  4724. // add the input
  4725. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4726. cb(ffn_inp, "ffn_inp", il);
  4727. // FF
  4728. {
  4729. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4730. model.layers[il].ffn_norm,
  4731. model.layers[il].ffn_norm_b,
  4732. LLM_NORM, cb, il);
  4733. cb(cur, "ffn_norm", il);
  4734. cur = llm_build_ffn(ctx0, cur,
  4735. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4736. NULL, NULL,
  4737. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4738. NULL,
  4739. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4740. cb(cur, "ffn_out", il);
  4741. }
  4742. inpL = ggml_add(ctx0, cur, ffn_inp);
  4743. cb(inpL, "l_out", il);
  4744. }
  4745. cur = llm_build_norm(ctx0, inpL, hparams,
  4746. model.output_norm,
  4747. model.output_norm_b,
  4748. LLM_NORM, cb, -1);
  4749. cb(cur, "result_norm", -1);
  4750. cur = ggml_mul_mat(ctx0, model.output, cur);
  4751. cb(cur, "result_output", -1);
  4752. ggml_build_forward_expand(gf, cur);
  4753. return gf;
  4754. }
  4755. struct ggml_cgraph * build_persimmon() {
  4756. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4757. const int64_t n_embd_head = hparams.n_embd_head_v;
  4758. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4759. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4760. struct ggml_tensor * cur;
  4761. struct ggml_tensor * inpL;
  4762. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4763. cb(inpL, "inp_embd", -1);
  4764. // inp_pos - contains the positions
  4765. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4766. cb(inp_pos, "inp_pos", -1);
  4767. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4768. 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);
  4769. cb(KQ_mask, "KQ_mask", -1);
  4770. if (do_rope_shift) {
  4771. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4772. }
  4773. for (int il = 0; il < n_layer; ++il) {
  4774. struct ggml_tensor * residual = inpL;
  4775. cur = llm_build_norm(ctx0, inpL, hparams,
  4776. model.layers[il].attn_norm,
  4777. model.layers[il].attn_norm_b,
  4778. LLM_NORM, cb, il);
  4779. cb(cur, "attn_norm", il);
  4780. // self attention
  4781. {
  4782. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4783. cb(cur, "wqkv", il);
  4784. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4785. cb(cur, "bqkv", il);
  4786. // split qkv
  4787. GGML_ASSERT(n_head_kv == n_head);
  4788. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4789. cb(tmpqkv, "tmpqkv", il);
  4790. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4791. cb(tmpqkv_perm, "tmpqkv", il);
  4792. struct ggml_tensor * tmpq = ggml_view_3d(
  4793. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4794. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4795. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4796. 0
  4797. );
  4798. cb(tmpq, "tmpq", il);
  4799. struct ggml_tensor * tmpk = ggml_view_3d(
  4800. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4801. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4802. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4803. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4804. );
  4805. cb(tmpk, "tmpk", il);
  4806. // Q/K Layernorm
  4807. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4808. model.layers[il].attn_q_norm,
  4809. model.layers[il].attn_q_norm_b,
  4810. LLM_NORM, cb, il);
  4811. cb(tmpq, "tmpq", il);
  4812. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4813. model.layers[il].attn_k_norm,
  4814. model.layers[il].attn_k_norm_b,
  4815. LLM_NORM, cb, il);
  4816. cb(tmpk, "tmpk", il);
  4817. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4818. struct ggml_tensor * qrot = ggml_view_3d(
  4819. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4820. ggml_element_size(tmpq) * n_embd_head,
  4821. ggml_element_size(tmpq) * n_embd_head * n_head,
  4822. 0
  4823. );
  4824. cb(qrot, "qrot", il);
  4825. struct ggml_tensor * krot = ggml_view_3d(
  4826. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4827. ggml_element_size(tmpk) * n_embd_head,
  4828. ggml_element_size(tmpk) * n_embd_head * n_head,
  4829. 0
  4830. );
  4831. cb(krot, "krot", il);
  4832. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4833. struct ggml_tensor * qpass = ggml_view_3d(
  4834. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4835. ggml_element_size(tmpq) * n_embd_head,
  4836. ggml_element_size(tmpq) * n_embd_head * n_head,
  4837. ggml_element_size(tmpq) * hparams.n_rot
  4838. );
  4839. cb(qpass, "qpass", il);
  4840. struct ggml_tensor * kpass = ggml_view_3d(
  4841. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4842. ggml_element_size(tmpk) * n_embd_head,
  4843. ggml_element_size(tmpk) * n_embd_head * n_head,
  4844. ggml_element_size(tmpk) * hparams.n_rot
  4845. );
  4846. cb(kpass, "kpass", il);
  4847. struct ggml_tensor * qrotated = ggml_rope_custom(
  4848. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4849. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4850. );
  4851. cb(qrotated, "qrotated", il);
  4852. struct ggml_tensor * krotated = ggml_rope_custom(
  4853. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4854. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4855. );
  4856. cb(krotated, "krotated", il);
  4857. // ggml currently only supports concatenation on dim=2
  4858. // so we need to permute qrot, qpass, concat, then permute back.
  4859. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4860. cb(qrotated, "qrotated", il);
  4861. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4862. cb(krotated, "krotated", il);
  4863. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4864. cb(qpass, "qpass", il);
  4865. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4866. cb(kpass, "kpass", il);
  4867. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4868. cb(Qcur, "Qcur", il);
  4869. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4870. cb(Kcur, "Kcur", il);
  4871. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4872. cb(Q, "Q", il);
  4873. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4874. cb(Kcur, "Kcur", il);
  4875. struct ggml_tensor * Vcur = ggml_view_3d(
  4876. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4877. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4878. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4879. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4880. );
  4881. cb(Vcur, "Vcur", il);
  4882. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4883. model.layers[il].wo, model.layers[il].bo,
  4884. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4885. cb(cur, "kqv_out", il);
  4886. }
  4887. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4888. cb(ffn_inp, "ffn_inp", il);
  4889. // feed-forward network
  4890. {
  4891. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4892. model.layers[il].ffn_norm,
  4893. model.layers[il].ffn_norm_b,
  4894. LLM_NORM, cb, il);
  4895. cb(cur, "ffn_norm", il);
  4896. cur = llm_build_ffn(ctx0, cur,
  4897. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4898. NULL, NULL,
  4899. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4900. NULL,
  4901. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4902. cb(cur, "ffn_out", il);
  4903. }
  4904. cur = ggml_add(ctx0, cur, ffn_inp);
  4905. cb(cur, "l_out", il);
  4906. inpL = cur;
  4907. }
  4908. cur = inpL;
  4909. cur = llm_build_norm(ctx0, cur, hparams,
  4910. model.output_norm,
  4911. model.output_norm_b,
  4912. LLM_NORM, cb, -1);
  4913. cb(cur, "result_norm", -1);
  4914. cur = ggml_mul_mat(ctx0, model.output, cur);
  4915. cb(cur, "result_output", -1);
  4916. ggml_build_forward_expand(gf, cur);
  4917. return gf;
  4918. }
  4919. struct ggml_cgraph * build_refact() {
  4920. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4921. const int64_t n_embd_head = hparams.n_embd_head_v;
  4922. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4923. struct ggml_tensor * cur;
  4924. struct ggml_tensor * inpL;
  4925. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4926. cb(inpL, "inp_embd", -1);
  4927. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4928. 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);
  4929. cb(KQ_mask, "KQ_mask", -1);
  4930. // positions of the tokens in the KV cache
  4931. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4932. cb(KQ_pos, "KQ_pos", -1);
  4933. for (int il = 0; il < n_layer; ++il) {
  4934. struct ggml_tensor * inpSA = inpL;
  4935. cur = llm_build_norm(ctx0, inpL, hparams,
  4936. model.layers[il].attn_norm, NULL,
  4937. LLM_NORM_RMS, cb, il);
  4938. cb(cur, "attn_norm", il);
  4939. // self-attention
  4940. {
  4941. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4942. cb(Qcur, "Qcur", il);
  4943. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4944. cb(Kcur, "Kcur", il);
  4945. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4946. cb(Vcur, "Vcur", il);
  4947. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4948. cb(Kcur, "Kcur", il);
  4949. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4950. cb(Qcur, "Qcur", il);
  4951. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4952. model.layers[il].wo, NULL,
  4953. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4954. cb(cur, "kqv_out", il);
  4955. }
  4956. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4957. cb(ffn_inp, "ffn_inp", il);
  4958. // feed-forward network
  4959. {
  4960. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4961. model.layers[il].ffn_norm, NULL,
  4962. LLM_NORM_RMS, cb, il);
  4963. cb(cur, "ffn_norm", il);
  4964. cur = llm_build_ffn(ctx0, cur,
  4965. model.layers[il].ffn_up, NULL,
  4966. model.layers[il].ffn_gate, NULL,
  4967. model.layers[il].ffn_down, NULL,
  4968. NULL,
  4969. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4970. cb(cur, "ffn_out", il);
  4971. }
  4972. cur = ggml_add(ctx0, cur, ffn_inp);
  4973. cb(cur, "l_out", il);
  4974. // input for next layer
  4975. inpL = cur;
  4976. }
  4977. cur = inpL;
  4978. cur = llm_build_norm(ctx0, cur, hparams,
  4979. model.output_norm, NULL,
  4980. LLM_NORM_RMS, cb, -1);
  4981. cb(cur, "result_norm", -1);
  4982. // lm_head
  4983. cur = ggml_mul_mat(ctx0, model.output, cur);
  4984. cb(cur, "result_output", -1);
  4985. ggml_build_forward_expand(gf, cur);
  4986. return gf;
  4987. }
  4988. struct ggml_cgraph * build_bert() {
  4989. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4990. const int64_t n_embd_head = hparams.n_embd_head_v;
  4991. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4992. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4993. struct ggml_tensor * cur;
  4994. struct ggml_tensor * inpL;
  4995. // get input vectors with right size
  4996. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  4997. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4998. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  4999. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  5000. // construct input embeddings (token, type, position)
  5001. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5002. // token types are hardcoded to zero ("Sentence A")
  5003. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5004. inpL = ggml_add(ctx0, inpL, type_row0);
  5005. if (model.arch == LLM_ARCH_BERT) {
  5006. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5007. }
  5008. cb(inpL, "inp_embd", -1);
  5009. // embed layer norm
  5010. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5011. cb(inpL, "inp_norm", -1);
  5012. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5013. 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);
  5014. cb(KQ_mask, "KQ_mask", -1); // [n_kv, n_tokens]
  5015. // iterate layers
  5016. for (int il = 0; il < n_layer; ++il) {
  5017. struct ggml_tensor * cur = inpL;
  5018. // self-attention
  5019. if (model.arch == LLM_ARCH_BERT) {
  5020. struct ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5021. cb(Qcur, "Qcur", il);
  5022. struct ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5023. cb(Kcur, "Kcur", il);
  5024. struct ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5025. cb(Vcur, "Vcur", il);
  5026. // seems like we just need to do this for Q?
  5027. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5028. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5029. model.layers[il].wo, model.layers[il].bo,
  5030. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5031. cb(cur, "kqv_out", il);
  5032. } else {
  5033. // compute Q and K and RoPE them
  5034. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5035. cb(cur, "wqkv", il);
  5036. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5037. 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)));
  5038. 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)));
  5039. cb(Qcur, "Qcur", il);
  5040. cb(Kcur, "Kcur", il);
  5041. cb(Vcur, "Vcur", il);
  5042. Qcur = ggml_rope_custom(
  5043. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5044. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5045. ext_factor, attn_factor, beta_fast, beta_slow
  5046. );
  5047. cb(Qcur, "Qcur", il);
  5048. Kcur = ggml_rope_custom(
  5049. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5050. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5051. ext_factor, attn_factor, beta_fast, beta_slow
  5052. );
  5053. cb(Kcur, "Kcur", il);
  5054. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5055. model.layers[il].wo, model.layers[il].bo,
  5056. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5057. cb(cur, "kqv_out", il);
  5058. }
  5059. // re-add the layer input
  5060. cur = ggml_add(ctx0, cur, inpL);
  5061. // attention layer norm
  5062. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5063. struct ggml_tensor * ffn_inp = cur;
  5064. cb(ffn_inp, "ffn_inp", il);
  5065. // feed-forward network
  5066. if (model.arch == LLM_ARCH_BERT) {
  5067. cur = llm_build_ffn(ctx0, cur,
  5068. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5069. NULL, NULL,
  5070. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5071. NULL,
  5072. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5073. } else {
  5074. cur = llm_build_ffn(ctx0, cur,
  5075. model.layers[il].ffn_up, NULL,
  5076. model.layers[il].ffn_gate, NULL,
  5077. model.layers[il].ffn_down, NULL,
  5078. NULL,
  5079. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5080. }
  5081. cb(cur, "ffn_out", il);
  5082. // attentions bypass the intermediate layer
  5083. cur = ggml_add(ctx0, cur, ffn_inp);
  5084. // output layer norm
  5085. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5086. // input for next layer
  5087. inpL = cur;
  5088. }
  5089. // final output
  5090. cur = inpL;
  5091. // pooling layer
  5092. if (pooling_type == LLAMA_POOLING_MEAN) {
  5093. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5094. } else if (pooling_type == LLAMA_POOLING_CLS) {
  5095. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5096. } else {
  5097. GGML_ASSERT(pooling_type == LLAMA_POOLING_NONE && "Invalid pooling type");
  5098. }
  5099. cb(cur, "result_embd", -1);
  5100. ggml_build_forward_expand(gf, cur);
  5101. return gf;
  5102. }
  5103. struct ggml_cgraph * build_bloom() {
  5104. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5105. const int64_t n_embd_head = hparams.n_embd_head_v;
  5106. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5107. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5108. struct ggml_tensor * cur;
  5109. struct ggml_tensor * inpL;
  5110. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5111. cb(inpL, "inp_embd", -1);
  5112. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5113. 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);
  5114. cb(KQ_mask, "KQ_mask", -1);
  5115. // positions of the tokens in the KV cache
  5116. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5117. cb(KQ_pos, "KQ_pos", -1);
  5118. inpL = llm_build_norm(ctx0, inpL, hparams,
  5119. model.tok_norm,
  5120. model.tok_norm_b,
  5121. LLM_NORM, cb, -1);
  5122. cb(inpL, "inp_norm", -1);
  5123. for (int il = 0; il < n_layer; ++il) {
  5124. cur = llm_build_norm(ctx0, inpL, hparams,
  5125. model.layers[il].attn_norm,
  5126. model.layers[il].attn_norm_b,
  5127. LLM_NORM, cb, il);
  5128. cb(cur, "attn_norm", il);
  5129. // self-attention
  5130. {
  5131. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5132. cb(cur, "wqkv", il);
  5133. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5134. cb(cur, "bqkv", il);
  5135. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5136. 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)));
  5137. 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)));
  5138. cb(Qcur, "Qcur", il);
  5139. cb(Kcur, "Kcur", il);
  5140. cb(Vcur, "Vcur", il);
  5141. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5142. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5143. model.layers[il].wo, model.layers[il].bo,
  5144. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5145. cb(cur, "kqv_out", il);
  5146. }
  5147. // Add the input
  5148. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5149. cb(ffn_inp, "ffn_inp", il);
  5150. // FF
  5151. {
  5152. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5153. model.layers[il].ffn_norm,
  5154. model.layers[il].ffn_norm_b,
  5155. LLM_NORM, cb, il);
  5156. cb(cur, "ffn_norm", il);
  5157. cur = llm_build_ffn(ctx0, cur,
  5158. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5159. NULL, NULL,
  5160. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5161. NULL,
  5162. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5163. cb(cur, "ffn_out", il);
  5164. }
  5165. inpL = ggml_add(ctx0, cur, ffn_inp);
  5166. cb(inpL, "l_out", il);
  5167. }
  5168. cur = llm_build_norm(ctx0, inpL, hparams,
  5169. model.output_norm,
  5170. model.output_norm_b,
  5171. LLM_NORM, cb, -1);
  5172. cb(cur, "result_norm", -1);
  5173. cur = ggml_mul_mat(ctx0, model.output, cur);
  5174. cb(cur, "result_output", -1);
  5175. ggml_build_forward_expand(gf, cur);
  5176. return gf;
  5177. }
  5178. struct ggml_cgraph * build_mpt() {
  5179. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5180. const int64_t n_embd_head = hparams.n_embd_head_v;
  5181. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5182. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5183. struct ggml_tensor * cur;
  5184. struct ggml_tensor * inpL;
  5185. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5186. cb(inpL, "inp_embd", -1);
  5187. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5188. 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);
  5189. cb(KQ_mask, "KQ_mask", -1);
  5190. // positions of the tokens in the KV cache
  5191. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5192. cb(KQ_pos, "KQ_pos", -1);
  5193. for (int il = 0; il < n_layer; ++il) {
  5194. struct ggml_tensor * attn_norm;
  5195. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5196. model.layers[il].attn_norm,
  5197. model.layers[il].attn_norm_b,
  5198. LLM_NORM, cb, il);
  5199. cb(attn_norm, "attn_norm", il);
  5200. // self-attention
  5201. {
  5202. cur = attn_norm;
  5203. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5204. cb(cur, "wqkv", il);
  5205. if (model.layers[il].bqkv){
  5206. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5207. cb(cur, "bqkv", il);
  5208. }
  5209. if (hparams.f_clamp_kqv > 0.0f) {
  5210. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5211. cb(cur, "wqkv_clamped", il);
  5212. }
  5213. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5214. 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)));
  5215. 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)));
  5216. cb(Qcur, "Qcur", il);
  5217. cb(Kcur, "Kcur", il);
  5218. cb(Vcur, "Vcur", il);
  5219. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5220. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5221. model.layers[il].wo, model.layers[il].bo,
  5222. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5223. cb(cur, "kqv_out", il);
  5224. }
  5225. // Add the input
  5226. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5227. cb(ffn_inp, "ffn_inp", il);
  5228. // feed forward
  5229. {
  5230. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5231. model.layers[il].ffn_norm,
  5232. model.layers[il].ffn_norm_b,
  5233. LLM_NORM, cb, il);
  5234. cb(cur, "ffn_norm", il);
  5235. cur = llm_build_ffn(ctx0, cur,
  5236. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5237. NULL, NULL,
  5238. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5239. model.layers[il].ffn_act,
  5240. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5241. cb(cur, "ffn_out", il);
  5242. }
  5243. cur = ggml_add(ctx0, cur, ffn_inp);
  5244. cb(cur, "l_out", il);
  5245. // input for next layer
  5246. inpL = cur;
  5247. }
  5248. cur = inpL;
  5249. cur = llm_build_norm(ctx0, cur, hparams,
  5250. model.output_norm,
  5251. model.output_norm_b,
  5252. LLM_NORM, cb, -1);
  5253. cb(cur, "result_norm", -1);
  5254. cur = ggml_mul_mat(ctx0, model.output, cur);
  5255. cb(cur, "result_output", -1);
  5256. ggml_build_forward_expand(gf, cur);
  5257. return gf;
  5258. }
  5259. struct ggml_cgraph * build_stablelm() {
  5260. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5261. const int64_t n_embd_head = hparams.n_embd_head_v;
  5262. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5263. struct ggml_tensor * cur;
  5264. struct ggml_tensor * inpL;
  5265. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5266. cb(inpL, "inp_embd", -1);
  5267. // inp_pos - contains the positions
  5268. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5269. cb(inp_pos, "inp_pos", -1);
  5270. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5271. 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);
  5272. cb(KQ_mask, "KQ_mask", -1);
  5273. // shift the entire K-cache if needed
  5274. if (do_rope_shift) {
  5275. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5276. }
  5277. for (int il = 0; il < n_layer; ++il) {
  5278. struct ggml_tensor * inpSA = inpL;
  5279. // norm
  5280. cur = llm_build_norm(ctx0, inpL, hparams,
  5281. model.layers[il].attn_norm,
  5282. model.layers[il].attn_norm_b,
  5283. LLM_NORM, cb, il);
  5284. cb(cur, "attn_norm", il);
  5285. // self-attention
  5286. {
  5287. // compute Q and K and RoPE them
  5288. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5289. cb(Qcur, "Qcur", il);
  5290. if (model.layers[il].bq) {
  5291. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5292. cb(Qcur, "Qcur", il);
  5293. }
  5294. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5295. cb(Kcur, "Kcur", il);
  5296. if (model.layers[il].bk) {
  5297. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5298. cb(Kcur, "Kcur", il);
  5299. }
  5300. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5301. cb(Vcur, "Vcur", il);
  5302. if (model.layers[il].bv) {
  5303. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5304. cb(Vcur, "Vcur", il);
  5305. }
  5306. Qcur = ggml_rope_custom(
  5307. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5308. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5309. ext_factor, attn_factor, beta_fast, beta_slow
  5310. );
  5311. cb(Qcur, "Qcur", il);
  5312. Kcur = ggml_rope_custom(
  5313. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5314. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5315. ext_factor, attn_factor, beta_fast, beta_slow
  5316. );
  5317. cb(Kcur, "Kcur", il);
  5318. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5319. model.layers[il].wo, NULL,
  5320. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5321. cb(cur, "kqv_out", il);
  5322. }
  5323. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5324. cb(ffn_inp, "ffn_inp", il);
  5325. // feed-forward network
  5326. {
  5327. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5328. model.layers[il].ffn_norm,
  5329. model.layers[il].ffn_norm_b,
  5330. LLM_NORM, cb, il);
  5331. cb(cur, "ffn_norm", il);
  5332. cur = llm_build_ffn(ctx0, cur,
  5333. model.layers[il].ffn_up, NULL,
  5334. model.layers[il].ffn_gate, NULL,
  5335. model.layers[il].ffn_down, NULL,
  5336. NULL,
  5337. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5338. cb(cur, "ffn_out", il);
  5339. }
  5340. cur = ggml_add(ctx0, cur, ffn_inp);
  5341. cb(cur, "l_out", il);
  5342. // input for next layer
  5343. inpL = cur;
  5344. }
  5345. cur = inpL;
  5346. cur = llm_build_norm(ctx0, cur, hparams,
  5347. model.output_norm,
  5348. model.output_norm_b,
  5349. LLM_NORM, cb, -1);
  5350. cb(cur, "result_norm", -1);
  5351. // lm_head
  5352. cur = ggml_mul_mat(ctx0, model.output, cur);
  5353. cb(cur, "result_output", -1);
  5354. ggml_build_forward_expand(gf, cur);
  5355. return gf;
  5356. }
  5357. struct ggml_cgraph * build_qwen() {
  5358. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5359. const int64_t n_embd_head = hparams.n_embd_head_v;
  5360. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5361. struct ggml_tensor * cur;
  5362. struct ggml_tensor * inpL;
  5363. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5364. cb(inpL, "inp_embd", -1);
  5365. // inp_pos - contains the positions
  5366. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5367. cb(inp_pos, "inp_pos", -1);
  5368. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5369. 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);
  5370. cb(KQ_mask, "KQ_mask", -1);
  5371. // shift the entire K-cache if needed
  5372. if (do_rope_shift) {
  5373. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5374. }
  5375. for (int il = 0; il < n_layer; ++il) {
  5376. struct ggml_tensor * inpSA = inpL;
  5377. cur = llm_build_norm(ctx0, inpL, hparams,
  5378. model.layers[il].attn_norm, NULL,
  5379. LLM_NORM_RMS, cb, il);
  5380. cb(cur, "attn_norm", il);
  5381. // self-attention
  5382. {
  5383. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5384. cb(cur, "wqkv", il);
  5385. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5386. cb(cur, "bqkv", il);
  5387. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5388. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5389. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5390. cb(Qcur, "Qcur", il);
  5391. cb(Kcur, "Kcur", il);
  5392. cb(Vcur, "Vcur", il);
  5393. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5394. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5395. // using mode = 2 for neox mode
  5396. Qcur = ggml_rope_custom(
  5397. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5398. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5399. );
  5400. cb(Qcur, "Qcur", il);
  5401. Kcur = ggml_rope_custom(
  5402. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5403. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5404. );
  5405. cb(Kcur, "Kcur", il);
  5406. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5407. model.layers[il].wo, NULL,
  5408. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5409. cb(cur, "kqv_out", il);
  5410. }
  5411. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5412. cb(ffn_inp, "ffn_inp", il);
  5413. // feed-forward forward
  5414. {
  5415. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5416. model.layers[il].ffn_norm, NULL,
  5417. LLM_NORM_RMS, cb, il);
  5418. cb(cur, "ffn_norm", il);
  5419. cur = llm_build_ffn(ctx0, cur,
  5420. model.layers[il].ffn_up, NULL,
  5421. model.layers[il].ffn_gate, NULL,
  5422. model.layers[il].ffn_down, NULL,
  5423. NULL,
  5424. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5425. cb(cur, "ffn_out", il);
  5426. }
  5427. cur = ggml_add(ctx0, cur, ffn_inp);
  5428. cb(cur, "l_out", il);
  5429. // input for next layer
  5430. inpL = cur;
  5431. }
  5432. cur = inpL;
  5433. cur = llm_build_norm(ctx0, cur, hparams,
  5434. model.output_norm, NULL,
  5435. LLM_NORM_RMS, cb, -1);
  5436. cb(cur, "result_norm", -1);
  5437. // lm_head
  5438. cur = ggml_mul_mat(ctx0, model.output, cur);
  5439. cb(cur, "result_output", -1);
  5440. ggml_build_forward_expand(gf, cur);
  5441. return gf;
  5442. }
  5443. struct ggml_cgraph * build_qwen2() {
  5444. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5445. const int64_t n_embd_head = hparams.n_embd_head_v;
  5446. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5447. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5448. struct ggml_tensor * cur;
  5449. struct ggml_tensor * inpL;
  5450. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5451. cb(inpL, "inp_embd", -1);
  5452. // inp_pos - contains the positions
  5453. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5454. cb(inp_pos, "inp_pos", -1);
  5455. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5456. 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);
  5457. cb(KQ_mask, "KQ_mask", -1);
  5458. // shift the entire K-cache if needed
  5459. if (do_rope_shift) {
  5460. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5461. }
  5462. for (int il = 0; il < n_layer; ++il) {
  5463. struct ggml_tensor * inpSA = inpL;
  5464. // norm
  5465. cur = llm_build_norm(ctx0, inpL, hparams,
  5466. model.layers[il].attn_norm, NULL,
  5467. LLM_NORM_RMS, cb, il);
  5468. cb(cur, "attn_norm", il);
  5469. // self-attention
  5470. {
  5471. // compute Q and K and RoPE them
  5472. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5473. cb(Qcur, "Qcur", il);
  5474. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5475. cb(Qcur, "Qcur", il);
  5476. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5477. cb(Kcur, "Kcur", il);
  5478. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5479. cb(Kcur, "Kcur", il);
  5480. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5481. cb(Vcur, "Vcur", il);
  5482. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5483. cb(Vcur, "Vcur", il);
  5484. // these nodes are added to the graph together so that they are not reordered
  5485. // by doing so, the number of splits in the graph is reduced
  5486. ggml_build_forward_expand(gf, Qcur);
  5487. ggml_build_forward_expand(gf, Kcur);
  5488. ggml_build_forward_expand(gf, Vcur);
  5489. Qcur = ggml_rope_custom(
  5490. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5491. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5492. ext_factor, attn_factor, beta_fast, beta_slow
  5493. );
  5494. cb(Qcur, "Qcur", il);
  5495. Kcur = ggml_rope_custom(
  5496. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5497. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5498. ext_factor, attn_factor, beta_fast, beta_slow
  5499. );
  5500. cb(Kcur, "Kcur", il);
  5501. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5502. model.layers[il].wo, model.layers[il].bo,
  5503. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5504. cb(cur, "kqv_out", il);
  5505. }
  5506. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5507. cb(ffn_inp, "ffn_inp", il);
  5508. // feed-forward network
  5509. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5510. model.layers[il].ffn_norm, NULL,
  5511. LLM_NORM_RMS, cb, il);
  5512. cb(cur, "ffn_norm", il);
  5513. cur = llm_build_ffn(ctx0, cur,
  5514. model.layers[il].ffn_up, NULL,
  5515. model.layers[il].ffn_gate, NULL,
  5516. model.layers[il].ffn_down, NULL,
  5517. NULL,
  5518. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5519. cb(cur, "ffn_out", il);
  5520. cur = ggml_add(ctx0, cur, ffn_inp);
  5521. cb(cur, "l_out", il);
  5522. // input for next layer
  5523. inpL = cur;
  5524. }
  5525. cur = inpL;
  5526. cur = llm_build_norm(ctx0, cur, hparams,
  5527. model.output_norm, NULL,
  5528. LLM_NORM_RMS, cb, -1);
  5529. cb(cur, "result_norm", -1);
  5530. // lm_head
  5531. cur = ggml_mul_mat(ctx0, model.output, cur);
  5532. cb(cur, "result_output", -1);
  5533. ggml_build_forward_expand(gf, cur);
  5534. return gf;
  5535. }
  5536. struct ggml_cgraph * build_phi2() {
  5537. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5538. const int64_t n_embd_head = hparams.n_embd_head_v;
  5539. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5540. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5541. struct ggml_tensor * cur;
  5542. struct ggml_tensor * attn_norm_output;
  5543. struct ggml_tensor * ffn_output;
  5544. struct ggml_tensor * inpL;
  5545. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5546. cb(inpL, "inp_embd", -1);
  5547. // inp_pos - contains the positions
  5548. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5549. cb(inp_pos, "inp_pos", -1);
  5550. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5551. 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);
  5552. cb(KQ_mask, "KQ_mask", -1);
  5553. // shift the entire K-cache if needed
  5554. if (do_rope_shift) {
  5555. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5556. }
  5557. for (int il = 0; il < n_layer; ++il) {
  5558. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5559. model.layers[il].attn_norm,
  5560. model.layers[il].attn_norm_b,
  5561. LLM_NORM, cb, il);
  5562. cb(attn_norm_output, "attn_norm", il);
  5563. // self-attention
  5564. {
  5565. struct ggml_tensor * Qcur = nullptr;
  5566. struct ggml_tensor * Kcur = nullptr;
  5567. struct ggml_tensor * Vcur = nullptr;
  5568. if (model.layers[il].wqkv) {
  5569. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5570. cb(cur, "wqkv", il);
  5571. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5572. cb(cur, "bqkv", il);
  5573. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5574. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5575. 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)));
  5576. } else {
  5577. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5578. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5579. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5580. }
  5581. cb(Qcur, "Qcur", il);
  5582. cb(Kcur, "Kcur", il);
  5583. cb(Vcur, "Vcur", il);
  5584. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5585. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5586. Qcur = ggml_rope_custom(
  5587. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5588. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5589. );
  5590. cb(Qcur, "Qcur", il);
  5591. // with phi2, we scale the Q to avoid precision issues
  5592. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5593. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5594. cb(Qcur, "Qcur", il);
  5595. Kcur = ggml_rope_custom(
  5596. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5597. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5598. );
  5599. cb(Kcur, "Kcur", il);
  5600. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5601. model.layers[il].wo, model.layers[il].bo,
  5602. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5603. cb(cur, "kqv_out", il);
  5604. }
  5605. // FF
  5606. {
  5607. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5608. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5609. NULL, NULL,
  5610. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5611. NULL,
  5612. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5613. cb(ffn_output, "ffn_out", il);
  5614. }
  5615. cur = ggml_add(ctx0, cur, ffn_output);
  5616. cb(cur, "l_out", il);
  5617. cur = ggml_add(ctx0, cur, inpL);
  5618. cb(cur, "l_out", il);
  5619. inpL = cur;
  5620. }
  5621. cur = llm_build_norm(ctx0, inpL, hparams,
  5622. model.output_norm,
  5623. model.output_norm_b,
  5624. LLM_NORM, cb, -1);
  5625. cb(cur, "result_norm", -1);
  5626. cur = ggml_mul_mat(ctx0, model.output, cur);
  5627. cb(cur, "result_output_no_bias", -1);
  5628. cur = ggml_add(ctx0, cur, model.output_b);
  5629. cb(cur, "result_output", -1);
  5630. ggml_build_forward_expand(gf, cur);
  5631. return gf;
  5632. }
  5633. struct ggml_cgraph * build_plamo() {
  5634. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5635. const int64_t n_embd_head = hparams.n_embd_head_v;
  5636. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5637. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5638. struct ggml_tensor * cur;
  5639. struct ggml_tensor * inpL;
  5640. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5641. cb(inpL, "inp_embd", -1);
  5642. // inp_pos - contains the positions
  5643. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5644. cb(inp_pos, "inp_pos", -1);
  5645. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5646. 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);
  5647. cb(KQ_mask, "KQ_mask", -1);
  5648. // shift the entire K-cache if needed
  5649. if (do_rope_shift) {
  5650. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5651. }
  5652. for (int il = 0; il < n_layer; ++il) {
  5653. // norm
  5654. cur = llm_build_norm(ctx0, inpL, hparams,
  5655. model.layers[il].attn_norm, NULL,
  5656. LLM_NORM_RMS, cb, il);
  5657. cb(cur, "attn_norm", il);
  5658. struct ggml_tensor * attention_norm = cur;
  5659. // self-attention
  5660. {
  5661. // compute Q and K and RoPE them
  5662. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5663. cb(Qcur, "Qcur", il);
  5664. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5665. cb(Kcur, "Kcur", il);
  5666. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5667. cb(Vcur, "Vcur", il);
  5668. Qcur = ggml_rope_custom(
  5669. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5670. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5671. ext_factor, attn_factor, beta_fast, beta_slow);
  5672. cb(Qcur, "Qcur", il);
  5673. Kcur = ggml_rope_custom(
  5674. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5675. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5676. ext_factor, attn_factor, beta_fast, beta_slow);
  5677. cb(Kcur, "Kcur", il);
  5678. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5679. model.layers[il].wo, NULL,
  5680. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5681. cb(cur, "kqv_out", il);
  5682. }
  5683. struct ggml_tensor * sa_out = cur;
  5684. cur = attention_norm;
  5685. // feed-forward network
  5686. {
  5687. cur = llm_build_ffn(ctx0, cur,
  5688. model.layers[il].ffn_up, NULL,
  5689. model.layers[il].ffn_gate, NULL,
  5690. model.layers[il].ffn_down, NULL,
  5691. NULL,
  5692. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5693. cb(cur, "ffn_out", il);
  5694. }
  5695. cur = ggml_add(ctx0, cur, sa_out);
  5696. cb(cur, "l_out", il);
  5697. cur = ggml_add(ctx0, cur, inpL);
  5698. cb(cur, "l_out", il);
  5699. // input for next layer
  5700. inpL = cur;
  5701. }
  5702. cur = inpL;
  5703. cur = llm_build_norm(ctx0, cur, hparams,
  5704. model.output_norm, NULL,
  5705. LLM_NORM_RMS, cb, -1);
  5706. cb(cur, "result_norm", -1);
  5707. // lm_head
  5708. cur = ggml_mul_mat(ctx0, model.output, cur);
  5709. cb(cur, "result_output", -1);
  5710. ggml_build_forward_expand(gf, cur);
  5711. return gf;
  5712. }
  5713. struct ggml_cgraph * build_gpt2() {
  5714. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5715. const int64_t n_embd_head = hparams.n_embd_head_v;
  5716. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5717. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5718. struct ggml_tensor * cur;
  5719. struct ggml_tensor * pos;
  5720. struct ggml_tensor * inpL;
  5721. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5722. cb(inpL, "inp_embd", -1);
  5723. // inp_pos - contains the positions
  5724. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5725. cb(inp_pos, "inp_pos", -1);
  5726. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5727. 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);
  5728. cb(KQ_mask, "KQ_mask", -1);
  5729. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5730. cb(pos, "pos_embd", -1);
  5731. inpL = ggml_add(ctx0, inpL, pos);
  5732. cb(inpL, "inpL", -1);
  5733. for (int il = 0; il < n_layer; ++il) {
  5734. cur = llm_build_norm(ctx0, inpL, hparams,
  5735. model.layers[il].attn_norm,
  5736. model.layers[il].attn_norm_b,
  5737. LLM_NORM, cb, il);
  5738. cb(cur, "attn_norm", il);
  5739. // self-attention
  5740. {
  5741. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5742. cb(cur, "wqkv", il);
  5743. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5744. cb(cur, "bqkv", il);
  5745. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5746. 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)));
  5747. 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)));
  5748. cb(Qcur, "Qcur", il);
  5749. cb(Kcur, "Kcur", il);
  5750. cb(Vcur, "Vcur", il);
  5751. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  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/sqrtf(float(n_embd_head)), cb, il);
  5755. cb(cur, "kqv_out", il);
  5756. }
  5757. // add the input
  5758. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5759. cb(ffn_inp, "ffn_inp", il);
  5760. // FF
  5761. {
  5762. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5763. model.layers[il].ffn_norm,
  5764. model.layers[il].ffn_norm_b,
  5765. LLM_NORM, cb, il);
  5766. cb(cur, "ffn_norm", il);
  5767. cur = llm_build_ffn(ctx0, cur,
  5768. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5769. NULL, NULL,
  5770. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5771. NULL,
  5772. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5773. cb(cur, "ffn_out", il);
  5774. }
  5775. inpL = ggml_add(ctx0, cur, ffn_inp);
  5776. cb(inpL, "l_out", il);
  5777. }
  5778. cur = llm_build_norm(ctx0, inpL, hparams,
  5779. model.output_norm,
  5780. model.output_norm_b,
  5781. LLM_NORM, cb, -1);
  5782. cb(cur, "result_norm", -1);
  5783. cur = ggml_mul_mat(ctx0, model.output, cur);
  5784. cb(cur, "result_output", -1);
  5785. ggml_build_forward_expand(gf, cur);
  5786. return gf;
  5787. }
  5788. struct ggml_cgraph * build_codeshell() {
  5789. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5790. const int64_t n_embd_head = hparams.n_embd_head_v;
  5791. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5792. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5793. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5794. struct ggml_tensor * cur;
  5795. struct ggml_tensor * inpL;
  5796. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5797. cb(inpL, "inp_embd", -1);
  5798. // inp_pos - contains the positions
  5799. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5800. cb(inp_pos, "inp_pos", -1);
  5801. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5802. 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);
  5803. cb(KQ_mask, "KQ_mask", -1);
  5804. // shift the entire K-cache if needed
  5805. if (do_rope_shift) {
  5806. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5807. }
  5808. for (int il = 0; il < n_layer; ++il) {
  5809. cur = llm_build_norm(ctx0, inpL, hparams,
  5810. model.layers[il].attn_norm,
  5811. model.layers[il].attn_norm_b,
  5812. LLM_NORM, cb, il);
  5813. cb(cur, "attn_norm", il);
  5814. // self-attention
  5815. {
  5816. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5817. cb(cur, "wqkv", il);
  5818. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5819. cb(cur, "bqkv", il);
  5820. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5821. 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)));
  5822. 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)));
  5823. cb(tmpq, "tmpq", il);
  5824. cb(tmpk, "tmpk", il);
  5825. cb(Vcur, "Vcur", il);
  5826. struct ggml_tensor * Qcur = ggml_rope_custom(
  5827. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5828. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5829. ext_factor, attn_factor, beta_fast, beta_slow
  5830. );
  5831. cb(Qcur, "Qcur", il);
  5832. struct ggml_tensor * Kcur = ggml_rope_custom(
  5833. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5834. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5835. ext_factor, attn_factor, beta_fast, beta_slow
  5836. );
  5837. cb(Kcur, "Kcur", il);
  5838. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5839. model.layers[il].wo, model.layers[il].bo,
  5840. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5841. cb(cur, "kqv_out", il);
  5842. }
  5843. // add the input
  5844. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5845. cb(ffn_inp, "ffn_inp", il);
  5846. // FF
  5847. {
  5848. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5849. model.layers[il].ffn_norm,
  5850. model.layers[il].ffn_norm_b,
  5851. LLM_NORM, cb, il);
  5852. cb(cur, "ffn_norm", il);
  5853. cur = llm_build_ffn(ctx0, cur,
  5854. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5855. NULL, NULL,
  5856. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5857. NULL,
  5858. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5859. cb(cur, "ffn_out", il);
  5860. }
  5861. inpL = ggml_add(ctx0, cur, ffn_inp);
  5862. cb(inpL, "l_out", il);
  5863. }
  5864. cur = llm_build_norm(ctx0, inpL, hparams,
  5865. model.output_norm,
  5866. model.output_norm_b,
  5867. LLM_NORM, cb, -1);
  5868. cb(cur, "result_norm", -1);
  5869. cur = ggml_mul_mat(ctx0, model.output, cur);
  5870. cb(cur, "result_output", -1);
  5871. ggml_build_forward_expand(gf, cur);
  5872. return gf;
  5873. }
  5874. struct ggml_cgraph * build_orion() {
  5875. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5876. const int64_t n_embd_head = hparams.n_embd_head_v;
  5877. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5878. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5879. struct ggml_tensor * cur;
  5880. struct ggml_tensor * inpL;
  5881. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5882. cb(inpL, "inp_embd", -1);
  5883. // inp_pos - contains the positions
  5884. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5885. cb(inp_pos, "inp_pos", -1);
  5886. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5887. 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);
  5888. cb(KQ_mask, "KQ_mask", -1);
  5889. // shift the entire K-cache if needed
  5890. if (do_rope_shift) {
  5891. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5892. }
  5893. for (int il = 0; il < n_layer; ++il) {
  5894. struct ggml_tensor * inpSA = inpL;
  5895. // norm
  5896. cur = llm_build_norm(ctx0, inpL, hparams,
  5897. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5898. LLM_NORM, cb, il);
  5899. cb(cur, "attn_norm", il);
  5900. // self-attention
  5901. {
  5902. // compute Q and K and RoPE them
  5903. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5904. cb(Qcur, "Qcur", il);
  5905. // if (model.layers[il].bq) {
  5906. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5907. // cb(Qcur, "Qcur", il);
  5908. // }
  5909. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5910. cb(Kcur, "Kcur", il);
  5911. // if (model.layers[il].bk) {
  5912. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5913. // cb(Kcur, "Kcur", il);
  5914. // }
  5915. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5916. cb(Vcur, "Vcur", il);
  5917. // if (model.layers[il].bv) {
  5918. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5919. // cb(Vcur, "Vcur", il);
  5920. // }
  5921. Qcur = ggml_rope_custom(
  5922. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5923. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5924. ext_factor, attn_factor, beta_fast, beta_slow
  5925. );
  5926. cb(Qcur, "Qcur", il);
  5927. Kcur = ggml_rope_custom(
  5928. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5929. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5930. ext_factor, attn_factor, beta_fast, beta_slow
  5931. );
  5932. cb(Kcur, "Kcur", il);
  5933. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5934. model.layers[il].wo, NULL,
  5935. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5936. cb(cur, "kqv_out", il);
  5937. }
  5938. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5939. cb(ffn_inp, "ffn_inp", il);
  5940. // feed-forward network
  5941. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5942. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  5943. LLM_NORM, cb, il);
  5944. cb(cur, "ffn_norm", il);
  5945. cur = llm_build_ffn(ctx0, cur,
  5946. model.layers[il].ffn_up, NULL,
  5947. model.layers[il].ffn_gate, NULL,
  5948. model.layers[il].ffn_down, NULL,
  5949. NULL,
  5950. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5951. cb(cur, "ffn_out", il);
  5952. cur = ggml_add(ctx0, cur, ffn_inp);
  5953. cb(cur, "l_out", il);
  5954. // input for next layer
  5955. inpL = cur;
  5956. }
  5957. cur = inpL;
  5958. cur = llm_build_norm(ctx0, cur, hparams,
  5959. model.output_norm, model.output_norm_b,
  5960. LLM_NORM, cb, -1);
  5961. cb(cur, "result_norm", -1);
  5962. // lm_head
  5963. cur = ggml_mul_mat(ctx0, model.output, cur);
  5964. cb(cur, "result_output", -1);
  5965. ggml_build_forward_expand(gf, cur);
  5966. return gf;
  5967. }
  5968. struct ggml_cgraph * build_internlm2() {
  5969. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5970. const int64_t n_embd_head = hparams.n_embd_head_v;
  5971. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5972. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5973. struct ggml_tensor * cur;
  5974. struct ggml_tensor * inpL;
  5975. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5976. cb(inpL, "inp_embd", -1);
  5977. // inp_pos - contains the positions
  5978. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5979. cb(inp_pos, "inp_pos", -1);
  5980. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5981. 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);
  5982. cb(KQ_mask, "KQ_mask", -1);
  5983. // shift the entire K-cache if needed
  5984. if (do_rope_shift) {
  5985. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5986. }
  5987. for (int il = 0; il < n_layer; ++il) {
  5988. struct ggml_tensor * inpSA = inpL;
  5989. // norm
  5990. cur = llm_build_norm(ctx0, inpL, hparams,
  5991. model.layers[il].attn_norm, NULL,
  5992. LLM_NORM_RMS, cb, il);
  5993. cb(cur, "attn_norm", il);
  5994. // self-attention
  5995. {
  5996. // compute Q and K and RoPE them
  5997. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5998. cb(Qcur, "Qcur", il);
  5999. if (model.layers[il].bq) {
  6000. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6001. cb(Qcur, "Qcur", il);
  6002. }
  6003. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6004. cb(Kcur, "Kcur", il);
  6005. if (model.layers[il].bk) {
  6006. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6007. cb(Kcur, "Kcur", il);
  6008. }
  6009. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6010. cb(Vcur, "Vcur", il);
  6011. if (model.layers[il].bv) {
  6012. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6013. cb(Vcur, "Vcur", il);
  6014. }
  6015. Qcur = ggml_rope_custom(
  6016. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6017. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6018. ext_factor, attn_factor, beta_fast, beta_slow
  6019. );
  6020. cb(Qcur, "Qcur", il);
  6021. Kcur = ggml_rope_custom(
  6022. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6023. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6024. ext_factor, attn_factor, beta_fast, beta_slow
  6025. );
  6026. cb(Kcur, "Kcur", il);
  6027. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6028. model.layers[il].wo, model.layers[il].bo,
  6029. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6030. cb(cur, "kqv_out", il);
  6031. }
  6032. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6033. cb(ffn_inp, "ffn_inp", il);
  6034. // feed-forward network
  6035. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6036. model.layers[il].ffn_norm, NULL,
  6037. LLM_NORM_RMS, cb, il);
  6038. cb(cur, "ffn_norm", il);
  6039. cur = llm_build_ffn(ctx0, cur,
  6040. model.layers[il].ffn_up, NULL,
  6041. model.layers[il].ffn_gate, NULL,
  6042. model.layers[il].ffn_down, NULL,
  6043. NULL,
  6044. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6045. cb(cur, "ffn_out", il);
  6046. cur = ggml_add(ctx0, cur, ffn_inp);
  6047. cb(cur, "l_out", il);
  6048. // input for next layer
  6049. inpL = cur;
  6050. }
  6051. cur = inpL;
  6052. cur = llm_build_norm(ctx0, cur, hparams,
  6053. model.output_norm, NULL,
  6054. LLM_NORM_RMS, cb, -1);
  6055. cb(cur, "result_norm", -1);
  6056. // lm_head
  6057. cur = ggml_mul_mat(ctx0, model.output, cur);
  6058. cb(cur, "result_output", -1);
  6059. ggml_build_forward_expand(gf, cur);
  6060. return gf;
  6061. }
  6062. // ref: https://arxiv.org/abs/2203.03466
  6063. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6064. // based on the original build_llama() function
  6065. struct ggml_cgraph * build_minicpm() {
  6066. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6067. const int64_t n_embd_head = hparams.n_embd_head_v;
  6068. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6069. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6070. const int64_t n_embd = hparams.n_embd;
  6071. //TODO: if the model varies, these parameters need to be read from the model
  6072. const int64_t n_embd_base = 256;
  6073. const float scale_embd = 12.0f;
  6074. const float scale_depth = 1.4f;
  6075. struct ggml_tensor * cur;
  6076. struct ggml_tensor * inpL;
  6077. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6078. cb(inpL, "inp_embd", -1);
  6079. // scale the input embeddings
  6080. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6081. cb(inpL, "inp_scaled", -1);
  6082. // inp_pos - contains the positions
  6083. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6084. cb(inp_pos, "inp_pos", -1);
  6085. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6086. 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);
  6087. cb(KQ_mask, "KQ_mask", -1);
  6088. // shift the entire K-cache if needed
  6089. if (do_rope_shift) {
  6090. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  6091. }
  6092. for (int il = 0; il < n_layer; ++il) {
  6093. struct ggml_tensor * inpSA = inpL;
  6094. // norm
  6095. cur = llm_build_norm(ctx0, inpL, hparams,
  6096. model.layers[il].attn_norm, NULL,
  6097. LLM_NORM_RMS, cb, il);
  6098. cb(cur, "attn_norm", il);
  6099. // self-attention
  6100. {
  6101. // compute Q and K and RoPE them
  6102. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6103. cb(Qcur, "Qcur", il);
  6104. if (model.layers[il].bq) {
  6105. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6106. cb(Qcur, "Qcur", il);
  6107. }
  6108. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6109. cb(Kcur, "Kcur", il);
  6110. if (model.layers[il].bk) {
  6111. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6112. cb(Kcur, "Kcur", il);
  6113. }
  6114. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6115. cb(Vcur, "Vcur", il);
  6116. if (model.layers[il].bv) {
  6117. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6118. cb(Vcur, "Vcur", il);
  6119. }
  6120. Qcur = ggml_rope_custom(
  6121. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6122. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6123. ext_factor, attn_factor, beta_fast, beta_slow
  6124. );
  6125. cb(Qcur, "Qcur", il);
  6126. Kcur = ggml_rope_custom(
  6127. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6128. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6129. ext_factor, attn_factor, beta_fast, beta_slow
  6130. );
  6131. cb(Kcur, "Kcur", il);
  6132. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6133. model.layers[il].wo, model.layers[il].bo,
  6134. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6135. cb(cur, "kqv_out", il);
  6136. }
  6137. // scale_res - scale the hidden states for residual connection
  6138. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6139. cur = ggml_scale(ctx0, cur, scale_res);
  6140. cb(cur, "hidden_scaled", -1);
  6141. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6142. cb(ffn_inp, "ffn_inp", il);
  6143. // feed-forward network
  6144. {
  6145. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6146. model.layers[il].ffn_norm, NULL,
  6147. LLM_NORM_RMS, cb, il);
  6148. cb(cur, "ffn_norm", il);
  6149. cur = llm_build_ffn(ctx0, cur,
  6150. model.layers[il].ffn_up, NULL,
  6151. model.layers[il].ffn_gate, NULL,
  6152. model.layers[il].ffn_down, NULL,
  6153. NULL,
  6154. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6155. cb(cur, "ffn_out", il);
  6156. }
  6157. // scale the hidden states for residual connection
  6158. cur = ggml_scale(ctx0, cur, scale_res);
  6159. cb(cur, "hidden_scaled_ffn", -1);
  6160. cur = ggml_add(ctx0, cur, ffn_inp);
  6161. cb(cur, "l_out", il);
  6162. // input for next layer
  6163. inpL = cur;
  6164. }
  6165. cur = inpL;
  6166. cur = llm_build_norm(ctx0, cur, hparams,
  6167. model.output_norm, NULL,
  6168. LLM_NORM_RMS, cb, -1);
  6169. cb(cur, "result_norm", -1);
  6170. // lm_head scaling
  6171. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6172. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6173. cb(cur, "lmhead_scaling", -1);
  6174. // lm_head
  6175. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6176. cb(cur, "result_output", -1);
  6177. ggml_build_forward_expand(gf, cur);
  6178. return gf;
  6179. }
  6180. struct ggml_cgraph * build_gemma() {
  6181. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6182. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6183. struct ggml_tensor * cur;
  6184. struct ggml_tensor * inpL;
  6185. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6186. cb(inpL, "inp_embd", -1);
  6187. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6188. cb(inpL, "inp_scaled", -1);
  6189. // inp_pos - contains the positions
  6190. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6191. cb(inp_pos, "inp_pos", -1);
  6192. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6193. 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);
  6194. cb(KQ_mask, "KQ_mask", -1);
  6195. // shift the entire K-cache if needed
  6196. if (do_rope_shift) {
  6197. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  6198. }
  6199. for (int il = 0; il < n_layer; ++il) {
  6200. // norm
  6201. cur = llm_build_norm(ctx0, inpL, hparams,
  6202. model.layers[il].attn_norm, NULL,
  6203. LLM_NORM_RMS, cb, il);
  6204. cb(cur, "attn_norm", il);
  6205. // self-attention
  6206. {
  6207. // compute Q and K and RoPE them
  6208. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6209. cb(Qcur, "Qcur", il);
  6210. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6211. cb(Kcur, "Kcur", il);
  6212. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6213. cb(Vcur, "Vcur", il);
  6214. Qcur = ggml_rope_custom(
  6215. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6216. n_embd_head_k, 2, 0, n_orig_ctx, freq_base, freq_scale,
  6217. ext_factor, attn_factor, beta_fast, beta_slow);
  6218. cb(Qcur, "Qcur", il);
  6219. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6220. cb(Qcur, "Qcur_scaled", il);
  6221. Kcur = ggml_rope_custom(
  6222. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6223. n_embd_head_k, 2, 0, n_orig_ctx, freq_base, freq_scale,
  6224. ext_factor, attn_factor, beta_fast, beta_slow);
  6225. cb(Kcur, "Kcur", il);
  6226. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6227. model.layers[il].wo, NULL,
  6228. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6229. cb(cur, "kqv_out", il);
  6230. }
  6231. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6232. cb(sa_out, "sa_out", il);
  6233. cur = llm_build_norm(ctx0, sa_out, hparams,
  6234. model.layers[il].ffn_norm, NULL,
  6235. LLM_NORM_RMS, cb, il);
  6236. cb(cur, "ffn_norm", il);
  6237. // feed-forward network
  6238. {
  6239. cur = llm_build_ffn(ctx0, cur,
  6240. model.layers[il].ffn_up, NULL,
  6241. model.layers[il].ffn_gate, NULL,
  6242. model.layers[il].ffn_down, NULL,
  6243. NULL,
  6244. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6245. cb(cur, "ffn_out", il);
  6246. }
  6247. cur = ggml_add(ctx0, cur, sa_out);
  6248. cb(cur, "l_out", il);
  6249. // input for next layer
  6250. inpL = cur;
  6251. }
  6252. cur = inpL;
  6253. cur = llm_build_norm(ctx0, cur, hparams,
  6254. model.output_norm, NULL,
  6255. LLM_NORM_RMS, cb, -1);
  6256. cb(cur, "result_norm", -1);
  6257. // lm_head
  6258. cur = ggml_mul_mat(ctx0, model.output, cur);
  6259. cb(cur, "result_output", -1);
  6260. ggml_build_forward_expand(gf, cur);
  6261. return gf;
  6262. }
  6263. };
  6264. static struct ggml_cgraph * llama_build_graph(
  6265. llama_context & lctx,
  6266. const llama_batch & batch,
  6267. bool worst_case) {
  6268. const auto & model = lctx.model;
  6269. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6270. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6271. if (il >= 0) {
  6272. ggml_format_name(cur, "%s-%d", name, il);
  6273. } else {
  6274. ggml_set_name(cur, name);
  6275. }
  6276. if (!lctx.cparams.offload_kqv) {
  6277. if (strcmp(name, "kqv_merged_cont") == 0) {
  6278. // all nodes between the KV store and the attention output are run on the CPU
  6279. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6280. }
  6281. }
  6282. };
  6283. struct ggml_cgraph * result = NULL;
  6284. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6285. llm.init();
  6286. switch (model.arch) {
  6287. case LLM_ARCH_LLAMA:
  6288. {
  6289. result = llm.build_llama();
  6290. } break;
  6291. case LLM_ARCH_BAICHUAN:
  6292. {
  6293. result = llm.build_baichuan();
  6294. } break;
  6295. case LLM_ARCH_FALCON:
  6296. {
  6297. result = llm.build_falcon();
  6298. } break;
  6299. case LLM_ARCH_STARCODER:
  6300. {
  6301. result = llm.build_starcoder();
  6302. } break;
  6303. case LLM_ARCH_PERSIMMON:
  6304. {
  6305. result = llm.build_persimmon();
  6306. } break;
  6307. case LLM_ARCH_REFACT:
  6308. {
  6309. result = llm.build_refact();
  6310. } break;
  6311. case LLM_ARCH_BERT:
  6312. case LLM_ARCH_NOMIC_BERT:
  6313. {
  6314. result = llm.build_bert();
  6315. } break;
  6316. case LLM_ARCH_BLOOM:
  6317. {
  6318. result = llm.build_bloom();
  6319. } break;
  6320. case LLM_ARCH_MPT:
  6321. {
  6322. result = llm.build_mpt();
  6323. } break;
  6324. case LLM_ARCH_STABLELM:
  6325. {
  6326. result = llm.build_stablelm();
  6327. } break;
  6328. case LLM_ARCH_QWEN:
  6329. {
  6330. result = llm.build_qwen();
  6331. } break;
  6332. case LLM_ARCH_QWEN2:
  6333. {
  6334. result = llm.build_qwen2();
  6335. } break;
  6336. case LLM_ARCH_PHI2:
  6337. {
  6338. result = llm.build_phi2();
  6339. } break;
  6340. case LLM_ARCH_PLAMO:
  6341. {
  6342. result = llm.build_plamo();
  6343. } break;
  6344. case LLM_ARCH_GPT2:
  6345. {
  6346. result = llm.build_gpt2();
  6347. } break;
  6348. case LLM_ARCH_CODESHELL:
  6349. {
  6350. result = llm.build_codeshell();
  6351. } break;
  6352. case LLM_ARCH_ORION:
  6353. {
  6354. result = llm.build_orion();
  6355. } break;
  6356. case LLM_ARCH_INTERNLM2:
  6357. {
  6358. result = llm.build_internlm2();
  6359. } break;
  6360. case LLM_ARCH_MINICPM:
  6361. {
  6362. result = llm.build_minicpm();
  6363. } break;
  6364. case LLM_ARCH_GEMMA:
  6365. {
  6366. result = llm.build_gemma();
  6367. } break;
  6368. default:
  6369. GGML_ASSERT(false);
  6370. }
  6371. llm.free();
  6372. return result;
  6373. }
  6374. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6375. //
  6376. // set input data
  6377. //
  6378. const auto & hparams = lctx.model.hparams;
  6379. const auto & cparams = lctx.cparams;
  6380. const auto & kv_self = lctx.kv_self;
  6381. if (batch.token) {
  6382. const int64_t n_tokens = batch.n_tokens;
  6383. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6384. }
  6385. if (batch.embd) {
  6386. const int64_t n_embd = hparams.n_embd;
  6387. const int64_t n_tokens = batch.n_tokens;
  6388. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6389. }
  6390. if (batch.pos) {
  6391. const int64_t n_tokens = batch.n_tokens;
  6392. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6393. }
  6394. {
  6395. const int64_t n_kv = kv_self.n;
  6396. const int64_t n_tokens = batch.n_tokens;
  6397. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6398. float * data = (float *) lctx.inp_KQ_mask->data;
  6399. for (int h = 0; h < 1; ++h) {
  6400. for (int j = 0; j < n_tokens; ++j) {
  6401. const llama_pos pos = batch.pos[j];
  6402. const llama_seq_id seq_id = batch.seq_id[j][0];
  6403. for (int i = 0; i < n_kv; ++i) {
  6404. float f;
  6405. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) ||
  6406. (hparams.causal_attn && lctx.kv_self.cells[i].pos > pos)) {
  6407. f = -INFINITY;
  6408. } else {
  6409. f = 0;
  6410. }
  6411. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6412. }
  6413. }
  6414. }
  6415. }
  6416. if (hparams.need_kq_pos) {
  6417. const int64_t n_kv = kv_self.n;
  6418. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6419. float * data = (float *) lctx.inp_KQ_pos->data;
  6420. for (int i = 0; i < n_kv; ++i) {
  6421. data[i] = float(lctx.kv_self.cells[i].pos);
  6422. }
  6423. }
  6424. if (kv_self.has_shift) {
  6425. const int64_t n_ctx = cparams.n_ctx;
  6426. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6427. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6428. for (int i = 0; i < n_ctx; ++i) {
  6429. data[i] = lctx.kv_self.cells[i].delta;
  6430. }
  6431. }
  6432. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_MEAN) {
  6433. const int64_t n_tokens = batch.n_tokens;
  6434. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6435. float * data = (float *) lctx.inp_mean->data;
  6436. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6437. std::vector<uint64_t> sum(n_tokens, 0);
  6438. for (int i = 0; i < n_tokens; ++i) {
  6439. const llama_seq_id seq_id = batch.seq_id[i][0];
  6440. sum[seq_id] += 1;
  6441. }
  6442. std::vector<float> div(n_tokens, 0.0f);
  6443. for (int i = 0; i < n_tokens; ++i) {
  6444. const uint64_t s = sum[i];
  6445. if (s > 0) {
  6446. div[i] = 1.0f/float(s);
  6447. }
  6448. }
  6449. for (int i = 0; i < n_tokens; ++i) {
  6450. const llama_seq_id seq_id = batch.seq_id[i][0];
  6451. data[seq_id*n_tokens + i] = div[seq_id];
  6452. }
  6453. }
  6454. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_CLS) {
  6455. const int64_t n_tokens = batch.n_tokens;
  6456. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6457. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6458. for (int i = 0; i < n_tokens; ++i) {
  6459. const llama_seq_id seq_id = batch.seq_id[i][0];
  6460. const llama_pos pos = batch.pos[i];
  6461. if (pos == 0) {
  6462. data[seq_id] = i;
  6463. }
  6464. }
  6465. }
  6466. }
  6467. // decode a batch of tokens by evaluating the transformer
  6468. //
  6469. // - lctx: llama context
  6470. // - batch: batch to evaluate
  6471. //
  6472. // return 0 on success
  6473. // return positive int on warning
  6474. // return negative int on error
  6475. //
  6476. static int llama_decode_internal(
  6477. llama_context & lctx,
  6478. llama_batch batch) {
  6479. const uint32_t n_tokens = batch.n_tokens;
  6480. if (n_tokens == 0) {
  6481. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6482. return -1;
  6483. }
  6484. const auto & model = lctx.model;
  6485. const auto & hparams = model.hparams;
  6486. const auto & cparams = lctx.cparams;
  6487. const auto n_batch = cparams.n_batch;
  6488. GGML_ASSERT(n_tokens <= n_batch);
  6489. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6490. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6491. const int64_t t_start_us = ggml_time_us();
  6492. #ifdef GGML_USE_MPI
  6493. // TODO: needs fix after #3228
  6494. GGML_ASSERT(false && "not implemented");
  6495. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6496. #endif
  6497. GGML_ASSERT(n_threads > 0);
  6498. auto & kv_self = lctx.kv_self;
  6499. const int64_t n_embd = hparams.n_embd;
  6500. const int64_t n_vocab = hparams.n_vocab;
  6501. // helpers for smoother batch API transition
  6502. // after deprecating the llama_eval calls, these will be removed
  6503. std::vector<llama_pos> pos;
  6504. std::vector<int32_t> n_seq_id;
  6505. std::vector<llama_seq_id *> seq_id_arr;
  6506. std::vector<std::vector<llama_seq_id>> seq_id;
  6507. if (batch.pos == nullptr) {
  6508. pos.resize(n_tokens);
  6509. for (uint32_t i = 0; i < n_tokens; i++) {
  6510. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6511. }
  6512. batch.pos = pos.data();
  6513. }
  6514. if (batch.seq_id == nullptr) {
  6515. n_seq_id.resize(n_tokens);
  6516. seq_id.resize(n_tokens);
  6517. seq_id_arr.resize(n_tokens);
  6518. for (uint32_t i = 0; i < n_tokens; i++) {
  6519. n_seq_id[i] = 1;
  6520. seq_id[i].resize(1);
  6521. seq_id[i][0] = batch.all_seq_id;
  6522. seq_id_arr[i] = seq_id[i].data();
  6523. }
  6524. batch.n_seq_id = n_seq_id.data();
  6525. batch.seq_id = seq_id_arr.data();
  6526. }
  6527. // if we have enough unused cells before the current head ->
  6528. // better to start searching from the beginning of the cache, hoping to fill it
  6529. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6530. kv_self.head = 0;
  6531. }
  6532. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6533. return 1;
  6534. }
  6535. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6536. // after enough generations, the benefit from this heuristic disappears
  6537. // if we start defragmenting the cache, the benefit from this will be more important
  6538. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6539. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6540. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6541. ggml_backend_sched_reset(lctx.sched);
  6542. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6543. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6544. // the output is always the last tensor in the graph
  6545. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6546. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  6547. if (strcmp(res->name, "result_output") == 0) {
  6548. // the embeddings could be the second to last tensor, or the third to last tensor
  6549. if (strcmp(embeddings->name, "result_norm") != 0) {
  6550. embeddings = gf->nodes[gf->n_nodes - 3];
  6551. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  6552. }
  6553. } else if (strcmp(res->name, "result_embd") == 0) {
  6554. embeddings = res;
  6555. res = nullptr;
  6556. } else {
  6557. GGML_ASSERT(false);
  6558. }
  6559. // 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);
  6560. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6561. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6562. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6563. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6564. // with the BLAS calls. need a better solution
  6565. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6566. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6567. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6568. n_threads = std::min(4, n_threads);
  6569. }
  6570. #ifdef GGML_USE_MPI
  6571. const int64_t n_layer = hparams.n_layer;
  6572. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6573. #endif
  6574. #ifdef GGML_USE_METAL
  6575. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6576. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6577. }
  6578. #endif
  6579. if (lctx.backend_cpu != nullptr) {
  6580. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6581. }
  6582. llama_set_inputs(lctx, batch);
  6583. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6584. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6585. #ifdef GGML_USE_MPI
  6586. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6587. #endif
  6588. // update the kv ring buffer
  6589. {
  6590. if (kv_self.has_shift) {
  6591. kv_self.has_shift = false;
  6592. for (uint32_t i = 0; i < kv_self.size; ++i) {
  6593. kv_self.cells[i].delta = 0;
  6594. }
  6595. }
  6596. kv_self.head += n_tokens;
  6597. // Ensure kv cache head points to a valid index.
  6598. if (kv_self.head >= kv_self.size) {
  6599. kv_self.head = 0;
  6600. }
  6601. }
  6602. #ifdef GGML_PERF
  6603. // print timing information per ggml operation (for debugging purposes)
  6604. // requires GGML_PERF to be defined
  6605. ggml_graph_print(gf);
  6606. #endif
  6607. // plot the computation graph in dot format (for debugging purposes)
  6608. //if (n_past%100 == 0) {
  6609. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6610. //}
  6611. // extract logits
  6612. // TODO: do not compute and extract logits if only embeddings are needed
  6613. // need to update the graphs to skip "result_output"
  6614. if (res) {
  6615. auto & logits_out = lctx.logits;
  6616. #ifndef NDEBUG
  6617. auto & logits_valid = lctx.logits_valid;
  6618. logits_valid.clear();
  6619. logits_valid.resize(n_tokens);
  6620. logits_out.clear();
  6621. #endif
  6622. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6623. GGML_ASSERT(res_backend != nullptr);
  6624. if (batch.logits) {
  6625. logits_out.resize(n_vocab * n_tokens);
  6626. for (uint32_t i = 0; i < n_tokens; i++) {
  6627. if (batch.logits[i] == 0) {
  6628. continue;
  6629. }
  6630. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6631. #ifndef NDEBUG
  6632. logits_valid[i] = true;
  6633. #endif
  6634. }
  6635. } else if (lctx.logits_all) {
  6636. logits_out.resize(n_vocab * n_tokens);
  6637. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6638. #ifndef NDEBUG
  6639. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6640. #endif
  6641. } else {
  6642. logits_out.resize(n_vocab);
  6643. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6644. #ifndef NDEBUG
  6645. logits_valid[0] = true;
  6646. #endif
  6647. }
  6648. ggml_backend_synchronize(res_backend);
  6649. }
  6650. // extract embeddings
  6651. if (!lctx.embedding.empty()) {
  6652. auto & embedding_out = lctx.embedding;
  6653. const int64_t embd_pos = res ? n_embd * (n_tokens-1) : 0;
  6654. const int64_t embd_size = res ? n_embd : n_embd * n_tokens;
  6655. embedding_out.resize(embd_size);
  6656. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  6657. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), embd_pos*sizeof(float), embd_size*sizeof(float));
  6658. ggml_backend_synchronize(embeddings_backend);
  6659. }
  6660. // measure the performance only for the single-token evals
  6661. if (n_tokens == 1) {
  6662. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6663. lctx.n_eval++;
  6664. }
  6665. else if (n_tokens > 1) {
  6666. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6667. lctx.n_p_eval += n_tokens;
  6668. }
  6669. // get a more accurate load time, upon first eval
  6670. // TODO: fix this
  6671. if (!lctx.has_evaluated_once) {
  6672. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6673. lctx.has_evaluated_once = true;
  6674. }
  6675. return 0;
  6676. }
  6677. //
  6678. // tokenizer
  6679. //
  6680. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  6681. return vocab.type;
  6682. }
  6683. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  6684. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  6685. }
  6686. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  6687. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  6688. }
  6689. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  6690. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  6691. }
  6692. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  6693. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  6694. }
  6695. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  6696. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  6697. }
  6698. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  6699. GGML_ASSERT(llama_is_byte_token(vocab, id));
  6700. const auto& token_data = vocab.id_to_token.at(id);
  6701. switch (llama_vocab_get_type(vocab)) {
  6702. case LLAMA_VOCAB_TYPE_SPM: {
  6703. auto buf = token_data.text.substr(3, 2);
  6704. return strtol(buf.c_str(), NULL, 16);
  6705. }
  6706. case LLAMA_VOCAB_TYPE_BPE: {
  6707. GGML_ASSERT(false);
  6708. return unicode_to_bytes_bpe(token_data.text);
  6709. }
  6710. case LLAMA_VOCAB_TYPE_WPM: {
  6711. GGML_ASSERT(false);
  6712. }
  6713. default:
  6714. GGML_ASSERT(false);
  6715. }
  6716. }
  6717. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  6718. static const char * hex = "0123456789ABCDEF";
  6719. switch (llama_vocab_get_type(vocab)) {
  6720. case LLAMA_VOCAB_TYPE_SPM: {
  6721. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  6722. auto token = vocab.token_to_id.find(buf);
  6723. if (token != vocab.token_to_id.end()) {
  6724. return (*token).second;
  6725. }
  6726. // Try to fall back to just the byte as a string
  6727. const char buf2[2] = { (char)ch, 0 };
  6728. return vocab.token_to_id.at(buf2);
  6729. }
  6730. case LLAMA_VOCAB_TYPE_WPM:
  6731. case LLAMA_VOCAB_TYPE_BPE: {
  6732. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  6733. }
  6734. default:
  6735. GGML_ASSERT(false);
  6736. }
  6737. }
  6738. static void llama_escape_whitespace(std::string & text) {
  6739. replace_all(text, " ", "\xe2\x96\x81");
  6740. }
  6741. static void llama_unescape_whitespace(std::string & word) {
  6742. replace_all(word, "\xe2\x96\x81", " ");
  6743. }
  6744. struct llm_symbol {
  6745. using index = int;
  6746. index prev;
  6747. index next;
  6748. const char * text;
  6749. size_t n;
  6750. };
  6751. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  6752. // SPM tokenizer
  6753. // original implementation:
  6754. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  6755. struct llm_bigram_spm {
  6756. struct comparator {
  6757. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  6758. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  6759. }
  6760. };
  6761. using queue_storage = std::vector<llm_bigram_spm>;
  6762. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  6763. llm_symbol::index left;
  6764. llm_symbol::index right;
  6765. float score;
  6766. size_t size;
  6767. };
  6768. struct llm_tokenizer_spm {
  6769. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  6770. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6771. // split string into utf8 chars
  6772. int index = 0;
  6773. size_t offs = 0;
  6774. while (offs < text.size()) {
  6775. llm_symbol sym;
  6776. size_t len = utf8_len(text[offs]);
  6777. sym.text = text.c_str() + offs;
  6778. sym.n = std::min(len, text.size() - offs);
  6779. offs += sym.n;
  6780. sym.prev = index - 1;
  6781. sym.next = offs == text.size() ? -1 : index + 1;
  6782. index++;
  6783. symbols.emplace_back(sym);
  6784. }
  6785. // seed the work queue with all possible 2-character tokens.
  6786. for (size_t i = 1; i < symbols.size(); ++i) {
  6787. try_add_bigram(i - 1, i);
  6788. }
  6789. // keep substituting the highest frequency pairs for as long as we can.
  6790. while (!work_queue.empty()) {
  6791. auto bigram = work_queue.top();
  6792. work_queue.pop();
  6793. auto & left_sym = symbols[bigram.left];
  6794. auto & right_sym = symbols[bigram.right];
  6795. // if one of the symbols already got merged, skip it.
  6796. if (left_sym.n == 0 || right_sym.n == 0 ||
  6797. left_sym.n + right_sym.n != bigram.size) {
  6798. continue;
  6799. }
  6800. // merge the right sym into the left one
  6801. left_sym.n += right_sym.n;
  6802. right_sym.n = 0;
  6803. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  6804. // remove the right sym from the chain
  6805. left_sym.next = right_sym.next;
  6806. if (right_sym.next >= 0) {
  6807. symbols[right_sym.next].prev = bigram.left;
  6808. }
  6809. // find more substitutions
  6810. try_add_bigram(left_sym.prev, bigram.left);
  6811. try_add_bigram(bigram.left, left_sym.next);
  6812. }
  6813. for (int i = 0; i != -1; i = symbols[i].next) {
  6814. auto & symbol = symbols[i];
  6815. resegment(symbol, output);
  6816. }
  6817. }
  6818. private:
  6819. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  6820. auto text = std::string(symbol.text, symbol.n);
  6821. auto token = vocab.token_to_id.find(text);
  6822. // Do we need to support is_unused?
  6823. if (token != vocab.token_to_id.end()) {
  6824. output.push_back((*token).second);
  6825. return;
  6826. }
  6827. const auto p = rev_merge.find(text);
  6828. if (p == rev_merge.end()) {
  6829. // output any symbols that did not form tokens as bytes.
  6830. output.reserve(output.size() + symbol.n);
  6831. for (int j = 0; j < (int)symbol.n; ++j) {
  6832. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  6833. output.push_back(token_id);
  6834. }
  6835. return;
  6836. }
  6837. resegment(symbols[p->second.first], output);
  6838. resegment(symbols[p->second.second], output);
  6839. }
  6840. void try_add_bigram(int left, int right) {
  6841. if (left == -1 || right == -1) {
  6842. return;
  6843. }
  6844. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  6845. auto token = vocab.token_to_id.find(text);
  6846. if (token == vocab.token_to_id.end()) {
  6847. return;
  6848. }
  6849. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  6850. return;
  6851. }
  6852. const auto & tok_data = vocab.id_to_token[(*token).second];
  6853. llm_bigram_spm bigram;
  6854. bigram.left = left;
  6855. bigram.right = right;
  6856. bigram.score = tok_data.score;
  6857. bigram.size = text.size();
  6858. work_queue.push(bigram);
  6859. // Do we need to support is_unused?
  6860. rev_merge[text] = std::make_pair(left, right);
  6861. }
  6862. const llama_vocab & vocab;
  6863. std::vector<llm_symbol> symbols;
  6864. llm_bigram_spm::queue work_queue;
  6865. std::map<std::string, std::pair<int, int>> rev_merge;
  6866. };
  6867. // BPE tokenizer
  6868. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  6869. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  6870. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  6871. struct llm_bigram_bpe {
  6872. struct comparator {
  6873. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  6874. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  6875. }
  6876. };
  6877. using queue_storage = std::vector<llm_bigram_bpe>;
  6878. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  6879. llm_symbol::index left;
  6880. llm_symbol::index right;
  6881. std::string text;
  6882. int rank;
  6883. size_t size;
  6884. };
  6885. struct llm_tokenizer_bpe {
  6886. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  6887. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6888. int final_prev_index = -1;
  6889. auto word_collection = bpe_gpt2_preprocess(text);
  6890. symbols_final.clear();
  6891. for (auto & word : word_collection) {
  6892. work_queue = llm_bigram_bpe::queue();
  6893. symbols.clear();
  6894. int index = 0;
  6895. size_t offset = 0;
  6896. while (offset < word.size()) {
  6897. llm_symbol sym;
  6898. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  6899. sym.text = word.c_str() + offset;
  6900. sym.n = char_len;
  6901. offset += sym.n;
  6902. sym.prev = index - 1;
  6903. sym.next = offset == word.size() ? -1 : index + 1;
  6904. index++;
  6905. symbols.emplace_back(sym);
  6906. }
  6907. for (size_t i = 1; i < symbols.size(); ++i) {
  6908. add_new_bigram(i - 1, i);
  6909. }
  6910. // build token(s)
  6911. while (!work_queue.empty()) {
  6912. auto bigram = work_queue.top();
  6913. work_queue.pop();
  6914. auto & left_symbol = symbols[bigram.left];
  6915. auto & right_symbol = symbols[bigram.right];
  6916. if (left_symbol.n == 0 || right_symbol.n == 0) {
  6917. continue;
  6918. }
  6919. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  6920. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  6921. if (left_token + right_token != bigram.text) {
  6922. continue; // Skip this bigram if it's outdated
  6923. }
  6924. // merge the right sym into the left one
  6925. left_symbol.n += right_symbol.n;
  6926. right_symbol.n = 0;
  6927. // remove the right sym from the chain
  6928. left_symbol.next = right_symbol.next;
  6929. if (right_symbol.next >= 0) {
  6930. symbols[right_symbol.next].prev = bigram.left;
  6931. }
  6932. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  6933. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  6934. }
  6935. // add the fnished tokens to the final list keeping correct order for next and prev
  6936. for (auto & sym : symbols) {
  6937. if (sym.n > 0) {
  6938. sym.prev = final_prev_index;
  6939. sym.next = -1;
  6940. if (final_prev_index != -1) {
  6941. symbols_final[final_prev_index].next = symbols_final.size();
  6942. }
  6943. symbols_final.emplace_back(sym);
  6944. final_prev_index = symbols_final.size() - 1;
  6945. }
  6946. }
  6947. }
  6948. symbols = symbols_final;
  6949. if (!symbols.empty()) {
  6950. for (int i = 0; i != -1; i = symbols[i].next) {
  6951. auto & symbol = symbols[i];
  6952. if (symbol.n == 0) {
  6953. continue;
  6954. }
  6955. const std::string str = std::string(symbol.text, symbol.n);
  6956. const auto token = vocab.token_to_id.find(str);
  6957. if (token == vocab.token_to_id.end()) {
  6958. for (auto j = str.begin(); j != str.end(); ++j) {
  6959. std::string byte_str(1, *j);
  6960. auto token_multibyte = vocab.token_to_id.find(byte_str);
  6961. if (token_multibyte == vocab.token_to_id.end()) {
  6962. throw std::runtime_error("ERROR: byte not found in vocab");
  6963. }
  6964. output.push_back((*token_multibyte).second);
  6965. }
  6966. } else {
  6967. output.push_back((*token).second);
  6968. }
  6969. }
  6970. }
  6971. }
  6972. private:
  6973. void add_new_bigram(int left, int right) {
  6974. if (left == -1 || right == -1) {
  6975. return;
  6976. }
  6977. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  6978. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  6979. int rank_found = -1;
  6980. rank_found = vocab.find_bpe_rank(left_token, right_token);
  6981. if (rank_found < 0) {
  6982. return;
  6983. }
  6984. llm_bigram_bpe bigram;
  6985. bigram.left = left;
  6986. bigram.right = right;
  6987. bigram.text = left_token + right_token;
  6988. bigram.size = left_token.size() + right_token.size();
  6989. bigram.rank = rank_found;
  6990. work_queue.push(bigram);
  6991. }
  6992. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  6993. std::vector<std::string> bpe_words;
  6994. std::vector<std::string> bpe_encoded_words;
  6995. std::string token = "";
  6996. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  6997. bool collecting_numeric = false;
  6998. bool collecting_letter = false;
  6999. bool collecting_special = false;
  7000. bool collecting_whitespace_lookahead = false;
  7001. bool collecting = false;
  7002. std::vector<std::string> text_utf;
  7003. text_utf.reserve(text.size());
  7004. bpe_words.reserve(text.size());
  7005. bpe_encoded_words.reserve(text.size());
  7006. auto cps = codepoints_from_utf8(text);
  7007. for (size_t i = 0; i < cps.size(); ++i)
  7008. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7009. for (int i = 0; i < (int)text_utf.size(); i++) {
  7010. const std::string & utf_char = text_utf[i];
  7011. bool split_condition = false;
  7012. int bytes_remain = text_utf.size() - i;
  7013. // forward backward lookups
  7014. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7015. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7016. // handling contractions
  7017. if (!split_condition && bytes_remain >= 2) {
  7018. // 's|'t|'m|'d
  7019. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7020. split_condition = true;
  7021. }
  7022. if (split_condition) {
  7023. if (token.size()) {
  7024. bpe_words.emplace_back(token); // push previous content as token
  7025. }
  7026. token = utf_char + utf_char_next;
  7027. bpe_words.emplace_back(token);
  7028. token = "";
  7029. i++;
  7030. continue;
  7031. }
  7032. }
  7033. if (!split_condition && bytes_remain >= 3) {
  7034. // 're|'ve|'ll
  7035. if (utf_char == "\'" && (
  7036. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7037. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7038. (utf_char_next == "l" && utf_char_next_next == "l"))
  7039. ) {
  7040. split_condition = true;
  7041. }
  7042. if (split_condition) {
  7043. // current token + next token can be defined
  7044. if (token.size()) {
  7045. bpe_words.emplace_back(token); // push previous content as token
  7046. }
  7047. token = utf_char + utf_char_next + utf_char_next_next;
  7048. bpe_words.emplace_back(token); // the contraction
  7049. token = "";
  7050. i += 2;
  7051. continue;
  7052. }
  7053. }
  7054. if (!split_condition && !collecting) {
  7055. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7056. collecting_letter = true;
  7057. collecting = true;
  7058. }
  7059. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7060. collecting_numeric = true;
  7061. collecting = true;
  7062. }
  7063. else if (
  7064. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7065. (!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)
  7066. ) {
  7067. collecting_special = true;
  7068. collecting = true;
  7069. }
  7070. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7071. collecting_whitespace_lookahead = true;
  7072. collecting = true;
  7073. }
  7074. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7075. split_condition = true;
  7076. }
  7077. }
  7078. else if (!split_condition && collecting) {
  7079. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7080. split_condition = true;
  7081. }
  7082. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7083. split_condition = true;
  7084. }
  7085. 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)) {
  7086. split_condition = true;
  7087. }
  7088. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7089. split_condition = true;
  7090. }
  7091. }
  7092. if (utf_char_next == "") {
  7093. split_condition = true; // final
  7094. token += utf_char;
  7095. }
  7096. if (split_condition) {
  7097. if (token.size()) {
  7098. bpe_words.emplace_back(token);
  7099. }
  7100. token = utf_char;
  7101. collecting = false;
  7102. collecting_letter = false;
  7103. collecting_numeric = false;
  7104. collecting_special = false;
  7105. collecting_whitespace_lookahead = false;
  7106. }
  7107. else {
  7108. token += utf_char;
  7109. }
  7110. }
  7111. for (std::string & word : bpe_words) {
  7112. std::string encoded_token = "";
  7113. for (char & c : word) {
  7114. encoded_token += bytes_to_unicode_bpe(c);
  7115. }
  7116. bpe_encoded_words.emplace_back(encoded_token);
  7117. }
  7118. return bpe_encoded_words;
  7119. }
  7120. const llama_vocab & vocab;
  7121. std::vector<llm_symbol> symbols;
  7122. std::vector<llm_symbol> symbols_final;
  7123. llm_bigram_bpe::queue work_queue;
  7124. };
  7125. struct llm_tokenizer_wpm {
  7126. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7127. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7128. auto * token_map = &vocab.token_to_id;
  7129. // normalize and split by whitespace
  7130. std::vector<std::string> words = preprocess(text);
  7131. // bos token prepended already
  7132. // find the longest tokens that form the words
  7133. for (const std::string &word : words) {
  7134. // skip empty words
  7135. if (word.size() == 0) {
  7136. continue;
  7137. }
  7138. // prepend phantom space
  7139. std::string word1 = "\xe2\x96\x81" + word;
  7140. int n = word1.size();
  7141. // we're at the start of a new word
  7142. int i = 0;
  7143. bool match_any = false;
  7144. // move through character position in word
  7145. while (i < n) {
  7146. // loop through possible match length
  7147. bool match = false;
  7148. for (int j = n; j > i; j--) {
  7149. auto it = token_map->find(word1.substr(i, j - i));
  7150. if (it != token_map->end()) {
  7151. output.push_back(it->second);
  7152. match = true;
  7153. match_any = true;
  7154. i = j;
  7155. break;
  7156. }
  7157. }
  7158. // must be an unknown character
  7159. if (!match) {
  7160. i++;
  7161. }
  7162. }
  7163. // we didn't find any matches for this word
  7164. if (!match_any) {
  7165. output.push_back(vocab.special_unk_id);
  7166. }
  7167. }
  7168. // append eos token
  7169. output.push_back(vocab.special_eos_id);
  7170. }
  7171. std::vector<std::string> preprocess(const std::string & text) {
  7172. std::string ori_str = normalize(text);
  7173. uint64_t ori_size = ori_str.size();
  7174. // single punct / single symbol / single digit
  7175. // baseline: add whitespace on the left and right of punct and chinese characters
  7176. std::vector<std::string> words;
  7177. std::string new_str = "";
  7178. uint64_t i = 0;
  7179. while (i < ori_size) {
  7180. int utf_char_len = utf8_len(ori_str[i]);
  7181. if ((utf_char_len == 1) && ispunct(ori_str[i])) {
  7182. new_str += " ";
  7183. new_str += ori_str[i];
  7184. new_str += " ";
  7185. i += 1;
  7186. }
  7187. else if ((utf_char_len == 3) && is_chinese_char(ori_str.substr(i, 3))) {
  7188. new_str += " ";
  7189. new_str += ori_str.substr(i, 3);
  7190. new_str += " ";
  7191. i += 3;
  7192. }
  7193. else {
  7194. new_str += ori_str[i];
  7195. i += 1;
  7196. }
  7197. }
  7198. // split by whitespace
  7199. uint64_t l = 0;
  7200. uint64_t r = 0;
  7201. while (r < new_str.size()) {
  7202. // if is whitespace
  7203. if (isspace(new_str[r])) {
  7204. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7205. l = r + 1;
  7206. r = l;
  7207. }
  7208. else {
  7209. r += 1;
  7210. }
  7211. }
  7212. if (r > l) {
  7213. words.push_back(new_str.substr(l, (r - l)));
  7214. }
  7215. return words;
  7216. }
  7217. std::string normalize(const std::string & text) {
  7218. // TODO: handle chinese characters? https://github.com/huggingface/tokenizers/blob/ef5f50605ddf9f8caef1598c0e4853862b9707a7/tokenizers/src/normalizers/bert.rs#L98
  7219. std::string text2 = strip_accents(text);
  7220. for (size_t i = 0; i < text2.size(); i += utf8_len(text2[i])) {
  7221. char c = text2[i];
  7222. if (c >= 'A' && c <= 'Z') {
  7223. text2[i] = c - 'A' + 'a';
  7224. }
  7225. }
  7226. return text2;
  7227. }
  7228. bool is_chinese_char(const std::string & str) {
  7229. int len = str.length();
  7230. unsigned int codepoint = 0;
  7231. int num_bytes = 0;
  7232. int i = 0;
  7233. unsigned char ch = static_cast<unsigned char>(str[i]);
  7234. if (ch <= 0x7f) {
  7235. codepoint = ch;
  7236. num_bytes = 1;
  7237. } else if ((ch >> 5) == 0x06) {
  7238. codepoint = ch & 0x1f;
  7239. num_bytes = 2;
  7240. } else if ((ch >> 4) == 0x0e) {
  7241. codepoint = ch & 0x0f;
  7242. num_bytes = 3;
  7243. } else if ((ch >> 3) == 0x1e) {
  7244. codepoint = ch & 0x07;
  7245. num_bytes = 4;
  7246. }
  7247. for (int j = 1; j < num_bytes; ++j) {
  7248. if (i + j >= len) {
  7249. return false; // incomplete UTF-8 character
  7250. }
  7251. unsigned char next_ch = static_cast<unsigned char>(str[i + j]);
  7252. if ((next_ch >> 6) != 0x02) {
  7253. return false; // invalid trailing byte
  7254. }
  7255. codepoint = (codepoint << 6) | (next_ch & 0x3f);
  7256. }
  7257. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7258. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7259. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7260. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7261. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7262. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7263. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7264. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7265. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7266. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7267. return true; // NOLINT
  7268. }
  7269. return false;
  7270. }
  7271. std::string strip_accents(const std::string & input_string) {
  7272. std::string resultString;
  7273. std::map<std::string, char> accent_map = {
  7274. {"À", 'A'}, {"Á", 'A'}, {"Â", 'A'}, {"Ã", 'A'}, {"Ä", 'A'}, {"Å", 'A'},
  7275. {"à", 'a'}, {"á", 'a'}, {"â", 'a'}, {"ã", 'a'}, {"ä", 'a'}, {"å", 'a'},
  7276. {"È", 'E'}, {"É", 'E'}, {"Ê", 'E'}, {"Ë", 'E'}, {"è", 'e'}, {"é", 'e'},
  7277. {"ê", 'e'}, {"ë", 'e'}, {"Ì", 'I'}, {"Í", 'I'}, {"Î", 'I'}, {"Ï", 'I'},
  7278. {"ì", 'i'}, {"í", 'i'}, {"î", 'i'}, {"ï", 'i'}, {"Ò", 'O'}, {"Ó", 'O'},
  7279. {"Ô", 'O'}, {"Õ", 'O'}, {"Ö", 'O'}, {"ò", 'o'}, {"ó", 'o'}, {"ô", 'o'},
  7280. {"õ", 'o'}, {"ö", 'o'}, {"Ù", 'U'}, {"Ú", 'U'}, {"Û", 'U'}, {"Ü", 'U'},
  7281. {"ù", 'u'}, {"ú", 'u'}, {"û", 'u'}, {"ü", 'u'}, {"Ý", 'Y'}, {"ý", 'y'},
  7282. {"Ç", 'C'}, {"ç", 'c'}, {"Ñ", 'N'}, {"ñ", 'n'},
  7283. };
  7284. for (size_t i = 0; i < input_string.length();) {
  7285. int len = utf8_len(input_string[i]);
  7286. std::string curChar = input_string.substr(i, len);
  7287. auto iter = accent_map.find(curChar);
  7288. if (iter != accent_map.end()) {
  7289. resultString += iter->second;
  7290. } else {
  7291. resultString += curChar;
  7292. }
  7293. i += len;
  7294. }
  7295. return resultString;
  7296. }
  7297. static size_t utf8_len(char src) {
  7298. const size_t lookup[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4};
  7299. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  7300. return lookup[highbits];
  7301. }
  7302. const llama_vocab & vocab;
  7303. };
  7304. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7305. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7306. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7307. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7308. struct fragment_buffer_variant {
  7309. fragment_buffer_variant(llama_vocab::id _token)
  7310. :
  7311. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7312. token(_token),
  7313. raw_text(_dummy),
  7314. offset(0),
  7315. length(0) {}
  7316. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7317. :
  7318. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7319. token((llama_vocab::id) - 1),
  7320. raw_text(_raw_text),
  7321. offset(_offset),
  7322. length(_length){
  7323. GGML_ASSERT(_offset >= 0);
  7324. GGML_ASSERT(_length >= 1);
  7325. GGML_ASSERT(offset + length <= raw_text.length());
  7326. }
  7327. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7328. const llama_vocab::id token;
  7329. const std::string _dummy;
  7330. const std::string & raw_text;
  7331. const uint64_t offset;
  7332. const uint64_t length;
  7333. };
  7334. // #define PRETOKENIZERDEBUG
  7335. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7336. // for each special token
  7337. for (const auto & st: vocab.special_tokens_cache) {
  7338. const auto & special_token = st.first;
  7339. const auto & special_id = st.second;
  7340. // for each text fragment
  7341. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7342. while (it != buffer.end()) {
  7343. auto & fragment = (*it);
  7344. // if a fragment is text ( not yet processed )
  7345. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7346. auto * raw_text = &(fragment.raw_text);
  7347. auto raw_text_base_offset = fragment.offset;
  7348. auto raw_text_base_length = fragment.length;
  7349. // loop over the text
  7350. while (true) {
  7351. // find the first occurrence of a given special token in this fragment
  7352. // passing offset argument only limit the "search area" but match coordinates
  7353. // are still relative to the source full raw_text
  7354. auto match = raw_text->find(special_token, raw_text_base_offset);
  7355. // no occurrences found, stop processing this fragment for a given special token
  7356. if (match == std::string::npos) break;
  7357. // check if match is within bounds of offset <-> length
  7358. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7359. #ifdef PRETOKENIZERDEBUG
  7360. 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());
  7361. #endif
  7362. auto source = std::distance(buffer.begin(), it);
  7363. // if match is further than base offset
  7364. // then we have some text to the left of it
  7365. if (match > raw_text_base_offset) {
  7366. // left
  7367. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7368. const int64_t left_reminder_length = match - raw_text_base_offset;
  7369. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7370. #ifdef PRETOKENIZERDEBUG
  7371. 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());
  7372. #endif
  7373. it++;
  7374. }
  7375. // special token
  7376. buffer.emplace_after(it, special_id);
  7377. it++;
  7378. // right
  7379. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7380. const int64_t right_reminder_offset = match + special_token.length();
  7381. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7382. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7383. #ifdef PRETOKENIZERDEBUG
  7384. 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());
  7385. #endif
  7386. it++;
  7387. if (source == 0) {
  7388. buffer.erase_after(buffer.before_begin());
  7389. } else {
  7390. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7391. }
  7392. // repeat for the right side
  7393. raw_text_base_offset = right_reminder_offset;
  7394. raw_text_base_length = right_reminder_length;
  7395. #ifdef PRETOKENIZERDEBUG
  7396. 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());
  7397. #endif
  7398. } else {
  7399. if (source == 0) {
  7400. buffer.erase_after(buffer.before_begin());
  7401. } else {
  7402. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7403. }
  7404. break;
  7405. }
  7406. }
  7407. }
  7408. it++;
  7409. }
  7410. }
  7411. }
  7412. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7413. std::vector<llama_vocab::id> output;
  7414. // OG tokenizer behavior:
  7415. //
  7416. // tokenizer.encode('', add_bos=True) returns [1]
  7417. // tokenizer.encode('', add_bos=False) returns []
  7418. if (bos && vocab.special_bos_id != -1) {
  7419. output.push_back(vocab.special_bos_id);
  7420. }
  7421. if (raw_text.empty()) {
  7422. return output;
  7423. }
  7424. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7425. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7426. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7427. switch (vocab.type) {
  7428. case LLAMA_VOCAB_TYPE_SPM:
  7429. {
  7430. for (const auto & fragment : fragment_buffer) {
  7431. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7432. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7433. // TODO: It's likely possible to get rid of this string copy entirely
  7434. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7435. // and passing 'add space prefix' as bool argument
  7436. //
  7437. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7438. if (&fragment == &fragment_buffer.front()) {
  7439. if (vocab.add_space_prefix) {
  7440. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7441. }
  7442. }
  7443. #ifdef PRETOKENIZERDEBUG
  7444. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7445. #endif
  7446. llm_tokenizer_spm tokenizer(vocab);
  7447. llama_escape_whitespace(raw_text);
  7448. tokenizer.tokenize(raw_text, output);
  7449. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7450. output.push_back(fragment.token);
  7451. }
  7452. }
  7453. } break;
  7454. case LLAMA_VOCAB_TYPE_BPE:
  7455. {
  7456. for (const auto & fragment : fragment_buffer) {
  7457. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7458. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7459. #ifdef PRETOKENIZERDEBUG
  7460. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7461. #endif
  7462. llm_tokenizer_bpe tokenizer(vocab);
  7463. tokenizer.tokenize(raw_text, output);
  7464. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7465. output.push_back(fragment.token);
  7466. }
  7467. }
  7468. } break;
  7469. case LLAMA_VOCAB_TYPE_WPM:
  7470. {
  7471. for (const auto & fragment : fragment_buffer) {
  7472. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7473. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7474. #ifdef PRETOKENIZERDEBUG
  7475. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7476. #endif
  7477. llm_tokenizer_wpm tokenizer(vocab);
  7478. tokenizer.tokenize(raw_text, output);
  7479. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7480. output.push_back(fragment.token);
  7481. }
  7482. }
  7483. } break;
  7484. }
  7485. return output;
  7486. }
  7487. //
  7488. // grammar - internal
  7489. //
  7490. struct llama_partial_utf8 {
  7491. uint32_t value; // bit value so far (unshifted)
  7492. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7493. };
  7494. struct llama_grammar {
  7495. const std::vector<std::vector<llama_grammar_element>> rules;
  7496. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7497. // buffer for partially generated UTF-8 sequence from accepted tokens
  7498. llama_partial_utf8 partial_utf8;
  7499. };
  7500. struct llama_grammar_candidate {
  7501. size_t index;
  7502. const uint32_t * code_points;
  7503. llama_partial_utf8 partial_utf8;
  7504. };
  7505. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7506. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7507. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7508. const std::string & src,
  7509. llama_partial_utf8 partial_start) {
  7510. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7511. const char * pos = src.c_str();
  7512. std::vector<uint32_t> code_points;
  7513. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7514. code_points.reserve(src.size() + 1);
  7515. uint32_t value = partial_start.value;
  7516. int n_remain = partial_start.n_remain;
  7517. // continue previous decode, if applicable
  7518. while (*pos != 0 && n_remain > 0) {
  7519. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7520. if ((next_byte >> 6) != 2) {
  7521. // invalid sequence, abort
  7522. code_points.push_back(0);
  7523. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7524. }
  7525. value = (value << 6) + (next_byte & 0x3F);
  7526. ++pos;
  7527. --n_remain;
  7528. }
  7529. if (partial_start.n_remain > 0 && n_remain == 0) {
  7530. code_points.push_back(value);
  7531. }
  7532. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7533. while (*pos != 0) {
  7534. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7535. uint8_t highbits = first_byte >> 4;
  7536. n_remain = lookup[highbits] - 1;
  7537. if (n_remain < 0) {
  7538. // invalid sequence, abort
  7539. code_points.clear();
  7540. code_points.push_back(0);
  7541. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7542. }
  7543. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7544. value = first_byte & mask;
  7545. ++pos;
  7546. while (*pos != 0 && n_remain > 0) {
  7547. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7548. ++pos;
  7549. --n_remain;
  7550. }
  7551. if (n_remain == 0) {
  7552. code_points.push_back(value);
  7553. }
  7554. }
  7555. code_points.push_back(0);
  7556. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7557. }
  7558. // returns true iff pos points to the end of one of the definitions of a rule
  7559. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7560. switch (pos->type) {
  7561. case LLAMA_GRETYPE_END: return true; // NOLINT
  7562. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  7563. default: return false;
  7564. }
  7565. }
  7566. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  7567. // asserts that pos is pointing to a char range element
  7568. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  7569. const llama_grammar_element * pos,
  7570. const uint32_t chr) {
  7571. bool found = false;
  7572. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7573. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  7574. do {
  7575. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7576. // inclusive range, e.g. [a-z]
  7577. found = found || (pos->value <= chr && chr <= pos[1].value);
  7578. pos += 2;
  7579. } else {
  7580. // exact char match, e.g. [a] or "a"
  7581. found = found || pos->value == chr;
  7582. pos += 1;
  7583. }
  7584. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7585. return std::make_pair(found == is_positive_char, pos);
  7586. }
  7587. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  7588. // range at pos (regular or inverse range)
  7589. // asserts that pos is pointing to a char range element
  7590. static bool llama_grammar_match_partial_char(
  7591. const llama_grammar_element * pos,
  7592. const llama_partial_utf8 partial_utf8) {
  7593. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7594. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  7595. uint32_t partial_value = partial_utf8.value;
  7596. int n_remain = partial_utf8.n_remain;
  7597. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  7598. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  7599. return false;
  7600. }
  7601. // range of possible code points this partial UTF-8 sequence could complete to
  7602. uint32_t low = partial_value << (n_remain * 6);
  7603. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  7604. if (low == 0) {
  7605. if (n_remain == 2) {
  7606. low = 1 << 11;
  7607. } else if (n_remain == 3) {
  7608. low = 1 << 16;
  7609. }
  7610. }
  7611. do {
  7612. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7613. // inclusive range, e.g. [a-z]
  7614. if (pos->value <= high && low <= pos[1].value) {
  7615. return is_positive_char;
  7616. }
  7617. pos += 2;
  7618. } else {
  7619. // exact char match, e.g. [a] or "a"
  7620. if (low <= pos->value && pos->value <= high) {
  7621. return is_positive_char;
  7622. }
  7623. pos += 1;
  7624. }
  7625. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7626. return !is_positive_char;
  7627. }
  7628. // transforms a grammar pushdown stack into N possible stacks, all ending
  7629. // at a character range (terminal element)
  7630. static void llama_grammar_advance_stack(
  7631. const std::vector<std::vector<llama_grammar_element>> & rules,
  7632. const std::vector<const llama_grammar_element *> & stack,
  7633. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  7634. if (stack.empty()) {
  7635. new_stacks.emplace_back(stack);
  7636. return;
  7637. }
  7638. const llama_grammar_element * pos = stack.back();
  7639. switch (pos->type) {
  7640. case LLAMA_GRETYPE_RULE_REF: {
  7641. const size_t rule_id = static_cast<size_t>(pos->value);
  7642. const llama_grammar_element * subpos = rules[rule_id].data();
  7643. do {
  7644. // init new stack without the top (pos)
  7645. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7646. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  7647. // if this rule ref is followed by another element, add that to stack
  7648. new_stack.push_back(pos + 1);
  7649. }
  7650. if (!llama_grammar_is_end_of_sequence(subpos)) {
  7651. // if alternate is nonempty, add to stack
  7652. new_stack.push_back(subpos);
  7653. }
  7654. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7655. while (!llama_grammar_is_end_of_sequence(subpos)) {
  7656. // scan to end of alternate def
  7657. subpos++;
  7658. }
  7659. if (subpos->type == LLAMA_GRETYPE_ALT) {
  7660. // there's another alternate def of this rule to process
  7661. subpos++;
  7662. } else {
  7663. break;
  7664. }
  7665. } while (true);
  7666. break;
  7667. }
  7668. case LLAMA_GRETYPE_CHAR:
  7669. case LLAMA_GRETYPE_CHAR_NOT:
  7670. new_stacks.emplace_back(stack);
  7671. break;
  7672. default:
  7673. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  7674. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  7675. // those
  7676. GGML_ASSERT(false);
  7677. }
  7678. }
  7679. // takes a set of possible pushdown stacks on a grammar, which are required to
  7680. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  7681. // produces the N possible stacks if the given char is accepted at those
  7682. // positions
  7683. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  7684. const std::vector<std::vector<llama_grammar_element>> & rules,
  7685. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7686. const uint32_t chr) {
  7687. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  7688. for (const auto & stack : stacks) {
  7689. if (stack.empty()) {
  7690. continue;
  7691. }
  7692. auto match = llama_grammar_match_char(stack.back(), chr);
  7693. if (match.first) {
  7694. const llama_grammar_element * pos = match.second;
  7695. // update top of stack to next element, if any
  7696. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7697. if (!llama_grammar_is_end_of_sequence(pos)) {
  7698. new_stack.push_back(pos);
  7699. }
  7700. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7701. }
  7702. }
  7703. return new_stacks;
  7704. }
  7705. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7706. const std::vector<std::vector<llama_grammar_element>> & rules,
  7707. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7708. const std::vector<llama_grammar_candidate> & candidates);
  7709. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  7710. const std::vector<std::vector<llama_grammar_element>> & rules,
  7711. const std::vector<const llama_grammar_element *> & stack,
  7712. const std::vector<llama_grammar_candidate> & candidates) {
  7713. std::vector<llama_grammar_candidate> rejects;
  7714. if (stack.empty()) {
  7715. for (const auto & tok : candidates) {
  7716. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  7717. rejects.push_back(tok);
  7718. }
  7719. }
  7720. return rejects;
  7721. }
  7722. const llama_grammar_element * stack_pos = stack.back();
  7723. std::vector<llama_grammar_candidate> next_candidates;
  7724. for (const auto & tok : candidates) {
  7725. if (*tok.code_points == 0) {
  7726. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  7727. // that cannot satisfy this position in grammar
  7728. if (tok.partial_utf8.n_remain != 0 &&
  7729. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  7730. rejects.push_back(tok);
  7731. }
  7732. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  7733. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  7734. } else {
  7735. rejects.push_back(tok);
  7736. }
  7737. }
  7738. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  7739. // update top of stack to next element, if any
  7740. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  7741. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  7742. stack_after.push_back(stack_pos_after);
  7743. }
  7744. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  7745. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  7746. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  7747. for (const auto & tok : next_rejects) {
  7748. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  7749. }
  7750. return rejects;
  7751. }
  7752. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7753. const std::vector<std::vector<llama_grammar_element>> & rules,
  7754. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7755. const std::vector<llama_grammar_candidate> & candidates) {
  7756. GGML_ASSERT(!stacks.empty()); // REVIEW
  7757. if (candidates.empty()) {
  7758. return std::vector<llama_grammar_candidate>();
  7759. }
  7760. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  7761. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  7762. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  7763. }
  7764. return rejects;
  7765. }
  7766. //
  7767. // grammar - external
  7768. //
  7769. struct llama_grammar * llama_grammar_init(
  7770. const llama_grammar_element ** rules,
  7771. size_t n_rules,
  7772. size_t start_rule_index) {
  7773. const llama_grammar_element * pos;
  7774. // copy rule definitions into vectors
  7775. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  7776. for (size_t i = 0; i < n_rules; i++) {
  7777. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  7778. vec_rules[i].push_back(*pos);
  7779. }
  7780. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  7781. }
  7782. // loop over alternates of start rule to build initial stacks
  7783. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7784. pos = rules[start_rule_index];
  7785. do {
  7786. std::vector<const llama_grammar_element *> stack;
  7787. if (!llama_grammar_is_end_of_sequence(pos)) {
  7788. // if alternate is nonempty, add to stack
  7789. stack.push_back(pos);
  7790. }
  7791. llama_grammar_advance_stack(vec_rules, stack, stacks);
  7792. while (!llama_grammar_is_end_of_sequence(pos)) {
  7793. // scan to end of alternate def
  7794. pos++;
  7795. }
  7796. if (pos->type == LLAMA_GRETYPE_ALT) {
  7797. // there's another alternate def of this rule to process
  7798. pos++;
  7799. } else {
  7800. break;
  7801. }
  7802. } while (true);
  7803. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  7804. }
  7805. void llama_grammar_free(struct llama_grammar * grammar) {
  7806. delete grammar;
  7807. }
  7808. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  7809. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  7810. // redirect elements in stacks to point to new rules
  7811. for (size_t is = 0; is < result->stacks.size(); is++) {
  7812. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  7813. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  7814. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  7815. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  7816. result->stacks[is][ie] = &result->rules[ir0][ir1];
  7817. }
  7818. }
  7819. }
  7820. }
  7821. }
  7822. return result;
  7823. }
  7824. //
  7825. // sampling
  7826. //
  7827. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  7828. if (seed == LLAMA_DEFAULT_SEED) {
  7829. seed = time(NULL);
  7830. }
  7831. ctx->rng.seed(seed);
  7832. }
  7833. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  7834. GGML_ASSERT(candidates->size > 0);
  7835. const int64_t t_start_sample_us = ggml_time_us();
  7836. // Sort the logits in descending order
  7837. if (!candidates->sorted) {
  7838. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7839. return a.logit > b.logit;
  7840. });
  7841. candidates->sorted = true;
  7842. }
  7843. float max_l = candidates->data[0].logit;
  7844. float cum_sum = 0.0f;
  7845. for (size_t i = 0; i < candidates->size; ++i) {
  7846. float p = expf(candidates->data[i].logit - max_l);
  7847. candidates->data[i].p = p;
  7848. cum_sum += p;
  7849. }
  7850. for (size_t i = 0; i < candidates->size; ++i) {
  7851. candidates->data[i].p /= cum_sum;
  7852. }
  7853. if (ctx) {
  7854. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7855. }
  7856. }
  7857. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  7858. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  7859. // if (k >= (int32_t)candidates->size) {
  7860. // return;
  7861. // }
  7862. const int64_t t_start_sample_us = ggml_time_us();
  7863. if (k <= 0) {
  7864. k = candidates->size;
  7865. }
  7866. k = std::max(k, (int) min_keep);
  7867. k = std::min(k, (int) candidates->size);
  7868. // Sort scores in descending order
  7869. if (!candidates->sorted) {
  7870. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  7871. return a.logit > b.logit;
  7872. };
  7873. if (k <= 128) {
  7874. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  7875. } else {
  7876. constexpr int nbuckets = 128;
  7877. constexpr float bucket_low = -10.0f;
  7878. constexpr float bucket_high = 10.0f;
  7879. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  7880. constexpr float bucker_inter = -bucket_low * bucket_scale;
  7881. std::vector<int> bucket_idx(candidates->size);
  7882. std::vector<int> histo(nbuckets, 0);
  7883. for (int i = 0; i < (int)candidates->size; ++i) {
  7884. const float val = candidates->data[i].logit;
  7885. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  7886. ib = std::max(0, std::min(nbuckets-1, ib));
  7887. bucket_idx[i] = ib;
  7888. ++histo[ib];
  7889. }
  7890. int nhave = 0;
  7891. int ib = nbuckets - 1;
  7892. for ( ; ib >= 0; --ib) {
  7893. nhave += histo[ib];
  7894. if (nhave >= k) break;
  7895. }
  7896. std::vector<llama_token_data> tmp_tokens(nhave);
  7897. auto ptr = tmp_tokens.data();
  7898. std::vector<llama_token_data*> bucket_ptrs;
  7899. bucket_ptrs.reserve(nbuckets - ib);
  7900. for (int j = nbuckets - 1; j >= ib; --j) {
  7901. bucket_ptrs.push_back(ptr);
  7902. ptr += histo[j];
  7903. }
  7904. for (int i = 0; i < (int)candidates->size; ++i) {
  7905. int j = bucket_idx[i];
  7906. if (j >= ib) {
  7907. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  7908. }
  7909. }
  7910. ptr = tmp_tokens.data();
  7911. int ndone = 0;
  7912. for (int j = nbuckets-1; j > ib; --j) {
  7913. std::sort(ptr, ptr + histo[j], comp);
  7914. ptr += histo[j];
  7915. ndone += histo[j];
  7916. }
  7917. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  7918. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  7919. }
  7920. candidates->sorted = true;
  7921. }
  7922. candidates->size = k;
  7923. if (ctx) {
  7924. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7925. }
  7926. }
  7927. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7928. if (p >= 1.0f) {
  7929. return;
  7930. }
  7931. llama_sample_softmax(ctx, candidates);
  7932. const int64_t t_start_sample_us = ggml_time_us();
  7933. // Compute the cumulative probabilities
  7934. float cum_sum = 0.0f;
  7935. size_t last_idx = candidates->size;
  7936. for (size_t i = 0; i < candidates->size; ++i) {
  7937. cum_sum += candidates->data[i].p;
  7938. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  7939. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  7940. if (cum_sum >= p && i + 1 >= min_keep) {
  7941. last_idx = i + 1;
  7942. break;
  7943. }
  7944. }
  7945. // Resize the output vector to keep only the top-p tokens
  7946. candidates->size = last_idx;
  7947. if (ctx) {
  7948. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7949. }
  7950. }
  7951. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7952. if (p <= 0.0f || !candidates->size) {
  7953. return;
  7954. }
  7955. const int64_t t_start_sample_us = ggml_time_us();
  7956. bool min_p_applied = false;
  7957. // if the candidates aren't sorted, try the unsorted implementation first
  7958. if (!candidates->sorted) {
  7959. std::vector<llama_token_data> filtered_tokens;
  7960. float max_logit = -FLT_MAX;
  7961. for (size_t i = 0; i < candidates->size; ++i) {
  7962. max_logit = std::max(max_logit, candidates->data[i].logit);
  7963. }
  7964. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  7965. for (size_t i = 0; i < candidates->size; ++i) {
  7966. if (candidates->data[i].logit >= min_logit) {
  7967. filtered_tokens.push_back(candidates->data[i]);
  7968. }
  7969. }
  7970. // if we have enough values the operation was a success
  7971. if (filtered_tokens.size() >= min_keep) {
  7972. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  7973. candidates->size = filtered_tokens.size();
  7974. min_p_applied = true;
  7975. }
  7976. }
  7977. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  7978. if (!min_p_applied) {
  7979. // Sort the logits in descending order
  7980. if (!candidates->sorted) {
  7981. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7982. return a.logit > b.logit;
  7983. });
  7984. candidates->sorted = true;
  7985. }
  7986. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  7987. size_t i = 1; // first token always matches
  7988. for (; i < candidates->size; ++i) {
  7989. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  7990. break; // prob too small
  7991. }
  7992. }
  7993. // Resize the output vector to keep only the matching tokens
  7994. candidates->size = i;
  7995. }
  7996. if (ctx) {
  7997. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7998. }
  7999. }
  8000. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8001. if (z >= 1.0f || candidates->size <= 2) {
  8002. return;
  8003. }
  8004. llama_sample_softmax(nullptr, candidates);
  8005. const int64_t t_start_sample_us = ggml_time_us();
  8006. // Compute the first and second derivatives
  8007. std::vector<float> first_derivatives(candidates->size - 1);
  8008. std::vector<float> second_derivatives(candidates->size - 2);
  8009. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8010. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8011. }
  8012. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8013. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8014. }
  8015. // Calculate absolute value of second derivatives
  8016. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8017. second_derivatives[i] = std::abs(second_derivatives[i]);
  8018. }
  8019. // Normalize the second derivatives
  8020. {
  8021. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8022. if (second_derivatives_sum > 1e-6f) {
  8023. for (float & value : second_derivatives) {
  8024. value /= second_derivatives_sum;
  8025. }
  8026. } else {
  8027. for (float & value : second_derivatives) {
  8028. value = 1.0f / second_derivatives.size();
  8029. }
  8030. }
  8031. }
  8032. float cum_sum = 0.0f;
  8033. size_t last_idx = candidates->size;
  8034. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8035. cum_sum += second_derivatives[i];
  8036. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8037. if (cum_sum > z && i >= min_keep) {
  8038. last_idx = i;
  8039. break;
  8040. }
  8041. }
  8042. // Resize the output vector to keep only the tokens above the tail location
  8043. candidates->size = last_idx;
  8044. if (ctx) {
  8045. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8046. }
  8047. }
  8048. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8049. // Reference implementation:
  8050. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8051. if (p >= 1.0f) {
  8052. return;
  8053. }
  8054. // Compute the softmax of logits and calculate entropy
  8055. llama_sample_softmax(nullptr, candidates);
  8056. const int64_t t_start_sample_us = ggml_time_us();
  8057. float entropy = 0.0f;
  8058. for (size_t i = 0; i < candidates->size; ++i) {
  8059. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8060. }
  8061. // Compute the absolute difference between negative log probability and entropy for each candidate
  8062. std::vector<float> shifted_scores;
  8063. for (size_t i = 0; i < candidates->size; ++i) {
  8064. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8065. shifted_scores.push_back(shifted_score);
  8066. }
  8067. // Sort tokens based on the shifted_scores and their corresponding indices
  8068. std::vector<size_t> indices(candidates->size);
  8069. std::iota(indices.begin(), indices.end(), 0);
  8070. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8071. return shifted_scores[a] < shifted_scores[b];
  8072. });
  8073. // Compute the cumulative probabilities
  8074. float cum_sum = 0.0f;
  8075. size_t last_idx = indices.size();
  8076. for (size_t i = 0; i < indices.size(); ++i) {
  8077. size_t idx = indices[i];
  8078. cum_sum += candidates->data[idx].p;
  8079. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8080. if (cum_sum > p && i >= min_keep - 1) {
  8081. last_idx = i + 1;
  8082. break;
  8083. }
  8084. }
  8085. // Resize the output vector to keep only the locally typical tokens
  8086. std::vector<llama_token_data> new_candidates;
  8087. for (size_t i = 0; i < last_idx; ++i) {
  8088. size_t idx = indices[i];
  8089. new_candidates.push_back(candidates->data[idx]);
  8090. }
  8091. // Replace the data in candidates with the new_candidates data
  8092. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8093. candidates->size = new_candidates.size();
  8094. candidates->sorted = false;
  8095. if (ctx) {
  8096. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8097. }
  8098. }
  8099. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8100. const int64_t t_start_sample_us = ggml_time_us();
  8101. // no need to do anything if there is only one (or zero) candidates
  8102. if(candidates_p->size <= 1) {
  8103. return;
  8104. }
  8105. // Calculate maximum possible entropy
  8106. float max_entropy = -logf(1.0f / candidates_p->size);
  8107. llama_sample_softmax(nullptr, candidates_p);
  8108. // Calculate entropy of the softmax probabilities
  8109. float entropy = 0.0f;
  8110. for (size_t i = 0; i < candidates_p->size; ++i) {
  8111. float prob = candidates_p->data[i].p;
  8112. if (prob > 0.0f) { // Ensure no log(0)
  8113. entropy -= prob * logf(prob);
  8114. }
  8115. }
  8116. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8117. float normalized_entropy = entropy / max_entropy;
  8118. // Map the normalized entropy to the desired temperature range using the power function
  8119. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8120. #ifdef DEBUG
  8121. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8122. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8123. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8124. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8125. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8126. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8127. #endif
  8128. // Apply the dynamically calculated temperature scaling
  8129. for (size_t i = 0; i < candidates_p->size; ++i) {
  8130. candidates_p->data[i].logit /= dyn_temp;
  8131. }
  8132. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8133. double max_l_double = candidates_p->data[0].logit;
  8134. double cum_sum_double = 0.0;
  8135. for (size_t i = 0; i < candidates_p->size; ++i) {
  8136. double p = exp(candidates_p->data[i].logit - max_l_double);
  8137. candidates_p->data[i].p = p; // Store the scaled probability
  8138. cum_sum_double += p;
  8139. }
  8140. for (size_t i = 0; i < candidates_p->size; ++i) {
  8141. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8142. }
  8143. #ifdef DEBUG
  8144. // Print the updated top 25 probabilities after temperature scaling
  8145. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8146. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8147. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8148. }
  8149. #endif
  8150. if (ctx) {
  8151. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8152. }
  8153. }
  8154. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8155. const int64_t t_start_sample_us = ggml_time_us();
  8156. for (size_t i = 0; i < candidates_p->size; ++i) {
  8157. candidates_p->data[i].logit /= temp;
  8158. }
  8159. if (ctx) {
  8160. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8161. }
  8162. }
  8163. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8164. llama_sample_temp(ctx, candidates_p, temp);
  8165. }
  8166. void llama_sample_repetition_penalties(
  8167. struct llama_context * ctx,
  8168. llama_token_data_array * candidates,
  8169. const llama_token * last_tokens,
  8170. size_t penalty_last_n,
  8171. float penalty_repeat,
  8172. float penalty_freq,
  8173. float penalty_present) {
  8174. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8175. return;
  8176. }
  8177. const int64_t t_start_sample_us = ggml_time_us();
  8178. // Create a frequency map to count occurrences of each token in last_tokens
  8179. std::unordered_map<llama_token, int> token_count;
  8180. for (size_t i = 0; i < penalty_last_n; ++i) {
  8181. token_count[last_tokens[i]]++;
  8182. }
  8183. // Apply frequency and presence penalties to the candidates
  8184. for (size_t i = 0; i < candidates->size; ++i) {
  8185. const auto token_iter = token_count.find(candidates->data[i].id);
  8186. if (token_iter == token_count.end()) {
  8187. continue;
  8188. }
  8189. const int count = token_iter->second;
  8190. // 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.
  8191. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8192. if (candidates->data[i].logit <= 0) {
  8193. candidates->data[i].logit *= penalty_repeat;
  8194. } else {
  8195. candidates->data[i].logit /= penalty_repeat;
  8196. }
  8197. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8198. }
  8199. candidates->sorted = false;
  8200. if (ctx) {
  8201. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8202. }
  8203. }
  8204. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8205. GGML_ASSERT(ctx);
  8206. const int64_t t_start_sample_us = ggml_time_us();
  8207. bool allow_eos = false;
  8208. for (const auto & stack : grammar->stacks) {
  8209. if (stack.empty()) {
  8210. allow_eos = true;
  8211. break;
  8212. }
  8213. }
  8214. const llama_token eos = llama_token_eos(&ctx->model);
  8215. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8216. candidates_decoded.reserve(candidates->size);
  8217. std::vector<llama_grammar_candidate> candidates_grammar;
  8218. candidates_grammar.reserve(candidates->size);
  8219. for (size_t i = 0; i < candidates->size; ++i) {
  8220. const llama_token id = candidates->data[i].id;
  8221. const std::string piece = llama_token_to_piece(ctx, id);
  8222. if (id == eos) {
  8223. if (!allow_eos) {
  8224. candidates->data[i].logit = -INFINITY;
  8225. }
  8226. } else if (piece.empty() || piece[0] == 0) {
  8227. candidates->data[i].logit = -INFINITY;
  8228. } else {
  8229. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8230. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8231. }
  8232. }
  8233. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8234. for (const auto & reject : rejects) {
  8235. candidates->data[reject.index].logit = -INFINITY;
  8236. }
  8237. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8238. }
  8239. static void llama_log_softmax(float * array, size_t size) {
  8240. float max_l = *std::max_element(array, array + size);
  8241. float sum = 0.f;
  8242. for (size_t i = 0; i < size; ++i) {
  8243. float p = expf(array[i] - max_l);
  8244. sum += p;
  8245. array[i] = p;
  8246. }
  8247. for (size_t i = 0; i < size; ++i) {
  8248. array[i] = logf(array[i] / sum);
  8249. }
  8250. }
  8251. void llama_sample_apply_guidance(
  8252. struct llama_context * ctx,
  8253. float * logits,
  8254. float * logits_guidance,
  8255. float scale) {
  8256. GGML_ASSERT(ctx);
  8257. const auto t_start_sample_us = ggml_time_us();
  8258. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8259. llama_log_softmax(logits, n_vocab);
  8260. llama_log_softmax(logits_guidance, n_vocab);
  8261. for (int i = 0; i < n_vocab; ++i) {
  8262. auto & l = logits[i];
  8263. const auto & g = logits_guidance[i];
  8264. l = scale * (l - g) + g;
  8265. }
  8266. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8267. }
  8268. void llama_sample_classifier_free_guidance(
  8269. struct llama_context * ctx,
  8270. llama_token_data_array * candidates,
  8271. struct llama_context * guidance_ctx,
  8272. float scale) {
  8273. GGML_ASSERT(ctx);
  8274. int64_t t_start_sample_us;
  8275. t_start_sample_us = ggml_time_us();
  8276. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  8277. GGML_ASSERT(n_vocab == candidates->size);
  8278. GGML_ASSERT(!candidates->sorted);
  8279. std::vector<float> logits_base(n_vocab);
  8280. for (size_t i = 0; i < n_vocab; ++i) {
  8281. logits_base[i] = candidates->data[i].logit;
  8282. }
  8283. float * logits_guidance = llama_get_logits(guidance_ctx);
  8284. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8285. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  8286. t_start_sample_us = ggml_time_us();
  8287. for (size_t i = 0; i < n_vocab; ++i) {
  8288. candidates->data[i].logit = logits_base[i];
  8289. }
  8290. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8291. }
  8292. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8293. GGML_ASSERT(ctx);
  8294. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8295. int64_t t_start_sample_us;
  8296. t_start_sample_us = ggml_time_us();
  8297. llama_sample_softmax(nullptr, candidates);
  8298. // Estimate s_hat using the most probable m tokens
  8299. float s_hat = 0.0;
  8300. float sum_ti_bi = 0.0;
  8301. float sum_ti_sq = 0.0;
  8302. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8303. float t_i = logf(float(i + 2) / float(i + 1));
  8304. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8305. sum_ti_bi += t_i * b_i;
  8306. sum_ti_sq += t_i * t_i;
  8307. }
  8308. s_hat = sum_ti_bi / sum_ti_sq;
  8309. // Compute k from the estimated s_hat and target surprise value
  8310. float epsilon_hat = s_hat - 1;
  8311. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8312. // Sample the next word X using top-k sampling
  8313. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8314. if (ctx) {
  8315. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8316. }
  8317. llama_token X = llama_sample_token(ctx, candidates);
  8318. t_start_sample_us = ggml_time_us();
  8319. // Compute error as the difference between observed surprise and target surprise value
  8320. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8321. return candidate.id == X;
  8322. }));
  8323. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8324. float e = observed_surprise - tau;
  8325. // Update mu using the learning rate and error
  8326. *mu = *mu - eta * e;
  8327. if (ctx) {
  8328. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8329. }
  8330. return X;
  8331. }
  8332. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8333. int64_t t_start_sample_us;
  8334. t_start_sample_us = ggml_time_us();
  8335. llama_sample_softmax(ctx, candidates);
  8336. // Truncate the words with surprise values greater than mu
  8337. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8338. return -log2f(candidate.p) > *mu;
  8339. }));
  8340. if (candidates->size == 0) {
  8341. candidates->size = 1;
  8342. }
  8343. if (ctx) {
  8344. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8345. }
  8346. // Normalize the probabilities of the remaining words
  8347. llama_sample_softmax(ctx, candidates);
  8348. // Sample the next word X from the remaining words
  8349. llama_token X = llama_sample_token(ctx, candidates);
  8350. t_start_sample_us = ggml_time_us();
  8351. // Compute error as the difference between observed surprise and target surprise value
  8352. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8353. return candidate.id == X;
  8354. }));
  8355. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8356. float e = observed_surprise - tau;
  8357. // Update mu using the learning rate and error
  8358. *mu = *mu - eta * e;
  8359. if (ctx) {
  8360. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8361. }
  8362. return X;
  8363. }
  8364. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8365. const int64_t t_start_sample_us = ggml_time_us();
  8366. // Find max element
  8367. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8368. return a.logit < b.logit;
  8369. });
  8370. llama_token result = max_iter->id;
  8371. if (ctx) {
  8372. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8373. ctx->n_sample++;
  8374. }
  8375. return result;
  8376. }
  8377. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8378. GGML_ASSERT(ctx);
  8379. const int64_t t_start_sample_us = ggml_time_us();
  8380. llama_sample_softmax(nullptr, candidates);
  8381. std::vector<float> probs;
  8382. probs.reserve(candidates->size);
  8383. for (size_t i = 0; i < candidates->size; ++i) {
  8384. probs.push_back(candidates->data[i].p);
  8385. }
  8386. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8387. auto & rng = ctx->rng;
  8388. int idx = dist(rng);
  8389. llama_token result = candidates->data[idx].id;
  8390. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8391. ctx->n_sample++;
  8392. return result;
  8393. }
  8394. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8395. const int64_t t_start_sample_us = ggml_time_us();
  8396. if (token == llama_token_eos(&ctx->model)) {
  8397. for (const auto & stack : grammar->stacks) {
  8398. if (stack.empty()) {
  8399. return;
  8400. }
  8401. }
  8402. GGML_ASSERT(false);
  8403. }
  8404. const std::string piece = llama_token_to_piece(ctx, token);
  8405. // Note terminating 0 in decoded string
  8406. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8407. const auto & code_points = decoded.first;
  8408. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8409. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8410. }
  8411. grammar->partial_utf8 = decoded.second;
  8412. GGML_ASSERT(!grammar->stacks.empty());
  8413. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8414. }
  8415. //
  8416. // Beam search
  8417. //
  8418. struct llama_beam {
  8419. std::vector<llama_token> tokens;
  8420. float p; // Cumulative beam probability (renormalized relative to all beams)
  8421. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8422. // Sort beams by probability. In case of ties, prefer beams at eob.
  8423. bool operator<(const llama_beam & rhs) const {
  8424. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8425. }
  8426. // Shift off first n tokens and discard them.
  8427. void shift_tokens(const size_t n) {
  8428. if (n) {
  8429. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8430. tokens.resize(tokens.size() - n);
  8431. }
  8432. }
  8433. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8434. };
  8435. // A struct for calculating logit-related info.
  8436. struct llama_logit_info {
  8437. const float * const logits;
  8438. const int n_vocab;
  8439. const float max_l;
  8440. const float normalizer;
  8441. struct sum_exp {
  8442. float max_l;
  8443. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8444. };
  8445. llama_logit_info(llama_context * ctx)
  8446. : logits(llama_get_logits(ctx))
  8447. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8448. , max_l(*std::max_element(logits, logits + n_vocab))
  8449. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8450. { }
  8451. llama_token_data get_token_data(const llama_token token_id) const {
  8452. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8453. return {token_id, logits[token_id], p};
  8454. }
  8455. // Return top k token_data by logit.
  8456. std::vector<llama_token_data> top_k(size_t k) {
  8457. std::vector<llama_token_data> min_heap; // min-heap by logit
  8458. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8459. min_heap.reserve(k_min);
  8460. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8461. min_heap.push_back(get_token_data(token_id));
  8462. }
  8463. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8464. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8465. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8466. if (min_heap.front().logit < logits[token_id]) {
  8467. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8468. min_heap.back().id = token_id;
  8469. min_heap.back().logit = logits[token_id];
  8470. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8471. }
  8472. }
  8473. return min_heap;
  8474. }
  8475. float probability_from_logit(float logit) const {
  8476. return normalizer * std::exp(logit - max_l);
  8477. }
  8478. };
  8479. struct llama_beam_search_data {
  8480. llama_context * ctx;
  8481. size_t n_beams;
  8482. int n_past;
  8483. int n_predict;
  8484. std::vector<llama_beam> beams;
  8485. std::vector<llama_beam> next_beams;
  8486. // Re-calculated on each loop iteration
  8487. size_t common_prefix_length;
  8488. // Used to communicate to/from callback on beams state.
  8489. std::vector<llama_beam_view> beam_views;
  8490. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8491. : ctx(ctx)
  8492. , n_beams(n_beams)
  8493. , n_past(n_past)
  8494. , n_predict(n_predict)
  8495. , beam_views(n_beams) {
  8496. beams.reserve(n_beams);
  8497. next_beams.reserve(n_beams);
  8498. }
  8499. // Collapse beams to a single beam given by index.
  8500. void collapse_beams(const size_t beam_idx) {
  8501. if (0u < beam_idx) {
  8502. std::swap(beams[0], beams[beam_idx]);
  8503. }
  8504. beams.resize(1);
  8505. }
  8506. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8507. // The repetitive patterns below reflect the 2 stages of heaps:
  8508. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8509. // * If the heap is full and a new element is found that should be included, pop the
  8510. // least element to the back(), replace it with the new, then push it into the heap.
  8511. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8512. // Min-heaps use a greater-than comparator.
  8513. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8514. if (beam.eob) {
  8515. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8516. if (next_beams.size() < n_beams) {
  8517. next_beams.push_back(std::move(beam));
  8518. if (next_beams.size() == n_beams) {
  8519. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8520. }
  8521. } else if (next_beams.front().p < beam.p) {
  8522. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8523. next_beams.back() = std::move(beam);
  8524. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8525. }
  8526. } else {
  8527. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8528. if (!beam.tokens.empty()) {
  8529. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8530. }
  8531. llama_logit_info logit_info(ctx);
  8532. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8533. size_t i=0;
  8534. if (next_beams.size() < n_beams) {
  8535. for (; next_beams.size() < n_beams ; ++i) {
  8536. llama_beam next_beam = beam;
  8537. next_beam.tokens.push_back(next_tokens[i].id);
  8538. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8539. next_beams.push_back(std::move(next_beam));
  8540. }
  8541. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8542. } else {
  8543. for (; next_beams.front().p == 0.0f ; ++i) {
  8544. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8545. next_beams.back() = beam;
  8546. next_beams.back().tokens.push_back(next_tokens[i].id);
  8547. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8548. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8549. }
  8550. }
  8551. for (; i < n_beams ; ++i) {
  8552. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8553. if (next_beams.front().p < next_p) {
  8554. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8555. next_beams.back() = beam;
  8556. next_beams.back().tokens.push_back(next_tokens[i].id);
  8557. next_beams.back().p = next_p;
  8558. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8559. }
  8560. }
  8561. }
  8562. }
  8563. // Find common_prefix_length based on beams.
  8564. // Requires beams is not empty.
  8565. size_t find_common_prefix_length() {
  8566. size_t common_prefix_length = beams[0].tokens.size();
  8567. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8568. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8569. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8570. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8571. common_prefix_length = j;
  8572. break;
  8573. }
  8574. }
  8575. }
  8576. return common_prefix_length;
  8577. }
  8578. // Construct beams_state to send back to caller via the callback function.
  8579. // Side effect: set common_prefix_length = find_common_prefix_length();
  8580. llama_beams_state get_beams_state(const bool last_call) {
  8581. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8582. beam_views[i] = beams[i].view();
  8583. }
  8584. common_prefix_length = find_common_prefix_length();
  8585. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8586. }
  8587. // Loop:
  8588. // * while i < n_predict, AND
  8589. // * any of the beams have not yet reached end-of-beam (eob), AND
  8590. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  8591. // (since all other beam probabilities can only decrease)
  8592. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  8593. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  8594. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  8595. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  8596. !beams[top_beam_index()].eob ; ++i) {
  8597. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  8598. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  8599. if (common_prefix_length) {
  8600. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  8601. n_past += common_prefix_length;
  8602. }
  8603. // Zero-out next_beam probabilities to place them last in following min-heap.
  8604. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  8605. for (llama_beam & beam : beams) {
  8606. beam.shift_tokens(common_prefix_length);
  8607. fill_next_beams_by_top_probabilities(beam);
  8608. }
  8609. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  8610. beams.swap(next_beams);
  8611. renormalize_beam_probabilities(beams);
  8612. }
  8613. collapse_beams(top_beam_index());
  8614. callback(callback_data, get_beams_state(true));
  8615. }
  8616. // As beams grow, the cumulative probabilities decrease.
  8617. // Renormalize them to avoid floating point underflow.
  8618. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  8619. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  8620. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  8621. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  8622. }
  8623. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  8624. size_t top_beam_index() {
  8625. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  8626. }
  8627. // Copy (p,eob) for each beam which may have been changed by the callback.
  8628. void update_beams_from_beam_views() {
  8629. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8630. beams[i].p = beam_views[i].p;
  8631. beams[i].eob = beam_views[i].eob;
  8632. }
  8633. }
  8634. };
  8635. void llama_beam_search(llama_context * ctx,
  8636. llama_beam_search_callback_fn_t callback, void * callback_data,
  8637. size_t n_beams, int n_past, int n_predict) {
  8638. assert(ctx);
  8639. const int64_t t_start_sample_us = ggml_time_us();
  8640. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  8641. beam_search_data.loop(callback, callback_data);
  8642. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8643. ctx->n_sample++;
  8644. }
  8645. //
  8646. // quantization
  8647. //
  8648. struct quantize_state_internal {
  8649. const llama_model & model;
  8650. const llama_model_quantize_params * params;
  8651. int n_attention_wv = 0;
  8652. int n_ffn_down = 0;
  8653. int n_ffn_gate = 0;
  8654. int n_ffn_up = 0;
  8655. int i_attention_wv = 0;
  8656. int i_ffn_down = 0;
  8657. int i_ffn_gate = 0;
  8658. int i_ffn_up = 0;
  8659. int n_k_quantized = 0;
  8660. int n_fallback = 0;
  8661. bool has_imatrix = false;
  8662. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  8663. : model(model)
  8664. , params(params)
  8665. {}
  8666. };
  8667. static void llama_convert_tensor_internal(
  8668. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  8669. const size_t nelements, const int nthread
  8670. ) {
  8671. if (output.size() < nelements) {
  8672. output.resize(nelements);
  8673. }
  8674. float * f32_output = (float *) output.data();
  8675. ggml_type_traits_t qtype;
  8676. if (ggml_is_quantized(tensor->type)) {
  8677. qtype = ggml_internal_get_type_traits(tensor->type);
  8678. if (qtype.to_float == NULL) {
  8679. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  8680. }
  8681. } else if (tensor->type != GGML_TYPE_F16) {
  8682. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  8683. }
  8684. if (nthread < 2) {
  8685. if (tensor->type == GGML_TYPE_F16) {
  8686. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  8687. } else if (ggml_is_quantized(tensor->type)) {
  8688. qtype.to_float(tensor->data, f32_output, nelements);
  8689. } else {
  8690. GGML_ASSERT(false); // unreachable
  8691. }
  8692. return;
  8693. }
  8694. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  8695. size_t block_size_bytes = ggml_type_size(tensor->type);
  8696. GGML_ASSERT(nelements % block_size == 0);
  8697. size_t nblocks = nelements / block_size;
  8698. size_t blocks_per_thread = nblocks / nthread;
  8699. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  8700. size_t in_buff_offs = 0;
  8701. size_t out_buff_offs = 0;
  8702. for (int tnum = 0; tnum < nthread; tnum++) {
  8703. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  8704. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  8705. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  8706. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  8707. if (typ == GGML_TYPE_F16) {
  8708. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  8709. } else {
  8710. qtype.to_float(inbuf, outbuf, nels);
  8711. }
  8712. };
  8713. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  8714. in_buff_offs += thr_block_bytes;
  8715. out_buff_offs += thr_elems;
  8716. }
  8717. for (auto & w : workers) { w.join(); }
  8718. workers.clear();
  8719. }
  8720. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  8721. const std::string name = ggml_get_name(tensor);
  8722. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8723. const llm_arch arch = qs.model.arch;
  8724. const auto tn = LLM_TN(arch);
  8725. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  8726. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  8727. };
  8728. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  8729. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  8730. if (n_expert > 1) {
  8731. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  8732. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  8733. // for getting the current layer as I initially thought, and we need to resort to parsing the
  8734. // tensor name.
  8735. n_layer /= n_expert;
  8736. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  8737. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  8738. }
  8739. if (i_layer < 0 || i_layer >= n_layer) {
  8740. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  8741. }
  8742. }
  8743. return std::make_pair(i_layer, n_layer);
  8744. };
  8745. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  8746. int nx = tensor->ne[0];
  8747. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  8748. new_type = GGML_TYPE_Q8_0;
  8749. }
  8750. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8751. new_type = GGML_TYPE_Q5_K;
  8752. }
  8753. else if (new_type != GGML_TYPE_Q8_0) {
  8754. new_type = GGML_TYPE_Q6_K;
  8755. }
  8756. } else if (name == "token_embd.weight") {
  8757. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8758. new_type = GGML_TYPE_Q2_K;
  8759. }
  8760. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8761. new_type = GGML_TYPE_Q4_K;
  8762. }
  8763. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8764. if (name.find("attn_v.weight") != std::string::npos) {
  8765. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  8766. else new_type = GGML_TYPE_Q2_K;
  8767. ++qs.i_attention_wv;
  8768. }
  8769. else if (name.find("ffn_down") != std::string::npos) {
  8770. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  8771. ++qs.i_ffn_down;
  8772. }
  8773. else if (name.find("attn_output.weight") != std::string::npos) {
  8774. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  8775. }
  8776. } else if (name.find("attn_v.weight") != std::string::npos) {
  8777. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  8778. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8779. }
  8780. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  8781. new_type = GGML_TYPE_Q4_K;
  8782. }
  8783. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8784. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_Q3_K : GGML_TYPE_IQ3_XXS;
  8785. }
  8786. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8787. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8788. }
  8789. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8790. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL && qs.model.hparams.n_gqa() >= 4) {
  8791. new_type = GGML_TYPE_Q5_K;
  8792. }
  8793. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  8794. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  8795. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  8796. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  8797. (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;
  8798. if (qs.model.type == MODEL_70B) {
  8799. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  8800. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  8801. // nearly negligible increase in model size by quantizing this tensor with more bits:
  8802. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  8803. }
  8804. if (qs.model.hparams.n_expert == 8) {
  8805. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8806. // TODO: explore better strategies
  8807. new_type = GGML_TYPE_Q8_0;
  8808. }
  8809. ++qs.i_attention_wv;
  8810. } else if (name.find("attn_k.weight") != std::string::npos) {
  8811. if (qs.model.hparams.n_expert == 8) {
  8812. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8813. // TODO: explore better strategies
  8814. new_type = GGML_TYPE_Q8_0;
  8815. }
  8816. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8817. new_type = GGML_TYPE_Q2_K;
  8818. }
  8819. } else if (name.find("ffn_down") != std::string::npos) {
  8820. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  8821. int i_layer = info.first, n_layer = info.second;
  8822. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8823. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8824. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  8825. }
  8826. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  8827. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8828. }
  8829. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8830. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  8831. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  8832. : GGML_TYPE_Q3_K;
  8833. }
  8834. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  8835. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  8836. }
  8837. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  8838. if (arch == LLM_ARCH_FALCON) {
  8839. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  8840. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8841. } else {
  8842. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8843. }
  8844. }
  8845. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL && !qs.has_imatrix) {
  8846. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q5_K;
  8847. }
  8848. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8849. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  8850. new_type = GGML_TYPE_Q5_K;
  8851. }
  8852. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  8853. && qs.has_imatrix && i_layer < n_layer/8) {
  8854. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  8855. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  8856. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  8857. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  8858. }
  8859. ++qs.i_ffn_down;
  8860. } else if (name.find("attn_output.weight") != std::string::npos) {
  8861. if (arch != LLM_ARCH_FALCON) {
  8862. if (qs.model.hparams.n_expert == 8) {
  8863. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  8864. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  8865. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  8866. new_type = GGML_TYPE_Q5_K;
  8867. }
  8868. } else {
  8869. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  8870. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_Q3_K;
  8871. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  8872. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8873. }
  8874. } else {
  8875. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  8876. }
  8877. }
  8878. else if (name.find("attn_qkv.weight") != std::string::npos) {
  8879. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  8880. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  8881. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  8882. }
  8883. else if (name.find("ffn_gate") != std::string::npos) {
  8884. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  8885. int i_layer = info.first, n_layer = info.second;
  8886. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  8887. new_type = GGML_TYPE_Q2_K;
  8888. }
  8889. ++qs.i_ffn_gate;
  8890. }
  8891. else if (name.find("ffn_up") != std::string::npos) {
  8892. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  8893. int i_layer = info.first, n_layer = info.second;
  8894. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  8895. new_type = GGML_TYPE_Q2_K;
  8896. }
  8897. ++qs.i_ffn_up;
  8898. }
  8899. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8900. //}
  8901. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  8902. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  8903. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8904. //}
  8905. // This can be used to reduce the size of the Q5_K_S model.
  8906. // The associated PPL increase is fully in line with the size reduction
  8907. //else {
  8908. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  8909. //}
  8910. bool convert_incompatible_tensor = false;
  8911. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  8912. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  8913. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS ||
  8914. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8915. int nx = tensor->ne[0];
  8916. int ny = tensor->ne[1];
  8917. if (nx % QK_K != 0) {
  8918. 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));
  8919. convert_incompatible_tensor = true;
  8920. } else {
  8921. ++qs.n_k_quantized;
  8922. }
  8923. }
  8924. if (convert_incompatible_tensor) {
  8925. switch (new_type) {
  8926. case GGML_TYPE_IQ2_XXS:
  8927. case GGML_TYPE_IQ2_XS:
  8928. case GGML_TYPE_IQ3_XXS:
  8929. case GGML_TYPE_IQ1_S:
  8930. case GGML_TYPE_Q2_K:
  8931. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_IQ4_NL; break;
  8932. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  8933. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  8934. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  8935. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  8936. }
  8937. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  8938. ++qs.n_fallback;
  8939. }
  8940. return new_type;
  8941. }
  8942. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  8943. ggml_type quantized_type;
  8944. llama_ftype ftype = params->ftype;
  8945. switch (params->ftype) {
  8946. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  8947. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  8948. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  8949. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  8950. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  8951. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  8952. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  8953. // K-quants
  8954. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  8955. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  8956. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  8957. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  8958. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  8959. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  8960. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  8961. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  8962. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  8963. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  8964. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  8965. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  8966. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  8967. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  8968. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  8969. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  8970. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  8971. }
  8972. int nthread = params->nthread;
  8973. if (nthread <= 0) {
  8974. nthread = std::thread::hardware_concurrency();
  8975. }
  8976. // mmap consistently increases speed Linux, and also increases speed on Windows with
  8977. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  8978. #if defined(__linux__) || defined(_WIN32)
  8979. constexpr bool use_mmap = true;
  8980. #else
  8981. constexpr bool use_mmap = false;
  8982. #endif
  8983. llama_model_loader ml(fname_inp, use_mmap, NULL);
  8984. ml.init_mapping(false); // no prefetching?
  8985. llama_model model;
  8986. llm_load_arch(ml, model);
  8987. llm_load_hparams(ml, model);
  8988. struct quantize_state_internal qs(model, params);
  8989. if (params->only_copy) {
  8990. ftype = model.ftype;
  8991. }
  8992. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  8993. if (params->imatrix) {
  8994. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  8995. if (imatrix_data) {
  8996. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  8997. qs.has_imatrix = true;
  8998. }
  8999. }
  9000. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  9001. struct gguf_context * ctx_out = gguf_init_empty();
  9002. // copy the KV pairs from the input file
  9003. gguf_set_kv (ctx_out, ml.ctx_gguf);
  9004. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  9005. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  9006. for (int i = 0; i < ml.n_tensors; ++i) {
  9007. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9008. const std::string name = ggml_get_name(meta);
  9009. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9010. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9011. ++qs.n_attention_wv;
  9012. }
  9013. else if (name.find("ffn_down") != std::string::npos) {
  9014. ++qs.n_ffn_down;
  9015. }
  9016. else if (name.find("ffn_gate") != std::string::npos) {
  9017. ++qs.n_ffn_gate;
  9018. }
  9019. else if (name.find("ffn_up") != std::string::npos) {
  9020. ++qs.n_ffn_up;
  9021. }
  9022. }
  9023. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9024. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9025. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9026. }
  9027. size_t total_size_org = 0;
  9028. size_t total_size_new = 0;
  9029. std::vector<int64_t> hist_all(1 << 4, 0);
  9030. std::vector<std::thread> workers;
  9031. workers.reserve(nthread);
  9032. std::mutex mutex;
  9033. int idx = 0;
  9034. std::vector<no_init<uint8_t>> read_data;
  9035. std::vector<no_init<uint8_t>> work;
  9036. std::vector<no_init<float>> f32_conv_buf;
  9037. // populate the original tensors so we get an initial meta data
  9038. for (int i = 0; i < ml.n_tensors; ++i) {
  9039. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9040. gguf_add_tensor(ctx_out, meta);
  9041. }
  9042. std::ofstream fout(fname_out, std::ios::binary);
  9043. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9044. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9045. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9046. // placeholder for the meta data
  9047. ::zeros(fout, meta_size);
  9048. for (int i = 0; i < ml.n_tensors; ++i) {
  9049. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9050. const std::string name = ggml_get_name(tensor);
  9051. if (!ml.use_mmap) {
  9052. if (read_data.size() < ggml_nbytes(tensor)) {
  9053. read_data.resize(ggml_nbytes(tensor));
  9054. }
  9055. tensor->data = read_data.data();
  9056. }
  9057. ml.load_data_for(tensor);
  9058. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9059. ++idx, ml.n_tensors,
  9060. ggml_get_name(tensor),
  9061. llama_format_tensor_shape(tensor).c_str(),
  9062. ggml_type_name(tensor->type));
  9063. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9064. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9065. // quantize only 2D tensors
  9066. quantize &= (ggml_n_dims(tensor) == 2);
  9067. quantize &= params->quantize_output_tensor || name != "output.weight";
  9068. quantize &= !params->only_copy;
  9069. // do not quantize expert gating tensors
  9070. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_FFN_GATE_INP, "weight");
  9071. // do not quantize positional embeddings and token types (BERT)
  9072. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9073. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9074. enum ggml_type new_type;
  9075. void * new_data;
  9076. size_t new_size;
  9077. if (quantize) {
  9078. new_type = quantized_type;
  9079. if (!params->pure) {
  9080. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9081. }
  9082. // If we've decided to quantize to the same type the tensor is already
  9083. // in then there's nothing to do.
  9084. quantize = tensor->type != new_type;
  9085. }
  9086. if (!quantize) {
  9087. new_type = tensor->type;
  9088. new_data = tensor->data;
  9089. new_size = ggml_nbytes(tensor);
  9090. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9091. } else {
  9092. const size_t nelements = ggml_nelements(tensor);
  9093. const float * imatrix = nullptr;
  9094. if (imatrix_data) {
  9095. auto it = imatrix_data->find(tensor->name);
  9096. if (it == imatrix_data->end()) {
  9097. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9098. } else {
  9099. if (it->second.size() == (size_t)tensor->ne[0]) {
  9100. imatrix = it->second.data();
  9101. } else {
  9102. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9103. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9104. }
  9105. }
  9106. }
  9107. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9108. new_type == GGML_TYPE_IQ2_XS ||
  9109. new_type == GGML_TYPE_IQ1_S ||
  9110. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9111. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9112. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9113. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9114. LLAMA_LOG_ERROR("============================================================\n\n");
  9115. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9116. }
  9117. float * f32_data;
  9118. if (tensor->type == GGML_TYPE_F32) {
  9119. f32_data = (float *) tensor->data;
  9120. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9121. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9122. } else {
  9123. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9124. f32_data = (float *) f32_conv_buf.data();
  9125. }
  9126. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9127. fflush(stdout);
  9128. if (work.size() < nelements * 4) {
  9129. work.resize(nelements * 4); // upper bound on size
  9130. }
  9131. new_data = work.data();
  9132. std::array<int64_t, 1 << 4> hist_cur = {};
  9133. const int n_per_row = tensor->ne[0];
  9134. const int nrows = nelements / n_per_row;
  9135. static const int min_chunk_size = 32 * 512;
  9136. 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);
  9137. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9138. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9139. if (nthread_use < 2) {
  9140. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  9141. } else {
  9142. int counter = 0;
  9143. new_size = 0;
  9144. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9145. nrows, n_per_row, imatrix]() {
  9146. std::array<int64_t, 1 << 4> local_hist = {};
  9147. const int nrows_per_chunk = chunk_size / n_per_row;
  9148. size_t local_size = 0;
  9149. while (true) {
  9150. std::unique_lock<std::mutex> lock(mutex);
  9151. int first_row = counter; counter += nrows_per_chunk;
  9152. if (first_row >= nrows) {
  9153. if (local_size > 0) {
  9154. for (int j=0; j<int(local_hist.size()); ++j) {
  9155. hist_cur[j] += local_hist[j];
  9156. }
  9157. new_size += local_size;
  9158. }
  9159. break;
  9160. }
  9161. lock.unlock();
  9162. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9163. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9164. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9165. }
  9166. };
  9167. for (int it = 0; it < nthread_use - 1; ++it) {
  9168. workers.emplace_back(compute);
  9169. }
  9170. compute();
  9171. for (auto & w : workers) { w.join(); }
  9172. workers.clear();
  9173. }
  9174. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9175. int64_t tot_count = 0;
  9176. for (size_t i = 0; i < hist_cur.size(); i++) {
  9177. hist_all[i] += hist_cur[i];
  9178. tot_count += hist_cur[i];
  9179. }
  9180. if (tot_count > 0) {
  9181. LLAMA_LOG_INFO(" | hist: ");
  9182. for (size_t i = 0; i < hist_cur.size(); i++) {
  9183. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9184. }
  9185. }
  9186. LLAMA_LOG_INFO("\n");
  9187. }
  9188. total_size_org += ggml_nbytes(tensor);
  9189. total_size_new += new_size;
  9190. // update the gguf meta data as we go
  9191. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9192. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9193. // write tensor data + padding
  9194. fout.write((const char *) new_data, new_size);
  9195. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9196. }
  9197. // go back to beginning of file and write the updated meta data
  9198. {
  9199. fout.seekp(0);
  9200. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9201. gguf_get_meta_data(ctx_out, data.data());
  9202. fout.write((const char *) data.data(), data.size());
  9203. }
  9204. fout.close();
  9205. gguf_free(ctx_out);
  9206. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9207. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9208. // print histogram for all tensors
  9209. {
  9210. int64_t sum_all = 0;
  9211. for (size_t i = 0; i < hist_all.size(); i++) {
  9212. sum_all += hist_all[i];
  9213. }
  9214. if (sum_all > 0) {
  9215. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9216. for (size_t i = 0; i < hist_all.size(); i++) {
  9217. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9218. }
  9219. LLAMA_LOG_INFO("\n");
  9220. }
  9221. }
  9222. if (qs.n_fallback > 0) {
  9223. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9224. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9225. }
  9226. }
  9227. static int llama_apply_lora_from_file_internal(
  9228. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9229. ) {
  9230. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9231. const int64_t t_start_lora_us = ggml_time_us();
  9232. llama_file fin(path_lora, "rb");
  9233. // verify magic and version
  9234. {
  9235. uint32_t magic = fin.read_u32();
  9236. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9237. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9238. return 1;
  9239. }
  9240. uint32_t format_version = fin.read_u32();
  9241. if (format_version != 1) {
  9242. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9243. return 1;
  9244. }
  9245. }
  9246. int32_t lora_r = fin.read_u32();
  9247. int32_t lora_alpha = fin.read_u32();
  9248. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9249. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9250. // load base model
  9251. std::unique_ptr<llama_model_loader> ml;
  9252. if (path_base_model) {
  9253. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9254. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9255. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9256. }
  9257. struct tensor_meta {
  9258. std::string name;
  9259. ggml_type type;
  9260. int32_t ne[2];
  9261. size_t offset;
  9262. };
  9263. std::map<std::string, tensor_meta> tensor_meta_map;
  9264. // load all tensor meta
  9265. while (true) {
  9266. if (fin.tell() == fin.size) {
  9267. // eof
  9268. break;
  9269. }
  9270. int32_t n_dims;
  9271. int32_t name_len;
  9272. int32_t ftype;
  9273. fin.read_raw(&n_dims, sizeof(n_dims));
  9274. fin.read_raw(&name_len, sizeof(name_len));
  9275. fin.read_raw(&ftype, sizeof(ftype));
  9276. if (n_dims != 1 && n_dims != 2) {
  9277. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9278. return 1;
  9279. }
  9280. int32_t ne[2] = { 1, 1 };
  9281. for (int i = 0; i < n_dims; ++i) {
  9282. fin.read_raw(&ne[i], sizeof(ne[i]));
  9283. }
  9284. std::string name;
  9285. {
  9286. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9287. char buf[GGML_MAX_NAME];
  9288. fin.read_raw(buf, name_len);
  9289. name = std::string(buf, name_len);
  9290. }
  9291. // check for lora suffix
  9292. std::string lora_suffix;
  9293. if (name.length() > 6) {
  9294. lora_suffix = name.substr(name.length() - 6);
  9295. }
  9296. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9297. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9298. return 1;
  9299. }
  9300. // tensor type
  9301. ggml_type wtype;
  9302. switch (ftype) {
  9303. case 0: wtype = GGML_TYPE_F32; break;
  9304. case 1: wtype = GGML_TYPE_F16; break;
  9305. default:
  9306. {
  9307. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9308. __func__, ftype);
  9309. return 1;
  9310. }
  9311. }
  9312. // data offset
  9313. size_t offset = fin.tell();
  9314. offset = (offset + 31) & -32;
  9315. // skip tensor data
  9316. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9317. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9318. }
  9319. bool warned = false;
  9320. int n_tensors = 0;
  9321. // apply
  9322. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9323. if (backend_cpu == nullptr) {
  9324. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9325. return 1;
  9326. }
  9327. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9328. std::vector<no_init<uint8_t>> read_buf;
  9329. for (const auto & it : model.tensors_by_name) {
  9330. const std::string & base_name = it.first;
  9331. ggml_tensor * model_t = it.second;
  9332. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9333. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9334. continue;
  9335. }
  9336. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9337. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9338. ggml_init_params lora_init_params = {
  9339. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9340. /* .mem_buffer */ nullptr,
  9341. /* .no_alloc */ true,
  9342. };
  9343. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9344. if (lora_ctx == nullptr) {
  9345. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9346. ggml_backend_free(backend_cpu);
  9347. return 1;
  9348. }
  9349. // create tensors
  9350. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9351. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9352. ggml_set_name(loraA, metaA.name.c_str());
  9353. ggml_set_name(loraB, metaB.name.c_str());
  9354. ggml_tensor * base_t;
  9355. if (ml) {
  9356. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9357. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9358. return 1;
  9359. }
  9360. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9361. } else {
  9362. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9363. }
  9364. ggml_set_name(base_t, base_name.c_str());
  9365. // allocate in backend buffer
  9366. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9367. if (lora_buf == nullptr) {
  9368. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9369. return 1;
  9370. }
  9371. // load tensor data
  9372. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9373. read_buf.resize(ggml_nbytes(tensor));
  9374. fin.seek(tensor_meta.offset, SEEK_SET);
  9375. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9376. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9377. };
  9378. load_tensor(metaA, loraA);
  9379. load_tensor(metaB, loraB);
  9380. // load base model tensor data
  9381. if (ml) {
  9382. ml->load_data_for(base_t);
  9383. } else {
  9384. ggml_backend_tensor_copy(model_t, base_t);
  9385. }
  9386. if (ggml_is_quantized(base_t->type) && !warned) {
  9387. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9388. "use a f16 or f32 base model with --lora-base\n", __func__);
  9389. warned = true;
  9390. }
  9391. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9392. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9393. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9394. ggml_free(lora_ctx);
  9395. ggml_backend_buffer_free(lora_buf);
  9396. ggml_backend_free(backend_cpu);
  9397. return 1;
  9398. }
  9399. auto build_lora_graph = [&]() {
  9400. // w = w + BA*s
  9401. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9402. ggml_set_name(BA, "BA");
  9403. if (scaling != 1.0f) {
  9404. BA = ggml_scale(lora_ctx, BA, scaling);
  9405. ggml_set_name(BA, "BA_scaled");
  9406. }
  9407. ggml_tensor * r;
  9408. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9409. ggml_set_name(r, "r_add");
  9410. if (base_t->type != model_t->type) {
  9411. // convert the result to the model type
  9412. r = ggml_cast(lora_ctx, r, model_t->type);
  9413. ggml_set_name(r, "r_cast");
  9414. }
  9415. return r;
  9416. };
  9417. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9418. ggml_tensor * r = build_lora_graph();
  9419. ggml_build_forward_expand(gf, r);
  9420. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9421. if (graph_buf == nullptr) {
  9422. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9423. ggml_free(lora_ctx);
  9424. ggml_backend_buffer_free(lora_buf);
  9425. ggml_backend_free(backend_cpu);
  9426. return 1;
  9427. }
  9428. ggml_backend_graph_compute(backend_cpu, gf);
  9429. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9430. #if 0
  9431. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9432. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9433. // sched compute
  9434. ggml_build_forward_expand(gf, build_graph());
  9435. ggml_backend_sched_init_measure(sched, gf);
  9436. // create the graph again, since the previous one was destroyed by the measure
  9437. ggml_graph_clear(gf);
  9438. ggml_build_forward_expand(gf, build_graph());
  9439. ggml_backend_sched_graph_compute(sched, gf);
  9440. ggml_backend_sched_free(sched);
  9441. #endif
  9442. ggml_backend_buffer_free(lora_buf);
  9443. ggml_backend_buffer_free(graph_buf);
  9444. ggml_free(lora_ctx);
  9445. n_tensors++;
  9446. if (n_tensors % 4 == 0) {
  9447. LLAMA_LOG_INFO(".");
  9448. }
  9449. }
  9450. ggml_backend_free(backend_cpu);
  9451. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9452. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9453. return 0;
  9454. }
  9455. //
  9456. // interface implementation
  9457. //
  9458. struct llama_model_params llama_model_default_params() {
  9459. struct llama_model_params result = {
  9460. /*.n_gpu_layers =*/ 0,
  9461. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  9462. /*.main_gpu =*/ 0,
  9463. /*.tensor_split =*/ nullptr,
  9464. /*.progress_callback =*/ nullptr,
  9465. /*.progress_callback_user_data =*/ nullptr,
  9466. /*.kv_overrides =*/ nullptr,
  9467. /*.vocab_only =*/ false,
  9468. /*.use_mmap =*/ true,
  9469. /*.use_mlock =*/ false,
  9470. };
  9471. #ifdef GGML_USE_METAL
  9472. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9473. result.n_gpu_layers = 999;
  9474. #endif
  9475. return result;
  9476. }
  9477. struct llama_context_params llama_context_default_params() {
  9478. struct llama_context_params result = {
  9479. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9480. /*.n_ctx =*/ 512,
  9481. /*.n_batch =*/ 512,
  9482. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9483. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9484. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  9485. /*.rope_freq_base =*/ 0.0f,
  9486. /*.rope_freq_scale =*/ 0.0f,
  9487. /*.yarn_ext_factor =*/ -1.0f,
  9488. /*.yarn_attn_factor =*/ 1.0f,
  9489. /*.yarn_beta_fast =*/ 32.0f,
  9490. /*.yarn_beta_slow =*/ 1.0f,
  9491. /*.yarn_orig_ctx =*/ 0,
  9492. /*.cb_eval =*/ nullptr,
  9493. /*.cb_eval_user_data =*/ nullptr,
  9494. /*.type_k =*/ GGML_TYPE_F16,
  9495. /*.type_v =*/ GGML_TYPE_F16,
  9496. /*.mul_mat_q =*/ true,
  9497. /*.logits_all =*/ false,
  9498. /*.embedding =*/ false,
  9499. /*.offload_kqv =*/ true,
  9500. /*.do_pooling =*/ true,
  9501. };
  9502. return result;
  9503. }
  9504. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9505. struct llama_model_quantize_params result = {
  9506. /*.nthread =*/ 0,
  9507. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9508. /*.allow_requantize =*/ false,
  9509. /*.quantize_output_tensor =*/ true,
  9510. /*.only_copy =*/ false,
  9511. /*.pure =*/ false,
  9512. /*.imatrix =*/ nullptr,
  9513. };
  9514. return result;
  9515. }
  9516. size_t llama_max_devices(void) {
  9517. #if defined(GGML_USE_METAL)
  9518. return 1;
  9519. #elif defined(GGML_USE_CUBLAS)
  9520. return GGML_CUDA_MAX_DEVICES;
  9521. #elif defined(GGML_USE_SYCL)
  9522. return GGML_SYCL_MAX_DEVICES;
  9523. #elif defined(GGML_USE_VULKAN)
  9524. return GGML_VK_MAX_DEVICES;
  9525. #else
  9526. return 1;
  9527. #endif
  9528. }
  9529. bool llama_supports_mmap(void) {
  9530. return llama_mmap::SUPPORTED;
  9531. }
  9532. bool llama_supports_mlock(void) {
  9533. return llama_mlock::SUPPORTED;
  9534. }
  9535. bool llama_supports_gpu_offload(void) {
  9536. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  9537. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  9538. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  9539. return true;
  9540. #else
  9541. return false;
  9542. #endif
  9543. }
  9544. // deprecated:
  9545. bool llama_mmap_supported(void) {
  9546. return llama_supports_mmap();
  9547. }
  9548. bool llama_mlock_supported(void) {
  9549. return llama_supports_mlock();
  9550. }
  9551. void llama_backend_init(void) {
  9552. ggml_time_init();
  9553. // needed to initialize f16 tables
  9554. {
  9555. struct ggml_init_params params = { 0, NULL, false };
  9556. struct ggml_context * ctx = ggml_init(params);
  9557. ggml_free(ctx);
  9558. }
  9559. #ifdef GGML_USE_MPI
  9560. ggml_mpi_backend_init();
  9561. #endif
  9562. }
  9563. void llama_numa_init(enum ggml_numa_strategy numa) {
  9564. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  9565. ggml_numa_init(numa);
  9566. }
  9567. }
  9568. void llama_backend_free(void) {
  9569. #ifdef GGML_USE_MPI
  9570. ggml_mpi_backend_free();
  9571. #endif
  9572. ggml_quantize_free();
  9573. }
  9574. int64_t llama_time_us(void) {
  9575. return ggml_time_us();
  9576. }
  9577. struct llama_model * llama_load_model_from_file(
  9578. const char * path_model,
  9579. struct llama_model_params params) {
  9580. ggml_time_init();
  9581. llama_model * model = new llama_model;
  9582. unsigned cur_percentage = 0;
  9583. if (params.progress_callback == NULL) {
  9584. params.progress_callback_user_data = &cur_percentage;
  9585. params.progress_callback = [](float progress, void * ctx) {
  9586. unsigned * cur_percentage_p = (unsigned *) ctx;
  9587. unsigned percentage = (unsigned) (100 * progress);
  9588. while (percentage > *cur_percentage_p) {
  9589. *cur_percentage_p = percentage;
  9590. LLAMA_LOG_INFO(".");
  9591. if (percentage >= 100) {
  9592. LLAMA_LOG_INFO("\n");
  9593. }
  9594. }
  9595. return true;
  9596. };
  9597. }
  9598. int status = llama_model_load(path_model, *model, params);
  9599. GGML_ASSERT(status <= 0);
  9600. if (status < 0) {
  9601. if (status == -1) {
  9602. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  9603. } else if (status == -2) {
  9604. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  9605. }
  9606. delete model;
  9607. return nullptr;
  9608. }
  9609. return model;
  9610. }
  9611. void llama_free_model(struct llama_model * model) {
  9612. delete model;
  9613. }
  9614. struct llama_context * llama_new_context_with_model(
  9615. struct llama_model * model,
  9616. struct llama_context_params params) {
  9617. if (!model) {
  9618. return nullptr;
  9619. }
  9620. llama_context * ctx = new llama_context(*model);
  9621. const auto & hparams = model->hparams;
  9622. auto & cparams = ctx->cparams;
  9623. cparams.n_batch = params.n_batch;
  9624. cparams.n_threads = params.n_threads;
  9625. cparams.n_threads_batch = params.n_threads_batch;
  9626. cparams.yarn_ext_factor = params.yarn_ext_factor;
  9627. cparams.yarn_attn_factor = params.yarn_attn_factor;
  9628. cparams.yarn_beta_fast = params.yarn_beta_fast;
  9629. cparams.yarn_beta_slow = params.yarn_beta_slow;
  9630. cparams.mul_mat_q = params.mul_mat_q;
  9631. cparams.offload_kqv = params.offload_kqv;
  9632. cparams.do_pooling = params.do_pooling;
  9633. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  9634. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  9635. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  9636. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  9637. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  9638. hparams.n_ctx_train;
  9639. cparams.cb_eval = params.cb_eval;
  9640. cparams.cb_eval_user_data = params.cb_eval_user_data;
  9641. auto rope_scaling_type = params.rope_scaling_type;
  9642. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  9643. rope_scaling_type = hparams.rope_scaling_type_train;
  9644. }
  9645. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  9646. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  9647. }
  9648. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  9649. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  9650. }
  9651. if (params.seed == LLAMA_DEFAULT_SEED) {
  9652. params.seed = time(NULL);
  9653. }
  9654. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  9655. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  9656. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  9657. ctx->rng = std::mt19937(params.seed);
  9658. ctx->logits_all = params.logits_all;
  9659. const ggml_type type_k = params.type_k;
  9660. const ggml_type type_v = params.type_v;
  9661. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  9662. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  9663. if (!hparams.vocab_only) {
  9664. // initialize backends
  9665. #ifdef GGML_USE_METAL
  9666. if (model->n_gpu_layers > 0) {
  9667. ctx->backend_metal = ggml_backend_metal_init();
  9668. if (ctx->backend_metal == nullptr) {
  9669. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  9670. llama_free(ctx);
  9671. return nullptr;
  9672. }
  9673. ctx->backends.push_back(ctx->backend_metal);
  9674. }
  9675. #elif defined(GGML_USE_CUBLAS)
  9676. if (model->n_gpu_layers > 0) {
  9677. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  9678. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  9679. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  9680. if (backend == nullptr) {
  9681. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  9682. llama_free(ctx);
  9683. return nullptr;
  9684. }
  9685. ctx->backends.push_back(backend);
  9686. } else {
  9687. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  9688. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  9689. ggml_backend_t backend = ggml_backend_cuda_init(device);
  9690. if (backend == nullptr) {
  9691. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  9692. llama_free(ctx);
  9693. return nullptr;
  9694. }
  9695. ctx->backends.push_back(backend);
  9696. }
  9697. }
  9698. }
  9699. #elif defined(GGML_USE_VULKAN)
  9700. if (model->n_gpu_layers > 0) {
  9701. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  9702. ggml_backend_t backend = ggml_backend_vk_init(device);
  9703. if (backend == nullptr) {
  9704. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  9705. llama_free(ctx);
  9706. return nullptr;
  9707. }
  9708. ctx->backends.push_back(backend);
  9709. }
  9710. }
  9711. #elif defined(GGML_USE_SYCL)
  9712. if (model->n_gpu_layers > 0) {
  9713. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  9714. if (backend == nullptr) {
  9715. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  9716. llama_free(ctx);
  9717. return nullptr;
  9718. }
  9719. ctx->backends.push_back(backend);
  9720. }
  9721. #elif defined(GGML_USE_KOMPUTE)
  9722. if (model->n_gpu_layers > 0) {
  9723. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  9724. if (backend == nullptr) {
  9725. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  9726. llama_free(ctx);
  9727. return nullptr;
  9728. }
  9729. ctx->backends.push_back(backend);
  9730. }
  9731. #endif
  9732. ctx->backend_cpu = ggml_backend_cpu_init();
  9733. if (ctx->backend_cpu == nullptr) {
  9734. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  9735. llama_free(ctx);
  9736. return nullptr;
  9737. }
  9738. ctx->backends.push_back(ctx->backend_cpu);
  9739. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  9740. cparams.n_ctx, cparams.offload_kqv)) {
  9741. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  9742. llama_free(ctx);
  9743. return nullptr;
  9744. }
  9745. {
  9746. size_t memory_size_k = 0;
  9747. size_t memory_size_v = 0;
  9748. for (auto & k : ctx->kv_self.k_l) {
  9749. memory_size_k += ggml_nbytes(k);
  9750. }
  9751. for (auto & v : ctx->kv_self.v_l) {
  9752. memory_size_v += ggml_nbytes(v);
  9753. }
  9754. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  9755. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  9756. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  9757. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  9758. }
  9759. // resized during inference, reserve maximum
  9760. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  9761. if (params.embedding) {
  9762. ctx->embedding.resize(hparams.n_embd);
  9763. }
  9764. // graph inputs
  9765. {
  9766. ggml_init_params init_params = {
  9767. /* .mem_size */ ggml_tensor_overhead()*8,
  9768. /* .mem_buffer */ nullptr,
  9769. /* .no_alloc */ true,
  9770. };
  9771. ctx->ctx_input = ggml_init(init_params);
  9772. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9773. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  9774. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9775. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  9776. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  9777. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  9778. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  9779. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9780. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  9781. ggml_set_name(ctx->inp_embd, "inp_embd");
  9782. ggml_set_name(ctx->inp_pos, "inp_pos");
  9783. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  9784. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  9785. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  9786. ggml_set_name(ctx->inp_mean, "inp_mean");
  9787. ggml_set_name(ctx->inp_cls, "inp_cls");
  9788. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  9789. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  9790. ggml_backend_buffer_name(ctx->buf_input),
  9791. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  9792. }
  9793. // scheduler and compute buffers
  9794. {
  9795. // buffer types used for the compute buffer of each backend
  9796. std::vector<ggml_backend_buffer_type_t> backend_buft;
  9797. for (auto * backend : ctx->backends) {
  9798. if (ggml_backend_is_cpu(backend)) {
  9799. // use host buffers for the CPU backend compute buffer
  9800. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  9801. } else {
  9802. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  9803. }
  9804. }
  9805. // buffer used to store the computation graph and the tensor meta data
  9806. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  9807. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  9808. // build worst-case graph
  9809. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  9810. int n_past = cparams.n_ctx - n_tokens;
  9811. 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
  9812. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  9813. // initialize scheduler with the worst-case graph
  9814. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  9815. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  9816. llama_free(ctx);
  9817. return nullptr;
  9818. }
  9819. for (size_t i = 0; i < ctx->backends.size(); i++) {
  9820. ggml_backend_t backend = ctx->backends[i];
  9821. ggml_backend_buffer_type_t buft = backend_buft[i];
  9822. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  9823. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  9824. ggml_backend_buft_name(buft),
  9825. size / 1024.0 / 1024.0);
  9826. }
  9827. // note: the number of splits during measure is higher than during inference due to the kv shift
  9828. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  9829. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  9830. }
  9831. }
  9832. #ifdef GGML_USE_MPI
  9833. ctx->ctx_mpi = ggml_mpi_init();
  9834. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  9835. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  9836. // TODO: needs fix after #3228
  9837. GGML_ASSERT(false && "not implemented");
  9838. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  9839. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  9840. llama_backend_free();
  9841. exit(1);
  9842. }
  9843. #endif
  9844. return ctx;
  9845. }
  9846. void llama_free(struct llama_context * ctx) {
  9847. delete ctx;
  9848. }
  9849. const llama_model * llama_get_model(const struct llama_context * ctx) {
  9850. return &ctx->model;
  9851. }
  9852. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  9853. return ctx->cparams.n_ctx;
  9854. }
  9855. uint32_t llama_n_batch(const struct llama_context * ctx) {
  9856. return ctx->cparams.n_batch;
  9857. }
  9858. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  9859. return model->vocab.type;
  9860. }
  9861. int32_t llama_n_vocab(const struct llama_model * model) {
  9862. return model->vocab.id_to_token.size();
  9863. }
  9864. int32_t llama_n_ctx_train(const struct llama_model * model) {
  9865. return model->hparams.n_ctx_train;
  9866. }
  9867. int32_t llama_n_embd(const struct llama_model * model) {
  9868. return model->hparams.n_embd;
  9869. }
  9870. float llama_rope_freq_scale_train(const struct llama_model * model) {
  9871. return model->hparams.rope_freq_scale_train;
  9872. }
  9873. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  9874. const auto & it = model->gguf_kv.find(key);
  9875. if (it == model->gguf_kv.end()) {
  9876. if (buf_size > 0) {
  9877. buf[0] = '\0';
  9878. }
  9879. return -1;
  9880. }
  9881. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9882. }
  9883. int32_t llama_model_meta_count(const struct llama_model * model) {
  9884. return (int)model->gguf_kv.size();
  9885. }
  9886. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  9887. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9888. if (buf_size > 0) {
  9889. buf[0] = '\0';
  9890. }
  9891. return -1;
  9892. }
  9893. auto it = model->gguf_kv.begin();
  9894. std::advance(it, i);
  9895. return snprintf(buf, buf_size, "%s", it->first.c_str());
  9896. }
  9897. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  9898. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9899. if (buf_size > 0) {
  9900. buf[0] = '\0';
  9901. }
  9902. return -1;
  9903. }
  9904. auto it = model->gguf_kv.begin();
  9905. std::advance(it, i);
  9906. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9907. }
  9908. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  9909. return snprintf(buf, buf_size, "%s %s %s",
  9910. llama_model_arch_name(model->arch),
  9911. llama_model_type_name(model->type),
  9912. llama_model_ftype_name(model->ftype).c_str());
  9913. }
  9914. uint64_t llama_model_size(const struct llama_model * model) {
  9915. uint64_t size = 0;
  9916. for (const auto & it : model->tensors_by_name) {
  9917. size += ggml_nbytes(it.second);
  9918. }
  9919. return size;
  9920. }
  9921. uint64_t llama_model_n_params(const struct llama_model * model) {
  9922. uint64_t nparams = 0;
  9923. for (const auto & it : model->tensors_by_name) {
  9924. nparams += ggml_nelements(it.second);
  9925. }
  9926. return nparams;
  9927. }
  9928. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  9929. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  9930. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  9931. return it.first == name;
  9932. });
  9933. if (it == model->tensors_by_name.end()) {
  9934. return nullptr;
  9935. }
  9936. return it->second;
  9937. }
  9938. uint32_t llama_model_quantize(
  9939. const char * fname_inp,
  9940. const char * fname_out,
  9941. const llama_model_quantize_params * params) {
  9942. try {
  9943. llama_model_quantize_internal(fname_inp, fname_out, params);
  9944. return 0;
  9945. } catch (const std::exception & err) {
  9946. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  9947. return 1;
  9948. }
  9949. }
  9950. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  9951. try {
  9952. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  9953. } catch (const std::exception & err) {
  9954. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9955. return 1;
  9956. }
  9957. }
  9958. 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) {
  9959. try {
  9960. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  9961. } catch (const std::exception & err) {
  9962. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9963. return 1;
  9964. }
  9965. }
  9966. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  9967. struct llama_kv_cache_view result = {
  9968. /*.n_cells = */ 0,
  9969. /*.n_max_seq = */ n_max_seq,
  9970. /*.token_count = */ 0,
  9971. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  9972. /*.max_contiguous = */ 0,
  9973. /*.max_contiguous_idx = */ -1,
  9974. /*.cells = */ nullptr,
  9975. /*.cells_sequences = */ nullptr,
  9976. };
  9977. return result;
  9978. }
  9979. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  9980. if (view->cells != nullptr) {
  9981. free(view->cells);
  9982. view->cells = nullptr;
  9983. }
  9984. if (view->cells_sequences != nullptr) {
  9985. free(view->cells_sequences);
  9986. view->cells_sequences = nullptr;
  9987. }
  9988. }
  9989. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  9990. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  9991. view->n_cells = int32_t(ctx->kv_self.size);
  9992. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  9993. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  9994. view->cells = (struct llama_kv_cache_view_cell *)p;
  9995. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  9996. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  9997. view->cells_sequences = (llama_seq_id *)p;
  9998. }
  9999. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  10000. llama_kv_cache_view_cell * c_curr = view->cells;
  10001. llama_seq_id * cs_curr = view->cells_sequences;
  10002. int32_t used_cells = 0;
  10003. int32_t token_count = 0;
  10004. int32_t curr_contig_idx = -1;
  10005. uint32_t max_contig = 0;
  10006. int32_t max_contig_idx = -1;
  10007. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10008. const size_t curr_size = kv_cells[i].seq_id.size();
  10009. token_count += curr_size;
  10010. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10011. if (curr_size > 0) {
  10012. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10013. max_contig = i - curr_contig_idx;
  10014. max_contig_idx = curr_contig_idx;
  10015. }
  10016. curr_contig_idx = -1;
  10017. } else if (curr_contig_idx < 0) {
  10018. curr_contig_idx = i;
  10019. }
  10020. int seq_idx = 0;
  10021. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10022. if (seq_idx >= view->n_max_seq) {
  10023. break;
  10024. }
  10025. cs_curr[seq_idx] = it;
  10026. seq_idx++;
  10027. }
  10028. if (seq_idx != 0) {
  10029. used_cells++;
  10030. }
  10031. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10032. cs_curr[seq_idx] = -1;
  10033. }
  10034. }
  10035. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10036. max_contig_idx = curr_contig_idx;
  10037. max_contig = kv_cells.size() - curr_contig_idx;
  10038. }
  10039. view->max_contiguous = max_contig;
  10040. view->max_contiguous_idx = max_contig_idx;
  10041. view->token_count = token_count;
  10042. view->used_cells = used_cells;
  10043. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10044. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10045. __func__, ctx->kv_self.used, used_cells);
  10046. }
  10047. }
  10048. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10049. int result = 0;
  10050. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10051. result += ctx->kv_self.cells[i].seq_id.size();
  10052. }
  10053. return result;
  10054. }
  10055. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10056. return ctx->kv_self.used;
  10057. }
  10058. void llama_kv_cache_clear(struct llama_context * ctx) {
  10059. llama_kv_cache_clear(ctx->kv_self);
  10060. }
  10061. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10062. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10063. }
  10064. 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) {
  10065. if (seq_id_src == seq_id_dst) {
  10066. return;
  10067. }
  10068. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10069. }
  10070. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10071. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10072. }
  10073. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10074. if (delta == 0) {
  10075. return;
  10076. }
  10077. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  10078. }
  10079. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10080. if (d == 1) {
  10081. return;
  10082. }
  10083. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10084. }
  10085. // Returns the *maximum* size of the state
  10086. size_t llama_get_state_size(const struct llama_context * ctx) {
  10087. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10088. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10089. const size_t s_rng_size = sizeof(size_t);
  10090. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10091. const size_t s_logits_size = sizeof(size_t);
  10092. // assume worst case for logits although only currently set ones are serialized
  10093. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10094. const size_t s_embedding_size = sizeof(size_t);
  10095. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  10096. const size_t s_kv_size = sizeof(size_t);
  10097. const size_t s_kv_ntok = sizeof(int);
  10098. const size_t s_kv = ctx->kv_self.total_size();
  10099. const size_t s_total = (
  10100. + s_rng_size
  10101. + s_rng
  10102. + s_logits_size
  10103. + s_logits
  10104. + s_embedding_size
  10105. + s_embedding
  10106. + s_kv_size
  10107. + s_kv_ntok
  10108. + s_kv
  10109. );
  10110. return s_total;
  10111. }
  10112. // llama_context_data
  10113. struct llama_data_context {
  10114. virtual void write(const void * src, size_t size) = 0;
  10115. virtual size_t get_size_written() = 0;
  10116. virtual ~llama_data_context() = default;
  10117. };
  10118. struct llama_data_buffer_context : llama_data_context {
  10119. uint8_t * ptr;
  10120. size_t size_written = 0;
  10121. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10122. void write(const void * src, size_t size) override {
  10123. memcpy(ptr, src, size);
  10124. ptr += size;
  10125. size_written += size;
  10126. }
  10127. size_t get_size_written() override {
  10128. return size_written;
  10129. }
  10130. };
  10131. struct llama_data_file_context : llama_data_context {
  10132. llama_file * file;
  10133. size_t size_written = 0;
  10134. llama_data_file_context(llama_file * f) : file(f) {}
  10135. void write(const void * src, size_t size) override {
  10136. file->write_raw(src, size);
  10137. size_written += size;
  10138. }
  10139. size_t get_size_written() override {
  10140. return size_written;
  10141. }
  10142. };
  10143. /** copy state data into either a buffer or file depending on the passed in context
  10144. *
  10145. * file context:
  10146. * llama_file file("/path", "wb");
  10147. * llama_data_file_context data_ctx(&file);
  10148. * llama_copy_state_data(ctx, &data_ctx);
  10149. *
  10150. * buffer context:
  10151. * std::vector<uint8_t> buf(max_size, 0);
  10152. * llama_data_buffer_context data_ctx(&buf.data());
  10153. * llama_copy_state_data(ctx, &data_ctx);
  10154. *
  10155. */
  10156. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10157. // copy rng
  10158. {
  10159. std::ostringstream rng_ss;
  10160. rng_ss << ctx->rng;
  10161. const std::string & rng_str = rng_ss.str();
  10162. const size_t rng_size = rng_str.size();
  10163. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10164. data_ctx->write(&rng_size, sizeof(rng_size));
  10165. data_ctx->write(rng_str.data(), rng_size);
  10166. }
  10167. // copy logits
  10168. {
  10169. const size_t logits_size = ctx->logits.size();
  10170. data_ctx->write(&logits_size, sizeof(logits_size));
  10171. if (logits_size) {
  10172. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10173. }
  10174. }
  10175. // copy embeddings
  10176. {
  10177. const size_t embedding_size = ctx->embedding.size();
  10178. data_ctx->write(&embedding_size, sizeof(embedding_size));
  10179. if (embedding_size) {
  10180. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  10181. }
  10182. }
  10183. // copy kv cache
  10184. {
  10185. const auto & kv_self = ctx->kv_self;
  10186. const auto & hparams = ctx->model.hparams;
  10187. const auto & cparams = ctx->cparams;
  10188. const auto n_layer = hparams.n_layer;
  10189. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  10190. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  10191. const auto n_ctx = cparams.n_ctx;
  10192. const size_t kv_buf_size = kv_self.total_size();
  10193. const uint32_t kv_head = kv_self.head;
  10194. const uint32_t kv_size = kv_self.size;
  10195. const uint32_t kv_used = kv_self.used;
  10196. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10197. data_ctx->write(&kv_head, sizeof(kv_head));
  10198. data_ctx->write(&kv_size, sizeof(kv_size));
  10199. data_ctx->write(&kv_used, sizeof(kv_used));
  10200. if (kv_buf_size) {
  10201. std::vector<uint8_t> tmp_buf;
  10202. for (int il = 0; il < (int) n_layer; ++il) {
  10203. size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10204. tmp_buf.resize(k_size);
  10205. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10206. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10207. // v is not contiguous, copy row by row
  10208. size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10209. size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10210. tmp_buf.resize(v_row_size);
  10211. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10212. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10213. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10214. }
  10215. }
  10216. }
  10217. for (uint32_t i = 0; i < kv_size; ++i) {
  10218. const auto & cell = kv_self.cells[i];
  10219. const llama_pos pos = cell.pos;
  10220. const size_t seq_id_size = cell.seq_id.size();
  10221. data_ctx->write(&pos, sizeof(pos));
  10222. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10223. for (auto seq_id : cell.seq_id) {
  10224. data_ctx->write(&seq_id, sizeof(seq_id));
  10225. }
  10226. }
  10227. }
  10228. }
  10229. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10230. llama_data_buffer_context data_ctx(dst);
  10231. llama_copy_state_data_internal(ctx, &data_ctx);
  10232. return data_ctx.get_size_written();
  10233. }
  10234. // Sets the state reading from the specified source address
  10235. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  10236. uint8_t * inp = src;
  10237. // set rng
  10238. {
  10239. size_t rng_size;
  10240. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10241. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10242. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  10243. std::istringstream rng_ss(rng_str);
  10244. rng_ss >> ctx->rng;
  10245. GGML_ASSERT(!rng_ss.fail());
  10246. }
  10247. // set logits
  10248. {
  10249. size_t logits_size;
  10250. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10251. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10252. if (logits_size) {
  10253. ctx->logits.resize(logits_size);
  10254. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10255. inp += logits_size * sizeof(float);
  10256. }
  10257. }
  10258. // set embeddings
  10259. {
  10260. size_t embedding_size;
  10261. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  10262. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  10263. if (embedding_size) {
  10264. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  10265. inp += embedding_size * sizeof(float);
  10266. }
  10267. }
  10268. // set kv cache
  10269. {
  10270. const auto & kv_self = ctx->kv_self;
  10271. const auto & hparams = ctx->model.hparams;
  10272. const auto & cparams = ctx->cparams;
  10273. const int n_layer = hparams.n_layer;
  10274. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  10275. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  10276. const int n_ctx = cparams.n_ctx;
  10277. size_t kv_buf_size;
  10278. uint32_t kv_head;
  10279. uint32_t kv_size;
  10280. uint32_t kv_used;
  10281. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10282. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10283. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10284. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10285. if (kv_buf_size) {
  10286. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10287. for (int il = 0; il < (int) n_layer; ++il) {
  10288. size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10289. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10290. inp += k_size;
  10291. // v is not contiguous, copy row by row
  10292. size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10293. size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10294. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10295. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10296. inp += v_row_size;
  10297. }
  10298. }
  10299. }
  10300. ctx->kv_self.head = kv_head;
  10301. ctx->kv_self.size = kv_size;
  10302. ctx->kv_self.used = kv_used;
  10303. ctx->kv_self.cells.resize(kv_size);
  10304. for (uint32_t i = 0; i < kv_size; ++i) {
  10305. llama_pos pos;
  10306. size_t seq_id_size;
  10307. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10308. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10309. ctx->kv_self.cells[i].pos = pos;
  10310. llama_seq_id seq_id;
  10311. for (size_t j = 0; j < seq_id_size; ++j) {
  10312. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10313. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10314. }
  10315. }
  10316. }
  10317. const size_t nread = inp - src;
  10318. const size_t max_size = llama_get_state_size(ctx);
  10319. GGML_ASSERT(nread <= max_size);
  10320. return nread;
  10321. }
  10322. 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) {
  10323. llama_file file(path_session, "rb");
  10324. // sanity checks
  10325. {
  10326. const uint32_t magic = file.read_u32();
  10327. const uint32_t version = file.read_u32();
  10328. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10329. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10330. return false;
  10331. }
  10332. llama_hparams session_hparams;
  10333. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10334. if (session_hparams != ctx->model.hparams) {
  10335. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10336. return false;
  10337. }
  10338. }
  10339. // load the prompt
  10340. {
  10341. const uint32_t n_token_count = file.read_u32();
  10342. if (n_token_count > n_token_capacity) {
  10343. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10344. return false;
  10345. }
  10346. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10347. *n_token_count_out = n_token_count;
  10348. }
  10349. // restore the context state
  10350. {
  10351. const size_t n_state_size_cur = file.size - file.tell();
  10352. const size_t n_state_size_max = llama_get_state_size(ctx);
  10353. if (n_state_size_cur > n_state_size_max) {
  10354. 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);
  10355. return false;
  10356. }
  10357. std::vector<uint8_t> state_data(n_state_size_max);
  10358. file.read_raw(state_data.data(), n_state_size_cur);
  10359. llama_set_state_data(ctx, state_data.data());
  10360. }
  10361. return true;
  10362. }
  10363. 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) {
  10364. try {
  10365. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10366. } catch (const std::exception & err) {
  10367. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10368. return false;
  10369. }
  10370. }
  10371. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10372. llama_file file(path_session, "wb");
  10373. file.write_u32(LLAMA_SESSION_MAGIC);
  10374. file.write_u32(LLAMA_SESSION_VERSION);
  10375. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10376. // save the prompt
  10377. file.write_u32((uint32_t) n_token_count);
  10378. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10379. // save the context state using stream saving
  10380. llama_data_file_context data_ctx(&file);
  10381. llama_copy_state_data_internal(ctx, &data_ctx);
  10382. return true;
  10383. }
  10384. int llama_eval(
  10385. struct llama_context * ctx,
  10386. llama_token * tokens,
  10387. int32_t n_tokens,
  10388. int32_t n_past) {
  10389. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10390. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  10391. if (ret < 0) {
  10392. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10393. }
  10394. return ret;
  10395. }
  10396. int llama_eval_embd(
  10397. struct llama_context * ctx,
  10398. float * embd,
  10399. int32_t n_tokens,
  10400. int32_t n_past) {
  10401. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10402. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  10403. const int ret = llama_decode_internal(*ctx, batch);
  10404. if (ret < 0) {
  10405. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10406. }
  10407. return ret;
  10408. }
  10409. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10410. ctx->cparams.n_threads = n_threads;
  10411. ctx->cparams.n_threads_batch = n_threads_batch;
  10412. }
  10413. struct llama_batch llama_batch_get_one(
  10414. llama_token * tokens,
  10415. int32_t n_tokens,
  10416. llama_pos pos_0,
  10417. llama_seq_id seq_id) {
  10418. return {
  10419. /*n_tokens =*/ n_tokens,
  10420. /*tokens =*/ tokens,
  10421. /*embd =*/ nullptr,
  10422. /*pos =*/ nullptr,
  10423. /*n_seq_id =*/ nullptr,
  10424. /*seq_id =*/ nullptr,
  10425. /*logits =*/ nullptr,
  10426. /*all_pos_0 =*/ pos_0,
  10427. /*all_pos_1 =*/ 1,
  10428. /*all_seq_id =*/ seq_id,
  10429. };
  10430. }
  10431. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10432. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10433. if (embd) {
  10434. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10435. } else {
  10436. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10437. }
  10438. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10439. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10440. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10441. for (int i = 0; i < n_tokens_alloc; ++i) {
  10442. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10443. }
  10444. batch.seq_id[n_tokens_alloc] = nullptr;
  10445. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10446. return batch;
  10447. }
  10448. void llama_batch_free(struct llama_batch batch) {
  10449. if (batch.token) free(batch.token);
  10450. if (batch.embd) free(batch.embd);
  10451. if (batch.pos) free(batch.pos);
  10452. if (batch.n_seq_id) free(batch.n_seq_id);
  10453. if (batch.seq_id) {
  10454. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10455. free(batch.seq_id[i]);
  10456. }
  10457. free(batch.seq_id);
  10458. }
  10459. if (batch.logits) free(batch.logits);
  10460. }
  10461. int32_t llama_decode(
  10462. struct llama_context * ctx,
  10463. struct llama_batch batch) {
  10464. const int ret = llama_decode_internal(*ctx, batch);
  10465. if (ret < 0) {
  10466. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10467. }
  10468. return ret;
  10469. }
  10470. float * llama_get_logits(struct llama_context * ctx) {
  10471. return ctx->logits.data();
  10472. }
  10473. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10474. assert(ctx->logits_valid.at(i));
  10475. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  10476. }
  10477. float * llama_get_embeddings(struct llama_context * ctx) {
  10478. return ctx->embedding.data();
  10479. }
  10480. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  10481. return ctx->embedding.data() + i*ctx->model.hparams.n_embd;
  10482. }
  10483. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  10484. return model->vocab.id_to_token[token].text.c_str();
  10485. }
  10486. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  10487. return model->vocab.id_to_token[token].score;
  10488. }
  10489. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  10490. return model->vocab.id_to_token[token].type;
  10491. }
  10492. llama_token llama_token_bos(const struct llama_model * model) {
  10493. return model->vocab.special_bos_id;
  10494. }
  10495. llama_token llama_token_eos(const struct llama_model * model) {
  10496. return model->vocab.special_eos_id;
  10497. }
  10498. llama_token llama_token_nl(const struct llama_model * model) {
  10499. return model->vocab.linefeed_id;
  10500. }
  10501. int32_t llama_add_bos_token(const struct llama_model * model) {
  10502. return model->vocab.special_add_bos;
  10503. }
  10504. int32_t llama_add_eos_token(const struct llama_model * model) {
  10505. return model->vocab.special_add_eos;
  10506. }
  10507. llama_token llama_token_prefix(const struct llama_model * model) {
  10508. return model->vocab.special_prefix_id;
  10509. }
  10510. llama_token llama_token_middle(const struct llama_model * model) {
  10511. return model->vocab.special_middle_id;
  10512. }
  10513. llama_token llama_token_suffix(const struct llama_model * model) {
  10514. return model->vocab.special_suffix_id;
  10515. }
  10516. llama_token llama_token_eot(const struct llama_model * model) {
  10517. return model->vocab.special_eot_id;
  10518. }
  10519. int32_t llama_tokenize(
  10520. const struct llama_model * model,
  10521. const char * text,
  10522. int32_t text_len,
  10523. llama_token * tokens,
  10524. int32_t n_max_tokens,
  10525. bool add_bos,
  10526. bool special) {
  10527. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  10528. if (n_max_tokens < (int) res.size()) {
  10529. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  10530. return -((int) res.size());
  10531. }
  10532. for (size_t i = 0; i < res.size(); i++) {
  10533. tokens[i] = res[i];
  10534. }
  10535. return res.size();
  10536. }
  10537. static std::string llama_decode_text(const std::string & text) {
  10538. std::string decoded_text;
  10539. auto unicode_sequences = codepoints_from_utf8(text);
  10540. for (auto& unicode_sequence : unicode_sequences) {
  10541. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  10542. }
  10543. return decoded_text;
  10544. }
  10545. // does not write null-terminator to buf
  10546. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  10547. if (0 <= token && token < llama_n_vocab(model)) {
  10548. switch (llama_vocab_get_type(model->vocab)) {
  10549. case LLAMA_VOCAB_TYPE_WPM:
  10550. case LLAMA_VOCAB_TYPE_SPM: {
  10551. // NOTE: we accept all unsupported token types,
  10552. // suppressing them like CONTROL tokens.
  10553. if (llama_is_normal_token(model->vocab, token)) {
  10554. std::string result = model->vocab.id_to_token[token].text;
  10555. llama_unescape_whitespace(result);
  10556. if (length < (int) result.length()) {
  10557. return -(int) result.length();
  10558. }
  10559. memcpy(buf, result.c_str(), result.length());
  10560. return result.length();
  10561. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10562. std::string result = model->vocab.id_to_token[token].text;
  10563. if (length < (int) result.length()) {
  10564. return -result.length();
  10565. }
  10566. memcpy(buf, result.c_str(), result.length());
  10567. return result.length();
  10568. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  10569. if (length < 3) {
  10570. return -3;
  10571. }
  10572. memcpy(buf, "\xe2\x96\x85", 3);
  10573. return 3;
  10574. } else if (llama_is_control_token(model->vocab, token)) {
  10575. ;
  10576. } else if (llama_is_byte_token(model->vocab, token)) {
  10577. if (length < 1) {
  10578. return -1;
  10579. }
  10580. buf[0] = llama_token_to_byte(model->vocab, token);
  10581. return 1;
  10582. }
  10583. break;
  10584. }
  10585. case LLAMA_VOCAB_TYPE_BPE: {
  10586. // NOTE: we accept all unsupported token types,
  10587. // suppressing them like CONTROL tokens.
  10588. if (llama_is_normal_token(model->vocab, token)) {
  10589. std::string result = model->vocab.id_to_token[token].text;
  10590. result = llama_decode_text(result);
  10591. if (length < (int) result.length()) {
  10592. return -(int) result.length();
  10593. }
  10594. memcpy(buf, result.c_str(), result.length());
  10595. return result.length();
  10596. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10597. std::string result = model->vocab.id_to_token[token].text;
  10598. if (length < (int) result.length()) {
  10599. return -result.length();
  10600. }
  10601. memcpy(buf, result.c_str(), result.length());
  10602. return result.length();
  10603. } else if (llama_is_control_token(model->vocab, token)) {
  10604. ;
  10605. }
  10606. break;
  10607. }
  10608. default:
  10609. GGML_ASSERT(false);
  10610. }
  10611. }
  10612. return 0;
  10613. }
  10614. // trim whitespace from the beginning and end of a string
  10615. static std::string trim(const std::string & str) {
  10616. size_t start = 0;
  10617. size_t end = str.size();
  10618. while (start < end && isspace(str[start])) {
  10619. start += 1;
  10620. }
  10621. while (end > start && isspace(str[end - 1])) {
  10622. end -= 1;
  10623. }
  10624. return str.substr(start, end - start);
  10625. }
  10626. // Simple version of "llama_apply_chat_template" that only works with strings
  10627. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  10628. static int32_t llama_chat_apply_template_internal(
  10629. const std::string & tmpl,
  10630. const std::vector<const llama_chat_message *> & chat,
  10631. std::string & dest, bool add_ass) {
  10632. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  10633. std::stringstream ss;
  10634. if (tmpl.find("<|im_start|>") != std::string::npos) {
  10635. // chatml template
  10636. for (auto message : chat) {
  10637. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  10638. }
  10639. if (add_ass) {
  10640. ss << "<|im_start|>assistant\n";
  10641. }
  10642. } else if (tmpl.find("[INST]") != std::string::npos) {
  10643. // llama2 template and its variants
  10644. // [variant] support system message
  10645. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  10646. // [variant] space before + after response
  10647. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  10648. // [variant] add BOS inside history
  10649. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  10650. // [variant] trim spaces from the input message
  10651. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  10652. // construct the prompt
  10653. bool is_inside_turn = true; // skip BOS at the beginning
  10654. ss << "[INST] ";
  10655. for (auto message : chat) {
  10656. std::string content = strip_message ? trim(message->content) : message->content;
  10657. std::string role(message->role);
  10658. if (!is_inside_turn) {
  10659. is_inside_turn = true;
  10660. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  10661. }
  10662. if (role == "system") {
  10663. if (support_system_message) {
  10664. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  10665. } else {
  10666. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  10667. ss << content << "\n";
  10668. }
  10669. } else if (role == "user") {
  10670. ss << content << " [/INST]";
  10671. } else {
  10672. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  10673. is_inside_turn = false;
  10674. }
  10675. }
  10676. // llama2 templates seem to not care about "add_generation_prompt"
  10677. } else if (tmpl.find("<|user|>") != std::string::npos) {
  10678. // zephyr template
  10679. for (auto message : chat) {
  10680. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  10681. }
  10682. if (add_ass) {
  10683. ss << "<|assistant|>\n";
  10684. }
  10685. } else if (tmpl.find("bos_token + message['role']") != std::string::npos) {
  10686. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  10687. for (auto message : chat) {
  10688. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  10689. ss << bos << message->role << "\n" << message->content << "</s>\n";
  10690. }
  10691. if (add_ass) {
  10692. ss << "<s>assistant\n";
  10693. }
  10694. } else if (tmpl.find("<start_of_turn>") != std::string::npos) {
  10695. // google/gemma-7b-it
  10696. std::string system_prompt = "";
  10697. for (auto message : chat) {
  10698. std::string role(message->role);
  10699. if (role == "system") {
  10700. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  10701. system_prompt = trim(message->content);
  10702. continue;
  10703. }
  10704. // in gemma, "assistant" is "model"
  10705. role = role == "assistant" ? "model" : message->role;
  10706. ss << "<start_of_turn>" << role << "\n";
  10707. if (!system_prompt.empty() && role != "model") {
  10708. ss << system_prompt << "\n\n";
  10709. system_prompt = "";
  10710. }
  10711. ss << trim(message->content) << "<end_of_turn>\n";
  10712. }
  10713. if (add_ass) {
  10714. ss << "<start_of_turn>model\n";
  10715. }
  10716. } else {
  10717. // template not supported
  10718. return -1;
  10719. }
  10720. dest = ss.str();
  10721. return dest.size();
  10722. }
  10723. LLAMA_API int32_t llama_chat_apply_template(
  10724. const struct llama_model * model,
  10725. const char * tmpl,
  10726. const struct llama_chat_message * chat,
  10727. size_t n_msg,
  10728. bool add_ass,
  10729. char * buf,
  10730. int32_t length) {
  10731. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  10732. if (tmpl == nullptr) {
  10733. GGML_ASSERT(model != nullptr);
  10734. // load template from model
  10735. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  10736. std::string template_key = "tokenizer.chat_template";
  10737. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  10738. if (res < 0) {
  10739. // worst case: there is no information about template, we will use chatml by default
  10740. curr_tmpl = "<|im_start|>"; // see llama_chat_apply_template_internal
  10741. } else {
  10742. curr_tmpl = std::string(model_template.data(), model_template.size());
  10743. }
  10744. }
  10745. // format the chat to string
  10746. std::vector<const llama_chat_message *> chat_vec;
  10747. chat_vec.resize(n_msg);
  10748. for (size_t i = 0; i < n_msg; i++) {
  10749. chat_vec[i] = &chat[i];
  10750. }
  10751. std::string formatted_chat;
  10752. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  10753. if (res < 0) {
  10754. return res;
  10755. }
  10756. strncpy(buf, formatted_chat.c_str(), length);
  10757. return res;
  10758. }
  10759. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  10760. struct llama_timings result = {
  10761. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  10762. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  10763. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  10764. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  10765. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  10766. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  10767. /*.n_sample =*/ std::max(1, ctx->n_sample),
  10768. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  10769. /*.n_eval =*/ std::max(1, ctx->n_eval),
  10770. };
  10771. return result;
  10772. }
  10773. void llama_print_timings(struct llama_context * ctx) {
  10774. const llama_timings timings = llama_get_timings(ctx);
  10775. LLAMA_LOG_INFO("\n");
  10776. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  10777. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10778. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  10779. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  10780. __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);
  10781. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10782. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  10783. 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));
  10784. }
  10785. void llama_reset_timings(struct llama_context * ctx) {
  10786. ctx->t_start_us = ggml_time_us();
  10787. ctx->t_sample_us = ctx->n_sample = 0;
  10788. ctx->t_eval_us = ctx->n_eval = 0;
  10789. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  10790. }
  10791. const char * llama_print_system_info(void) {
  10792. static std::string s;
  10793. s = "";
  10794. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  10795. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  10796. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  10797. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  10798. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  10799. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  10800. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  10801. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  10802. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  10803. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  10804. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  10805. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  10806. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  10807. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  10808. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  10809. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  10810. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  10811. return s.c_str();
  10812. }
  10813. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  10814. fprintf(stream, "\n");
  10815. fprintf(stream, "###########\n");
  10816. fprintf(stream, "# Timings #\n");
  10817. fprintf(stream, "###########\n");
  10818. fprintf(stream, "\n");
  10819. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  10820. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  10821. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  10822. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  10823. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  10824. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  10825. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  10826. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  10827. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  10828. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  10829. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  10830. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  10831. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  10832. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  10833. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  10834. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  10835. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  10836. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  10837. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  10838. }
  10839. // For internal test use
  10840. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  10841. struct llama_context * ctx
  10842. ) {
  10843. return ctx->model.tensors_by_name;
  10844. }
  10845. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  10846. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  10847. g_state.log_callback_user_data = user_data;
  10848. #ifdef GGML_USE_METAL
  10849. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  10850. #endif
  10851. }
  10852. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  10853. va_list args_copy;
  10854. va_copy(args_copy, args);
  10855. char buffer[128];
  10856. int len = vsnprintf(buffer, 128, format, args);
  10857. if (len < 128) {
  10858. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  10859. } else {
  10860. char* buffer2 = new char[len+1];
  10861. vsnprintf(buffer2, len+1, format, args_copy);
  10862. buffer2[len] = 0;
  10863. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  10864. delete[] buffer2;
  10865. }
  10866. va_end(args_copy);
  10867. }
  10868. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  10869. va_list args;
  10870. va_start(args, format);
  10871. llama_log_internal_v(level, format, args);
  10872. va_end(args);
  10873. }
  10874. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  10875. (void) level;
  10876. (void) user_data;
  10877. fputs(text, stderr);
  10878. fflush(stderr);
  10879. }