llama.cpp 514 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <cwctype>
  65. #include <forward_list>
  66. #include <fstream>
  67. #include <functional>
  68. #include <initializer_list>
  69. #include <locale>
  70. #include <map>
  71. #include <memory>
  72. #include <mutex>
  73. #include <numeric>
  74. #include <queue>
  75. #include <random>
  76. #include <regex>
  77. #include <set>
  78. #include <sstream>
  79. #include <thread>
  80. #include <type_traits>
  81. #include <unordered_map>
  82. #if defined(_MSC_VER)
  83. #pragma warning(disable: 4244 4267) // possible loss of data
  84. #endif
  85. #ifdef __GNUC__
  86. #ifdef __MINGW32__
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  88. #else
  89. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  90. #endif
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...)
  93. #endif
  94. #define LLAMA_MAX_NODES 8192
  95. #define LLAMA_MAX_EXPERTS 8
  96. //
  97. // logging
  98. //
  99. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  100. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  101. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  102. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  103. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  104. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  105. //
  106. // helpers
  107. //
  108. static size_t utf8_len(char src) {
  109. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  110. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  111. return lookup[highbits];
  112. }
  113. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  114. std::string result;
  115. for (size_t pos = 0; ; pos += search.length()) {
  116. auto new_pos = s.find(search, pos);
  117. if (new_pos == std::string::npos) {
  118. result += s.substr(pos, s.size() - pos);
  119. break;
  120. }
  121. result += s.substr(pos, new_pos - pos) + replace;
  122. pos = new_pos;
  123. }
  124. s = std::move(result);
  125. }
  126. static bool is_float_close(float a, float b, float abs_tol) {
  127. // Check for non-negative tolerance
  128. if (abs_tol < 0.0) {
  129. throw std::invalid_argument("Tolerance must be non-negative");
  130. }
  131. // Exact equality check
  132. if (a == b) {
  133. return true;
  134. }
  135. // Check for infinities
  136. if (std::isinf(a) || std::isinf(b)) {
  137. return false;
  138. }
  139. // Regular comparison using the provided absolute tolerance
  140. return std::fabs(b - a) <= abs_tol;
  141. }
  142. static void zeros(std::ofstream & file, size_t n) {
  143. char zero = 0;
  144. for (size_t i = 0; i < n; ++i) {
  145. file.write(&zero, 1);
  146. }
  147. }
  148. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  149. static std::string format(const char * fmt, ...) {
  150. va_list ap;
  151. va_list ap2;
  152. va_start(ap, fmt);
  153. va_copy(ap2, ap);
  154. int size = vsnprintf(NULL, 0, fmt, ap);
  155. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  156. std::vector<char> buf(size + 1);
  157. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  158. GGML_ASSERT(size2 == size);
  159. va_end(ap2);
  160. va_end(ap);
  161. return std::string(buf.data(), size);
  162. }
  163. //
  164. // gguf constants (sync with gguf.py)
  165. //
  166. enum llm_arch {
  167. LLM_ARCH_LLAMA,
  168. LLM_ARCH_FALCON,
  169. LLM_ARCH_BAICHUAN,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_PERSIMMON,
  176. LLM_ARCH_REFACT,
  177. LLM_ARCH_BERT,
  178. LLM_ARCH_NOMIC_BERT,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_PHI2,
  184. LLM_ARCH_PLAMO,
  185. LLM_ARCH_CODESHELL,
  186. LLM_ARCH_ORION,
  187. LLM_ARCH_INTERNLM2,
  188. LLM_ARCH_MINICPM,
  189. LLM_ARCH_GEMMA,
  190. LLM_ARCH_UNKNOWN,
  191. };
  192. static std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  193. { LLM_ARCH_LLAMA, "llama" },
  194. { LLM_ARCH_FALCON, "falcon" },
  195. { LLM_ARCH_GPT2, "gpt2" },
  196. { LLM_ARCH_GPTJ, "gptj" },
  197. { LLM_ARCH_GPTNEOX, "gptneox" },
  198. { LLM_ARCH_MPT, "mpt" },
  199. { LLM_ARCH_BAICHUAN, "baichuan" },
  200. { LLM_ARCH_STARCODER, "starcoder" },
  201. { LLM_ARCH_PERSIMMON, "persimmon" },
  202. { LLM_ARCH_REFACT, "refact" },
  203. { LLM_ARCH_BERT, "bert" },
  204. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  205. { LLM_ARCH_BLOOM, "bloom" },
  206. { LLM_ARCH_STABLELM, "stablelm" },
  207. { LLM_ARCH_QWEN, "qwen" },
  208. { LLM_ARCH_QWEN2, "qwen2" },
  209. { LLM_ARCH_PHI2, "phi2" },
  210. { LLM_ARCH_PLAMO, "plamo" },
  211. { LLM_ARCH_CODESHELL, "codeshell" },
  212. { LLM_ARCH_ORION, "orion" },
  213. { LLM_ARCH_INTERNLM2, "internlm2" },
  214. { LLM_ARCH_MINICPM, "minicpm" },
  215. { LLM_ARCH_GEMMA, "gemma" },
  216. };
  217. enum llm_kv {
  218. LLM_KV_GENERAL_ARCHITECTURE,
  219. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  220. LLM_KV_GENERAL_ALIGNMENT,
  221. LLM_KV_GENERAL_NAME,
  222. LLM_KV_GENERAL_AUTHOR,
  223. LLM_KV_GENERAL_URL,
  224. LLM_KV_GENERAL_DESCRIPTION,
  225. LLM_KV_GENERAL_LICENSE,
  226. LLM_KV_GENERAL_SOURCE_URL,
  227. LLM_KV_GENERAL_SOURCE_HF_REPO,
  228. LLM_KV_CONTEXT_LENGTH,
  229. LLM_KV_EMBEDDING_LENGTH,
  230. LLM_KV_BLOCK_COUNT,
  231. LLM_KV_FEED_FORWARD_LENGTH,
  232. LLM_KV_USE_PARALLEL_RESIDUAL,
  233. LLM_KV_TENSOR_DATA_LAYOUT,
  234. LLM_KV_EXPERT_COUNT,
  235. LLM_KV_EXPERT_USED_COUNT,
  236. LLM_KV_POOLING_TYPE,
  237. LLM_KV_ATTENTION_HEAD_COUNT,
  238. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  239. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  240. LLM_KV_ATTENTION_CLAMP_KQV,
  241. LLM_KV_ATTENTION_KEY_LENGTH,
  242. LLM_KV_ATTENTION_VALUE_LENGTH,
  243. LLM_KV_ATTENTION_LAYERNORM_EPS,
  244. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  245. LLM_KV_ATTENTION_CAUSAL,
  246. LLM_KV_ROPE_DIMENSION_COUNT,
  247. LLM_KV_ROPE_FREQ_BASE,
  248. LLM_KV_ROPE_SCALE_LINEAR,
  249. LLM_KV_ROPE_SCALING_TYPE,
  250. LLM_KV_ROPE_SCALING_FACTOR,
  251. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  252. LLM_KV_ROPE_SCALING_FINETUNED,
  253. LLM_KV_TOKENIZER_MODEL,
  254. LLM_KV_TOKENIZER_LIST,
  255. LLM_KV_TOKENIZER_TOKEN_TYPE,
  256. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  257. LLM_KV_TOKENIZER_SCORES,
  258. LLM_KV_TOKENIZER_MERGES,
  259. LLM_KV_TOKENIZER_BOS_ID,
  260. LLM_KV_TOKENIZER_EOS_ID,
  261. LLM_KV_TOKENIZER_UNK_ID,
  262. LLM_KV_TOKENIZER_SEP_ID,
  263. LLM_KV_TOKENIZER_PAD_ID,
  264. LLM_KV_TOKENIZER_ADD_BOS,
  265. LLM_KV_TOKENIZER_ADD_EOS,
  266. LLM_KV_TOKENIZER_ADD_PREFIX,
  267. LLM_KV_TOKENIZER_HF_JSON,
  268. LLM_KV_TOKENIZER_RWKV,
  269. };
  270. static std::map<llm_kv, const char *> LLM_KV_NAMES = {
  271. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  272. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  273. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  274. { LLM_KV_GENERAL_NAME, "general.name" },
  275. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  276. { LLM_KV_GENERAL_URL, "general.url" },
  277. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  278. { LLM_KV_GENERAL_LICENSE, "general.license" },
  279. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  280. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  281. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  282. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  283. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  284. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  285. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  286. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  287. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  288. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  289. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  290. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  291. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  292. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  293. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  294. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  295. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  296. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  297. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  298. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  299. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  300. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  301. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  302. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  303. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  304. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  305. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  306. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  307. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  308. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  309. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  310. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  311. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  312. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  313. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  314. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  315. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  316. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  317. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  318. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  319. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  320. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  321. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  322. };
  323. struct LLM_KV {
  324. LLM_KV(llm_arch arch) : arch(arch) {}
  325. llm_arch arch;
  326. std::string operator()(llm_kv kv) const {
  327. return ::format(LLM_KV_NAMES[kv], LLM_ARCH_NAMES[arch]);
  328. }
  329. };
  330. enum llm_tensor {
  331. LLM_TENSOR_TOKEN_EMBD,
  332. LLM_TENSOR_TOKEN_EMBD_NORM,
  333. LLM_TENSOR_TOKEN_TYPES,
  334. LLM_TENSOR_POS_EMBD,
  335. LLM_TENSOR_OUTPUT,
  336. LLM_TENSOR_OUTPUT_NORM,
  337. LLM_TENSOR_ROPE_FREQS,
  338. LLM_TENSOR_ATTN_Q,
  339. LLM_TENSOR_ATTN_K,
  340. LLM_TENSOR_ATTN_V,
  341. LLM_TENSOR_ATTN_QKV,
  342. LLM_TENSOR_ATTN_OUT,
  343. LLM_TENSOR_ATTN_NORM,
  344. LLM_TENSOR_ATTN_NORM_2,
  345. LLM_TENSOR_ATTN_OUT_NORM,
  346. LLM_TENSOR_ATTN_ROT_EMBD,
  347. LLM_TENSOR_FFN_GATE_INP,
  348. LLM_TENSOR_FFN_NORM,
  349. LLM_TENSOR_FFN_GATE,
  350. LLM_TENSOR_FFN_DOWN,
  351. LLM_TENSOR_FFN_UP,
  352. LLM_TENSOR_FFN_ACT,
  353. LLM_TENSOR_FFN_DOWN_EXP,
  354. LLM_TENSOR_FFN_GATE_EXP,
  355. LLM_TENSOR_FFN_UP_EXP,
  356. LLM_TENSOR_ATTN_Q_NORM,
  357. LLM_TENSOR_ATTN_K_NORM,
  358. LLM_TENSOR_LAYER_OUT_NORM,
  359. };
  360. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  361. {
  362. LLM_ARCH_LLAMA,
  363. {
  364. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  365. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  366. { LLM_TENSOR_OUTPUT, "output" },
  367. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  368. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  369. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  370. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  371. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  372. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  373. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  374. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  375. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  376. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  377. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  378. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  379. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  380. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  381. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  382. },
  383. },
  384. {
  385. LLM_ARCH_BAICHUAN,
  386. {
  387. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  388. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  389. { LLM_TENSOR_OUTPUT, "output" },
  390. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  391. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  392. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  393. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  394. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  395. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  396. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  397. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  398. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  399. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  400. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  401. },
  402. },
  403. {
  404. LLM_ARCH_FALCON,
  405. {
  406. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  407. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  408. { LLM_TENSOR_OUTPUT, "output" },
  409. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  410. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  411. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  412. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  413. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  414. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  415. },
  416. },
  417. {
  418. LLM_ARCH_GPT2,
  419. {
  420. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  421. { LLM_TENSOR_POS_EMBD, "position_embd" },
  422. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  423. { LLM_TENSOR_OUTPUT, "output" },
  424. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  425. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  426. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  427. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  428. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  429. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  430. },
  431. },
  432. {
  433. LLM_ARCH_GPTJ,
  434. {
  435. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  436. },
  437. },
  438. {
  439. LLM_ARCH_GPTNEOX,
  440. {
  441. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  442. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  443. { LLM_TENSOR_OUTPUT, "output" },
  444. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  445. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  446. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  447. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  448. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  449. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  450. },
  451. },
  452. {
  453. LLM_ARCH_PERSIMMON,
  454. {
  455. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  456. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  457. { LLM_TENSOR_OUTPUT, "output"},
  458. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  459. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  460. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  461. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  462. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  463. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  465. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  466. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  467. },
  468. },
  469. {
  470. LLM_ARCH_MPT,
  471. {
  472. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  473. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  474. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  475. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  476. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  477. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  478. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  479. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  480. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  481. },
  482. },
  483. {
  484. LLM_ARCH_STARCODER,
  485. {
  486. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  487. { LLM_TENSOR_POS_EMBD, "position_embd" },
  488. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  489. { LLM_TENSOR_OUTPUT, "output" },
  490. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  491. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  492. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  493. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  494. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  495. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  496. },
  497. },
  498. {
  499. LLM_ARCH_REFACT,
  500. {
  501. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  502. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  503. { LLM_TENSOR_OUTPUT, "output" },
  504. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  505. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  506. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  507. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  508. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  509. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  510. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  511. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  512. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  513. },
  514. },
  515. {
  516. LLM_ARCH_BERT,
  517. {
  518. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  519. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  520. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  521. { LLM_TENSOR_POS_EMBD, "position_embd" },
  522. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  523. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  524. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  525. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  526. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  527. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  528. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  529. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  530. },
  531. },
  532. {
  533. LLM_ARCH_NOMIC_BERT,
  534. {
  535. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  536. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  537. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  538. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  539. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  540. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  541. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  542. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  543. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  544. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  545. },
  546. },
  547. {
  548. LLM_ARCH_BLOOM,
  549. {
  550. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  551. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  552. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  553. { LLM_TENSOR_OUTPUT, "output" },
  554. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  555. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  556. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  557. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  558. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  559. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  560. },
  561. },
  562. {
  563. LLM_ARCH_STABLELM,
  564. {
  565. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  566. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  567. { LLM_TENSOR_OUTPUT, "output" },
  568. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  569. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  570. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  571. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  572. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  573. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  574. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  575. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  576. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  577. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  578. },
  579. },
  580. {
  581. LLM_ARCH_QWEN,
  582. {
  583. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  584. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  585. { LLM_TENSOR_OUTPUT, "output" },
  586. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  587. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  588. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  589. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  590. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  591. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  592. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  593. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  594. },
  595. },
  596. {
  597. LLM_ARCH_QWEN2,
  598. {
  599. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  600. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  601. { LLM_TENSOR_OUTPUT, "output" },
  602. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  603. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  604. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  605. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  606. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  607. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  608. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  609. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  610. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  611. },
  612. },
  613. {
  614. LLM_ARCH_PHI2,
  615. {
  616. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  617. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  618. { LLM_TENSOR_OUTPUT, "output" },
  619. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  620. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  621. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  622. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  623. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  624. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  625. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  626. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  627. },
  628. },
  629. {
  630. LLM_ARCH_PLAMO,
  631. {
  632. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  633. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  634. { LLM_TENSOR_OUTPUT, "output" },
  635. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  636. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  637. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  638. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  639. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  640. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  641. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  642. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  643. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  644. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  645. },
  646. },
  647. {
  648. LLM_ARCH_CODESHELL,
  649. {
  650. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  651. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  652. { LLM_TENSOR_OUTPUT, "output" },
  653. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  654. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  655. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  656. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  657. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  658. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  659. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  660. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  661. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  662. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  663. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  664. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  665. },
  666. },
  667. {
  668. LLM_ARCH_ORION,
  669. {
  670. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  671. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  672. { LLM_TENSOR_OUTPUT, "output" },
  673. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  674. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  675. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  676. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  677. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  678. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  679. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  680. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  681. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  682. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  683. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  684. },
  685. },
  686. {
  687. LLM_ARCH_INTERNLM2,
  688. {
  689. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  690. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  691. { LLM_TENSOR_OUTPUT, "output" },
  692. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  693. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  694. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  695. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  696. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  697. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  698. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  699. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  700. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  701. },
  702. },
  703. {
  704. LLM_ARCH_MINICPM,
  705. {
  706. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  707. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  708. { LLM_TENSOR_OUTPUT, "output" },
  709. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  710. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  711. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  712. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  713. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  714. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  715. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  716. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  717. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  718. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  719. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  720. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  721. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  722. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  723. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  724. },
  725. },
  726. {
  727. LLM_ARCH_GEMMA,
  728. {
  729. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  730. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  731. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  732. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  733. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  734. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  735. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  736. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  737. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  738. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  739. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  740. },
  741. },
  742. {
  743. LLM_ARCH_UNKNOWN,
  744. {
  745. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  746. },
  747. },
  748. };
  749. static llm_arch llm_arch_from_string(const std::string & name) {
  750. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  751. if (kv.second == name) {
  752. return kv.first;
  753. }
  754. }
  755. return LLM_ARCH_UNKNOWN;
  756. }
  757. // helper to handle gguf constants
  758. // usage:
  759. //
  760. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  761. //
  762. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  763. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  764. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  765. //
  766. struct LLM_TN {
  767. LLM_TN(llm_arch arch) : arch(arch) {}
  768. llm_arch arch;
  769. std::string operator()(llm_tensor tensor) const {
  770. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  771. return "__missing__";
  772. }
  773. return LLM_TENSOR_NAMES[arch].at(tensor);
  774. }
  775. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  776. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  777. return "__missing__";
  778. }
  779. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  780. }
  781. std::string operator()(llm_tensor tensor, int bid) const {
  782. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  783. return "__missing__";
  784. }
  785. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  786. }
  787. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  788. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  789. return "__missing__";
  790. }
  791. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  792. }
  793. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  794. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  795. return "__missing__";
  796. }
  797. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  798. }
  799. };
  800. //
  801. // gguf helpers
  802. //
  803. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  804. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  805. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  806. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  807. };
  808. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  809. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  810. if (kv.second == name) {
  811. return kv.first;
  812. }
  813. }
  814. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  815. }
  816. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  817. switch (type) {
  818. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  819. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  820. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  821. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  822. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  823. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  824. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  825. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  826. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  827. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  828. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  829. default: return format("unknown type %d", type);
  830. }
  831. }
  832. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  833. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  834. switch (type) {
  835. case GGUF_TYPE_STRING:
  836. return gguf_get_val_str(ctx_gguf, i);
  837. case GGUF_TYPE_ARRAY:
  838. {
  839. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  840. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  841. const void * data = gguf_get_arr_data(ctx_gguf, i);
  842. std::stringstream ss;
  843. ss << "[";
  844. for (int j = 0; j < arr_n; j++) {
  845. if (arr_type == GGUF_TYPE_STRING) {
  846. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  847. // escape quotes
  848. replace_all(val, "\\", "\\\\");
  849. replace_all(val, "\"", "\\\"");
  850. ss << '"' << val << '"';
  851. } else if (arr_type == GGUF_TYPE_ARRAY) {
  852. ss << "???";
  853. } else {
  854. ss << gguf_data_to_str(arr_type, data, j);
  855. }
  856. if (j < arr_n - 1) {
  857. ss << ", ";
  858. }
  859. }
  860. ss << "]";
  861. return ss.str();
  862. }
  863. default:
  864. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  865. }
  866. }
  867. //
  868. // ggml helpers
  869. //
  870. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  871. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  872. if (plan.work_size > 0) {
  873. buf.resize(plan.work_size);
  874. plan.work_data = buf.data();
  875. }
  876. ggml_graph_compute(graph, &plan);
  877. }
  878. //
  879. // llama helpers
  880. //
  881. #if defined(_WIN32)
  882. static std::string llama_format_win_err(DWORD err) {
  883. LPSTR buf;
  884. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  885. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  886. if (!size) {
  887. return "FormatMessageA failed";
  888. }
  889. std::string ret(buf, size);
  890. LocalFree(buf);
  891. return ret;
  892. }
  893. #endif
  894. template <typename T>
  895. struct no_init {
  896. T value;
  897. no_init() { /* do nothing */ }
  898. };
  899. struct llama_file {
  900. // use FILE * so we don't have to re-open the file to mmap
  901. FILE * fp;
  902. size_t size;
  903. llama_file(const char * fname, const char * mode) {
  904. fp = std::fopen(fname, mode);
  905. if (fp == NULL) {
  906. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  907. }
  908. seek(0, SEEK_END);
  909. size = tell();
  910. seek(0, SEEK_SET);
  911. }
  912. size_t tell() const {
  913. #ifdef _WIN32
  914. __int64 ret = _ftelli64(fp);
  915. #else
  916. long ret = std::ftell(fp);
  917. #endif
  918. GGML_ASSERT(ret != -1); // this really shouldn't fail
  919. return (size_t) ret;
  920. }
  921. void seek(size_t offset, int whence) const {
  922. #ifdef _WIN32
  923. int ret = _fseeki64(fp, (__int64) offset, whence);
  924. #else
  925. int ret = std::fseek(fp, (long) offset, whence);
  926. #endif
  927. GGML_ASSERT(ret == 0); // same
  928. }
  929. void read_raw(void * ptr, size_t len) const {
  930. if (len == 0) {
  931. return;
  932. }
  933. errno = 0;
  934. std::size_t ret = std::fread(ptr, len, 1, fp);
  935. if (ferror(fp)) {
  936. throw std::runtime_error(format("read error: %s", strerror(errno)));
  937. }
  938. if (ret != 1) {
  939. throw std::runtime_error("unexpectedly reached end of file");
  940. }
  941. }
  942. uint32_t read_u32() const {
  943. uint32_t ret;
  944. read_raw(&ret, sizeof(ret));
  945. return ret;
  946. }
  947. void write_raw(const void * ptr, size_t len) const {
  948. if (len == 0) {
  949. return;
  950. }
  951. errno = 0;
  952. size_t ret = std::fwrite(ptr, len, 1, fp);
  953. if (ret != 1) {
  954. throw std::runtime_error(format("write error: %s", strerror(errno)));
  955. }
  956. }
  957. void write_u32(std::uint32_t val) const {
  958. write_raw(&val, sizeof(val));
  959. }
  960. ~llama_file() {
  961. if (fp) {
  962. std::fclose(fp);
  963. }
  964. }
  965. };
  966. struct llama_mmap {
  967. void * addr;
  968. size_t size;
  969. llama_mmap(const llama_mmap &) = delete;
  970. #ifdef _POSIX_MAPPED_FILES
  971. static constexpr bool SUPPORTED = true;
  972. // list of mapped fragments (first_offset, last_offset)
  973. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  974. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  975. size = file->size;
  976. int fd = fileno(file->fp);
  977. int flags = MAP_SHARED;
  978. // prefetch/readahead impairs performance on NUMA systems
  979. if (numa) { prefetch = 0; }
  980. #ifdef __linux__
  981. // advise the kernel to read the file sequentially (increases readahead)
  982. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  983. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  984. strerror(errno));
  985. }
  986. if (prefetch) { flags |= MAP_POPULATE; }
  987. #endif
  988. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  989. if (addr == MAP_FAILED) { // NOLINT
  990. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  991. }
  992. if (prefetch > 0) {
  993. // advise the kernel to preload the mapped memory
  994. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  995. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  996. strerror(errno));
  997. }
  998. }
  999. if (numa) {
  1000. // advise the kernel not to use readahead
  1001. // (because the next page might not belong on the same node)
  1002. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1003. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1004. strerror(errno));
  1005. }
  1006. }
  1007. // initialize list of mapped_fragments
  1008. mapped_fragments.emplace_back(0, file->size);
  1009. }
  1010. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1011. // align first to the next page
  1012. size_t offset_in_page = *first & (page_size - 1);
  1013. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1014. *first += offset_to_page;
  1015. // align last to the previous page
  1016. *last = *last & ~(page_size - 1);
  1017. if (*last <= *first) {
  1018. *last = *first;
  1019. }
  1020. }
  1021. // partially unmap the file in the range [first, last)
  1022. void unmap_fragment(size_t first, size_t last) {
  1023. // note: this function must not be called multiple times with overlapping ranges
  1024. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1025. int page_size = sysconf(_SC_PAGESIZE);
  1026. align_range(&first, &last, page_size);
  1027. size_t len = last - first;
  1028. if (len == 0) {
  1029. return;
  1030. }
  1031. GGML_ASSERT(first % page_size == 0);
  1032. GGML_ASSERT(last % page_size == 0);
  1033. GGML_ASSERT(last > first);
  1034. void * next_page_start = (uint8_t *) addr + first;
  1035. // unmap the range
  1036. if (munmap(next_page_start, len)) {
  1037. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1038. }
  1039. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1040. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1041. for (const auto & frag : mapped_fragments) {
  1042. if (frag.first < first && frag.second > last) {
  1043. // the range is in the middle of the fragment, split it
  1044. new_mapped_fragments.emplace_back(frag.first, first);
  1045. new_mapped_fragments.emplace_back(last, frag.second);
  1046. } else if (frag.first < first && frag.second > first) {
  1047. // the range starts in the middle of the fragment
  1048. new_mapped_fragments.emplace_back(frag.first, first);
  1049. } else if (frag.first < last && frag.second > last) {
  1050. // the range ends in the middle of the fragment
  1051. new_mapped_fragments.emplace_back(last, frag.second);
  1052. } else if (frag.first >= first && frag.second <= last) {
  1053. // the range covers the entire fragment
  1054. } else {
  1055. // the range is outside the fragment
  1056. new_mapped_fragments.push_back(frag);
  1057. }
  1058. }
  1059. mapped_fragments = std::move(new_mapped_fragments);
  1060. }
  1061. ~llama_mmap() {
  1062. for (const auto & frag : mapped_fragments) {
  1063. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1064. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1065. }
  1066. }
  1067. }
  1068. #elif defined(_WIN32)
  1069. static constexpr bool SUPPORTED = true;
  1070. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1071. GGML_UNUSED(numa);
  1072. size = file->size;
  1073. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1074. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1075. if (hMapping == NULL) {
  1076. DWORD error = GetLastError();
  1077. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1078. }
  1079. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1080. DWORD error = GetLastError();
  1081. CloseHandle(hMapping);
  1082. if (addr == NULL) {
  1083. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1084. }
  1085. if (prefetch > 0) {
  1086. #if _WIN32_WINNT >= 0x602
  1087. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1088. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1089. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1090. // may fail on pre-Windows 8 systems
  1091. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1092. if (pPrefetchVirtualMemory) {
  1093. // advise the kernel to preload the mapped memory
  1094. WIN32_MEMORY_RANGE_ENTRY range;
  1095. range.VirtualAddress = addr;
  1096. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1097. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1098. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1099. llama_format_win_err(GetLastError()).c_str());
  1100. }
  1101. }
  1102. #else
  1103. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1104. #endif
  1105. }
  1106. }
  1107. void unmap_fragment(size_t first, size_t last) {
  1108. // not supported
  1109. GGML_UNUSED(first);
  1110. GGML_UNUSED(last);
  1111. }
  1112. ~llama_mmap() {
  1113. if (!UnmapViewOfFile(addr)) {
  1114. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1115. llama_format_win_err(GetLastError()).c_str());
  1116. }
  1117. }
  1118. #else
  1119. static constexpr bool SUPPORTED = false;
  1120. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1121. GGML_UNUSED(file);
  1122. GGML_UNUSED(prefetch);
  1123. GGML_UNUSED(numa);
  1124. throw std::runtime_error("mmap not supported");
  1125. }
  1126. void unmap_fragment(size_t first, size_t last) {
  1127. GGML_UNUSED(first);
  1128. GGML_UNUSED(last);
  1129. throw std::runtime_error("mmap not supported");
  1130. }
  1131. #endif
  1132. };
  1133. // Represents some region of memory being locked using mlock or VirtualLock;
  1134. // will automatically unlock on destruction.
  1135. struct llama_mlock {
  1136. void * addr = NULL;
  1137. size_t size = 0;
  1138. bool failed_already = false;
  1139. llama_mlock() {}
  1140. llama_mlock(const llama_mlock &) = delete;
  1141. ~llama_mlock() {
  1142. if (size) {
  1143. raw_unlock(addr, size);
  1144. }
  1145. }
  1146. void init(void * ptr) {
  1147. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1148. addr = ptr;
  1149. }
  1150. void grow_to(size_t target_size) {
  1151. GGML_ASSERT(addr);
  1152. if (failed_already) {
  1153. return;
  1154. }
  1155. size_t granularity = lock_granularity();
  1156. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1157. if (target_size > size) {
  1158. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1159. size = target_size;
  1160. } else {
  1161. failed_already = true;
  1162. }
  1163. }
  1164. }
  1165. #ifdef _POSIX_MEMLOCK_RANGE
  1166. static constexpr bool SUPPORTED = true;
  1167. static size_t lock_granularity() {
  1168. return (size_t) sysconf(_SC_PAGESIZE);
  1169. }
  1170. #ifdef __APPLE__
  1171. #define MLOCK_SUGGESTION \
  1172. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1173. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1174. #else
  1175. #define MLOCK_SUGGESTION \
  1176. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1177. #endif
  1178. bool raw_lock(const void * addr, size_t size) const {
  1179. if (!mlock(addr, size)) {
  1180. return true;
  1181. }
  1182. char* errmsg = std::strerror(errno);
  1183. bool suggest = (errno == ENOMEM);
  1184. // Check if the resource limit is fine after all
  1185. struct rlimit lock_limit;
  1186. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1187. suggest = false;
  1188. }
  1189. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1190. suggest = false;
  1191. }
  1192. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1193. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1194. return false;
  1195. }
  1196. #undef MLOCK_SUGGESTION
  1197. static void raw_unlock(void * addr, size_t size) {
  1198. if (munlock(addr, size)) {
  1199. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1200. }
  1201. }
  1202. #elif defined(_WIN32)
  1203. static constexpr bool SUPPORTED = true;
  1204. static size_t lock_granularity() {
  1205. SYSTEM_INFO si;
  1206. GetSystemInfo(&si);
  1207. return (size_t) si.dwPageSize;
  1208. }
  1209. bool raw_lock(void * ptr, size_t len) const {
  1210. for (int tries = 1; ; tries++) {
  1211. if (VirtualLock(ptr, len)) {
  1212. return true;
  1213. }
  1214. if (tries == 2) {
  1215. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1216. len, size, llama_format_win_err(GetLastError()).c_str());
  1217. return false;
  1218. }
  1219. // It failed but this was only the first try; increase the working
  1220. // set size and try again.
  1221. SIZE_T min_ws_size, max_ws_size;
  1222. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1223. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1224. llama_format_win_err(GetLastError()).c_str());
  1225. return false;
  1226. }
  1227. // Per MSDN: "The maximum number of pages that a process can lock
  1228. // is equal to the number of pages in its minimum working set minus
  1229. // a small overhead."
  1230. // Hopefully a megabyte is enough overhead:
  1231. size_t increment = len + 1048576;
  1232. // The minimum must be <= the maximum, so we need to increase both:
  1233. min_ws_size += increment;
  1234. max_ws_size += increment;
  1235. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1236. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1237. llama_format_win_err(GetLastError()).c_str());
  1238. return false;
  1239. }
  1240. }
  1241. }
  1242. static void raw_unlock(void * ptr, size_t len) {
  1243. if (!VirtualUnlock(ptr, len)) {
  1244. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1245. llama_format_win_err(GetLastError()).c_str());
  1246. }
  1247. }
  1248. #else
  1249. static constexpr bool SUPPORTED = false;
  1250. static size_t lock_granularity() {
  1251. return (size_t) 65536;
  1252. }
  1253. bool raw_lock(const void * addr, size_t len) const {
  1254. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1255. return false;
  1256. }
  1257. static void raw_unlock(const void * addr, size_t len) {}
  1258. #endif
  1259. };
  1260. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1261. std::vector<char> result(8, 0);
  1262. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1263. if (n_tokens < 0) {
  1264. result.resize(-n_tokens);
  1265. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1266. GGML_ASSERT(check == -n_tokens);
  1267. }
  1268. else {
  1269. result.resize(n_tokens);
  1270. }
  1271. return std::string(result.data(), result.size());
  1272. }
  1273. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1274. ggml_backend_buffer_type_t buft = nullptr;
  1275. #if defined(GGML_USE_CUBLAS)
  1276. // host buffers should only be used when data is expected to be copied to/from the GPU
  1277. if (host_buffer) {
  1278. buft = ggml_backend_cuda_host_buffer_type();
  1279. }
  1280. #elif defined(GGML_USE_SYCL)
  1281. buft = ggml_backend_sycl_host_buffer_type();
  1282. #elif defined(GGML_USE_CPU_HBM)
  1283. buft = ggml_backend_cpu_hbm_buffer_type();
  1284. #elif defined(GGML_USE_VULKAN)
  1285. if (host_buffer) {
  1286. buft = ggml_backend_vk_host_buffer_type();
  1287. }
  1288. #endif
  1289. if (buft == nullptr) {
  1290. buft = ggml_backend_cpu_buffer_type();
  1291. }
  1292. return buft;
  1293. GGML_UNUSED(host_buffer);
  1294. }
  1295. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1296. ggml_backend_buffer_type_t buft = nullptr;
  1297. #ifdef GGML_USE_METAL
  1298. buft = ggml_backend_metal_buffer_type();
  1299. #elif defined(GGML_USE_CUBLAS)
  1300. buft = ggml_backend_cuda_buffer_type(gpu);
  1301. #elif defined(GGML_USE_VULKAN)
  1302. buft = ggml_backend_vk_buffer_type(gpu);
  1303. #elif defined(GGML_USE_SYCL)
  1304. buft = ggml_backend_sycl_buffer_type(gpu);
  1305. #elif defined(GGML_USE_CLBLAST)
  1306. buft = ggml_backend_opencl_buffer_type();
  1307. #elif defined(GGML_USE_KOMPUTE)
  1308. buft = ggml_backend_kompute_buffer_type(gpu);
  1309. if (buft == nullptr) {
  1310. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1311. }
  1312. #endif
  1313. if (buft == nullptr) {
  1314. buft = llama_default_buffer_type_cpu(true);
  1315. }
  1316. return buft;
  1317. GGML_UNUSED(gpu);
  1318. }
  1319. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1320. ggml_backend_buffer_type_t buft = nullptr;
  1321. #ifdef GGML_USE_CUBLAS
  1322. if (ggml_backend_cuda_get_device_count() > 1) {
  1323. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1324. }
  1325. #endif
  1326. if (buft == nullptr) {
  1327. buft = llama_default_buffer_type_offload(fallback_gpu);
  1328. }
  1329. return buft;
  1330. GGML_UNUSED(tensor_split);
  1331. }
  1332. static size_t llama_get_device_count() {
  1333. #if defined(GGML_USE_CUBLAS)
  1334. return ggml_backend_cuda_get_device_count();
  1335. #elif defined(GGML_USE_VULKAN)
  1336. return ggml_backend_vk_get_device_count();
  1337. #else
  1338. return 1;
  1339. #endif
  1340. }
  1341. static size_t llama_get_device_memory(int device) {
  1342. #if defined(GGML_USE_CUBLAS)
  1343. size_t total;
  1344. size_t free;
  1345. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1346. return free;
  1347. #elif defined(GGML_USE_VULKAN)
  1348. size_t total;
  1349. size_t free;
  1350. ggml_backend_vk_get_device_memory(device, &total, &free);
  1351. return free;
  1352. #else
  1353. return 1;
  1354. GGML_UNUSED(device);
  1355. #endif
  1356. }
  1357. //
  1358. // globals
  1359. //
  1360. struct llama_state {
  1361. llama_state() {
  1362. #ifdef GGML_USE_METAL
  1363. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1364. #endif
  1365. }
  1366. // We save the log callback globally
  1367. ggml_log_callback log_callback = llama_log_callback_default;
  1368. void * log_callback_user_data = nullptr;
  1369. };
  1370. static llama_state g_state;
  1371. // available llama models
  1372. enum e_model {
  1373. MODEL_UNKNOWN,
  1374. MODEL_17M,
  1375. MODEL_22M,
  1376. MODEL_33M,
  1377. MODEL_109M,
  1378. MODEL_137M,
  1379. MODEL_335M,
  1380. MODEL_0_5B,
  1381. MODEL_1B,
  1382. MODEL_2B,
  1383. MODEL_3B,
  1384. MODEL_4B,
  1385. MODEL_7B,
  1386. MODEL_8B,
  1387. MODEL_13B,
  1388. MODEL_14B,
  1389. MODEL_15B,
  1390. MODEL_20B,
  1391. MODEL_30B,
  1392. MODEL_34B,
  1393. MODEL_40B,
  1394. MODEL_65B,
  1395. MODEL_70B,
  1396. MODEL_SMALL,
  1397. MODEL_MEDIUM,
  1398. MODEL_LARGE,
  1399. MODEL_XL,
  1400. };
  1401. static const size_t kiB = 1024;
  1402. static const size_t MiB = 1024*kiB;
  1403. static const size_t GiB = 1024*MiB;
  1404. struct llama_hparams {
  1405. bool vocab_only;
  1406. bool rope_finetuned;
  1407. uint32_t n_vocab;
  1408. uint32_t n_ctx_train; // context size the model was trained on
  1409. uint32_t n_embd;
  1410. uint32_t n_head;
  1411. uint32_t n_head_kv;
  1412. uint32_t n_layer;
  1413. uint32_t n_rot;
  1414. 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
  1415. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1416. uint32_t n_ff;
  1417. uint32_t n_expert = 0;
  1418. uint32_t n_expert_used = 0;
  1419. uint32_t n_vocab_type = 0; // for BERT-style token types
  1420. float f_norm_eps;
  1421. float f_norm_rms_eps;
  1422. float rope_freq_base_train;
  1423. float rope_freq_scale_train;
  1424. uint32_t n_yarn_orig_ctx;
  1425. int32_t rope_scaling_type_train;
  1426. float f_clamp_kqv = 0.0f;
  1427. float f_max_alibi_bias = 0.0f;
  1428. bool causal_attn = true;
  1429. bool need_kq_pos = false;
  1430. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1431. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1432. bool operator!=(const llama_hparams & other) const {
  1433. if (this->vocab_only != other.vocab_only) return true;
  1434. if (this->n_vocab != other.n_vocab) return true;
  1435. if (this->n_ctx_train != other.n_ctx_train) return true;
  1436. if (this->n_embd != other.n_embd) return true;
  1437. if (this->n_head != other.n_head) return true;
  1438. if (this->n_head_kv != other.n_head_kv) return true;
  1439. if (this->n_layer != other.n_layer) return true;
  1440. if (this->n_rot != other.n_rot) return true;
  1441. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1442. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1443. if (this->n_ff != other.n_ff) return true;
  1444. if (this->n_expert != other.n_expert) return true;
  1445. if (this->n_expert_used != other.n_expert_used) return true;
  1446. if (this->rope_finetuned != other.rope_finetuned) return true;
  1447. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1448. const float EPSILON = 1e-9f;
  1449. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1450. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1451. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1452. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1453. return false;
  1454. }
  1455. uint32_t n_gqa() const {
  1456. return n_head/n_head_kv;
  1457. }
  1458. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1459. return n_embd_head_k * n_head_kv;
  1460. }
  1461. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1462. return n_embd_head_v * n_head_kv;
  1463. }
  1464. };
  1465. struct llama_cparams {
  1466. uint32_t n_ctx; // context size used during inference
  1467. uint32_t n_batch;
  1468. uint32_t n_threads; // number of threads to use for generation
  1469. uint32_t n_threads_batch; // number of threads to use for batch processing
  1470. float rope_freq_base;
  1471. float rope_freq_scale;
  1472. uint32_t n_yarn_orig_ctx;
  1473. // These hyperparameters are not exposed in GGUF, because all
  1474. // existing YaRN models use the same values for them.
  1475. float yarn_ext_factor;
  1476. float yarn_attn_factor;
  1477. float yarn_beta_fast;
  1478. float yarn_beta_slow;
  1479. float defrag_thold;
  1480. bool mul_mat_q;
  1481. bool offload_kqv;
  1482. bool do_pooling;
  1483. ggml_backend_sched_eval_callback cb_eval;
  1484. void * cb_eval_user_data;
  1485. };
  1486. struct llama_layer {
  1487. // normalization
  1488. struct ggml_tensor * attn_norm;
  1489. struct ggml_tensor * attn_norm_b;
  1490. struct ggml_tensor * attn_norm_2;
  1491. struct ggml_tensor * attn_norm_2_b;
  1492. struct ggml_tensor * attn_q_norm;
  1493. struct ggml_tensor * attn_q_norm_b;
  1494. struct ggml_tensor * attn_k_norm;
  1495. struct ggml_tensor * attn_k_norm_b;
  1496. struct ggml_tensor * attn_out_norm;
  1497. struct ggml_tensor * attn_out_norm_b;
  1498. // attention
  1499. struct ggml_tensor * wq;
  1500. struct ggml_tensor * wk;
  1501. struct ggml_tensor * wv;
  1502. struct ggml_tensor * wo;
  1503. struct ggml_tensor * wqkv;
  1504. // attention bias
  1505. struct ggml_tensor * bq;
  1506. struct ggml_tensor * bk;
  1507. struct ggml_tensor * bv;
  1508. struct ggml_tensor * bo;
  1509. struct ggml_tensor * bqkv;
  1510. // normalization
  1511. struct ggml_tensor * ffn_norm;
  1512. struct ggml_tensor * ffn_norm_b;
  1513. struct ggml_tensor * layer_out_norm;
  1514. struct ggml_tensor * layer_out_norm_b;
  1515. // ff
  1516. struct ggml_tensor * ffn_gate; // w1
  1517. struct ggml_tensor * ffn_down; // w2
  1518. struct ggml_tensor * ffn_up; // w3
  1519. // ff MoE
  1520. struct ggml_tensor * ffn_gate_inp;
  1521. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1522. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1523. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1524. // ff bias
  1525. struct ggml_tensor * ffn_down_b; // b2
  1526. struct ggml_tensor * ffn_up_b; // b3
  1527. struct ggml_tensor * ffn_act;
  1528. };
  1529. struct llama_kv_cell {
  1530. llama_pos pos = -1;
  1531. llama_pos delta = 0;
  1532. std::set<llama_seq_id> seq_id;
  1533. bool has_seq_id(const llama_seq_id & id) const {
  1534. return seq_id.find(id) != seq_id.end();
  1535. }
  1536. bool is_empty() const {
  1537. return seq_id.empty();
  1538. }
  1539. bool is_same_seq(const llama_kv_cell & other) const {
  1540. return seq_id == other.seq_id;
  1541. }
  1542. };
  1543. // ring-buffer of cached KV data
  1544. struct llama_kv_cache {
  1545. bool has_shift = false;
  1546. bool do_defrag = false;
  1547. // Note: The value of head isn't only used to optimize searching
  1548. // for a free KV slot. llama_decode_internal also uses it, so it
  1549. // cannot be freely changed after a slot has been allocated.
  1550. uint32_t head = 0;
  1551. uint32_t size = 0;
  1552. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1553. // computed before each graph build
  1554. uint32_t n = 0;
  1555. ggml_type type_k = GGML_TYPE_F16;
  1556. ggml_type type_v = GGML_TYPE_F16;
  1557. std::vector<llama_kv_cell> cells;
  1558. std::vector<struct ggml_tensor *> k_l; // per layer
  1559. std::vector<struct ggml_tensor *> v_l;
  1560. std::vector<struct ggml_context *> ctxs;
  1561. std::vector<ggml_backend_buffer_t> bufs;
  1562. size_t total_size() const {
  1563. size_t size = 0;
  1564. for (ggml_backend_buffer_t buf : bufs) {
  1565. size += ggml_backend_buffer_get_size(buf);
  1566. }
  1567. return size;
  1568. }
  1569. ~llama_kv_cache() {
  1570. for (struct ggml_context * ctx : ctxs) {
  1571. ggml_free(ctx);
  1572. }
  1573. for (ggml_backend_buffer_t buf : bufs) {
  1574. ggml_backend_buffer_free(buf);
  1575. }
  1576. }
  1577. };
  1578. struct llama_vocab {
  1579. using id = int32_t;
  1580. using token = std::string;
  1581. using ttype = llama_token_type;
  1582. struct token_data {
  1583. token text;
  1584. float score;
  1585. ttype type;
  1586. };
  1587. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1588. std::unordered_map<token, id> token_to_id;
  1589. std::vector<token_data> id_to_token;
  1590. std::unordered_map<token, id> special_tokens_cache;
  1591. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1592. // default LLaMA special tokens
  1593. id special_bos_id = 1;
  1594. id special_eos_id = 2;
  1595. id special_unk_id = 0;
  1596. id special_sep_id = -1;
  1597. id special_pad_id = -1;
  1598. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1599. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1600. id linefeed_id = 13;
  1601. id special_prefix_id = 32007;
  1602. id special_middle_id = 32009;
  1603. id special_suffix_id = 32008;
  1604. id special_eot_id = 32010;
  1605. bool add_space_prefix = true;
  1606. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1607. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1608. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1609. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1610. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1611. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1612. if (it == bpe_ranks.end()) {
  1613. return -1;
  1614. }
  1615. return it->second;
  1616. }
  1617. };
  1618. struct llama_model {
  1619. e_model type = MODEL_UNKNOWN;
  1620. llm_arch arch = LLM_ARCH_UNKNOWN;
  1621. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1622. std::string name = "n/a";
  1623. llama_hparams hparams = {};
  1624. llama_vocab vocab;
  1625. struct ggml_tensor * tok_embd;
  1626. struct ggml_tensor * type_embd;
  1627. struct ggml_tensor * pos_embd;
  1628. struct ggml_tensor * tok_norm;
  1629. struct ggml_tensor * tok_norm_b;
  1630. struct ggml_tensor * output_norm;
  1631. struct ggml_tensor * output_norm_b;
  1632. struct ggml_tensor * output;
  1633. struct ggml_tensor * output_b;
  1634. std::vector<llama_layer> layers;
  1635. llama_split_mode split_mode;
  1636. int main_gpu;
  1637. int n_gpu_layers;
  1638. // gguf metadata
  1639. std::unordered_map<std::string, std::string> gguf_kv;
  1640. // layer -> buffer type mapping
  1641. struct layer_buft {
  1642. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1643. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1644. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1645. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1646. ggml_backend_buffer_type_t buft; // everything else
  1647. };
  1648. layer_buft buft_input;
  1649. layer_buft buft_output;
  1650. std::vector<layer_buft> buft_layer;
  1651. // contexts where the model tensors metadata is stored
  1652. std::vector<struct ggml_context *> ctxs;
  1653. // the model memory buffers for the tensor data
  1654. std::vector<ggml_backend_buffer_t> bufs;
  1655. // model memory mapped file
  1656. std::unique_ptr<llama_mmap> mapping;
  1657. // objects representing data potentially being locked in memory
  1658. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1659. llama_mlock mlock_mmap;
  1660. // for quantize-stats only
  1661. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1662. int64_t t_load_us = 0;
  1663. int64_t t_start_us = 0;
  1664. ~llama_model() {
  1665. for (struct ggml_context * ctx : ctxs) {
  1666. ggml_free(ctx);
  1667. }
  1668. for (ggml_backend_buffer_t buf : bufs) {
  1669. ggml_backend_buffer_free(buf);
  1670. }
  1671. }
  1672. };
  1673. struct llama_context {
  1674. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1675. ~llama_context() {
  1676. ggml_backend_sched_free(sched);
  1677. for (ggml_backend_t backend : backends) {
  1678. ggml_backend_free(backend);
  1679. }
  1680. #ifdef GGML_USE_VULKAN
  1681. ggml_vk_free_cpu_assist();
  1682. #endif
  1683. ggml_backend_buffer_free(buf_input);
  1684. ggml_free(ctx_input);
  1685. }
  1686. llama_cparams cparams;
  1687. std::vector<ggml_backend_t> backends;
  1688. #ifdef GGML_USE_METAL
  1689. ggml_backend_t backend_metal = nullptr;
  1690. #endif
  1691. ggml_backend_t backend_cpu = nullptr;
  1692. const llama_model & model;
  1693. // key + value cache for the self attention
  1694. struct llama_kv_cache kv_self;
  1695. std::mt19937 rng;
  1696. bool has_evaluated_once = false;
  1697. int64_t t_start_us;
  1698. int64_t t_load_us;
  1699. int64_t t_sample_us = 0;
  1700. int64_t t_p_eval_us = 0;
  1701. int64_t t_eval_us = 0;
  1702. int32_t n_sample = 0; // number of tokens sampled
  1703. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1704. int32_t n_eval = 0; // number of eval calls
  1705. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1706. std::vector<float> logits;
  1707. #ifndef NDEBUG
  1708. // guard against access to unset logits
  1709. std::vector<bool> logits_valid;
  1710. #endif
  1711. bool logits_all = false;
  1712. // input embedding (1-dimensional array: [n_embd])
  1713. std::vector<float> embedding;
  1714. // memory buffers used to evaluate the model
  1715. std::vector<uint8_t> buf_compute_meta;
  1716. ggml_backend_sched_t sched = nullptr;
  1717. // input tensors
  1718. ggml_backend_buffer_t buf_input = nullptr;
  1719. ggml_context * ctx_input = nullptr;
  1720. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1721. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1722. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1723. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1724. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1725. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1726. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1727. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1728. #ifdef GGML_USE_MPI
  1729. ggml_mpi_context * ctx_mpi = NULL;
  1730. #endif
  1731. };
  1732. //
  1733. // kv cache helpers
  1734. //
  1735. static bool llama_kv_cache_init(
  1736. struct llama_kv_cache & cache,
  1737. const llama_model & model,
  1738. ggml_type type_k,
  1739. ggml_type type_v,
  1740. uint32_t n_ctx,
  1741. bool offload) {
  1742. const struct llama_hparams & hparams = model.hparams;
  1743. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1744. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1745. const int64_t n_layer = hparams.n_layer;
  1746. cache.has_shift = false;
  1747. cache.head = 0;
  1748. cache.size = n_ctx;
  1749. cache.used = 0;
  1750. cache.type_k = type_k;
  1751. cache.type_v = type_v;
  1752. cache.cells.clear();
  1753. cache.cells.resize(n_ctx);
  1754. #ifdef GGML_USE_CLBLAST
  1755. offload = false;
  1756. #endif
  1757. // count used buffer types
  1758. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1759. if (offload) {
  1760. for (int64_t i = 0; i < n_layer; ++i) {
  1761. buft_layer_count[model.buft_layer[i].buft]++;
  1762. }
  1763. } else {
  1764. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1765. }
  1766. // create a context for each buffer type
  1767. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1768. for (auto & it : buft_layer_count) {
  1769. int n_layers = it.second;
  1770. struct ggml_init_params params = {
  1771. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1772. /*.mem_buffer =*/ NULL,
  1773. /*.no_alloc =*/ true,
  1774. };
  1775. ggml_context * ctx = ggml_init(params);
  1776. if (!ctx) {
  1777. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1778. return false;
  1779. }
  1780. ctx_map[it.first] = ctx;
  1781. cache.ctxs.push_back(ctx);
  1782. }
  1783. cache.k_l.reserve(n_layer);
  1784. cache.v_l.reserve(n_layer);
  1785. for (int i = 0; i < (int) n_layer; i++) {
  1786. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1787. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*n_ctx);
  1788. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*n_ctx);
  1789. ggml_format_name(k, "cache_k_l%d", i);
  1790. ggml_format_name(v, "cache_v_l%d", i);
  1791. cache.k_l.push_back(k);
  1792. cache.v_l.push_back(v);
  1793. }
  1794. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1795. for (auto it : ctx_map) {
  1796. ggml_backend_buffer_type_t buft = it.first;
  1797. ggml_context * ctx = it.second;
  1798. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1799. if (!buf) {
  1800. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1801. return false;
  1802. }
  1803. ggml_backend_buffer_clear(buf, 0);
  1804. 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);
  1805. cache.bufs.push_back(buf);
  1806. }
  1807. return true;
  1808. }
  1809. // find an empty slot of size "n_tokens" in the cache
  1810. // updates the cache head
  1811. // Note: On success, it's important that cache.head points
  1812. // to the first cell of the slot.
  1813. static bool llama_kv_cache_find_slot(
  1814. struct llama_kv_cache & cache,
  1815. const struct llama_batch & batch) {
  1816. const uint32_t n_ctx = cache.size;
  1817. const uint32_t n_tokens = batch.n_tokens;
  1818. if (n_tokens > n_ctx) {
  1819. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1820. return false;
  1821. }
  1822. uint32_t n_tested = 0;
  1823. while (true) {
  1824. if (cache.head + n_tokens > n_ctx) {
  1825. n_tested += n_ctx - cache.head;
  1826. cache.head = 0;
  1827. continue;
  1828. }
  1829. bool found = true;
  1830. for (uint32_t i = 0; i < n_tokens; i++) {
  1831. if (cache.cells[cache.head + i].pos >= 0) {
  1832. found = false;
  1833. cache.head += i + 1;
  1834. n_tested += i + 1;
  1835. break;
  1836. }
  1837. }
  1838. if (found) {
  1839. break;
  1840. }
  1841. if (n_tested >= n_ctx) {
  1842. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1843. return false;
  1844. }
  1845. }
  1846. for (uint32_t i = 0; i < n_tokens; i++) {
  1847. cache.cells[cache.head + i].pos = batch.pos[i];
  1848. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1849. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1850. }
  1851. }
  1852. cache.used += n_tokens;
  1853. return true;
  1854. }
  1855. // find how many cells are currently in use
  1856. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1857. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1858. if (cache.cells[i].pos >= 0 && !cache.cells[i].is_empty()) {
  1859. return i + 1;
  1860. }
  1861. }
  1862. return 0;
  1863. }
  1864. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1865. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1866. cache.cells[i].pos = -1;
  1867. cache.cells[i].seq_id.clear();
  1868. }
  1869. cache.head = 0;
  1870. cache.used = 0;
  1871. }
  1872. static void llama_kv_cache_seq_rm(
  1873. struct llama_kv_cache & cache,
  1874. llama_seq_id seq_id,
  1875. llama_pos p0,
  1876. llama_pos p1) {
  1877. uint32_t new_head = cache.size;
  1878. if (p0 < 0) p0 = 0;
  1879. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1880. for (uint32_t i = 0; i < cache.size; ++i) {
  1881. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1882. if (seq_id < 0) {
  1883. cache.cells[i].seq_id.clear();
  1884. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1885. cache.cells[i].seq_id.erase(seq_id);
  1886. } else {
  1887. continue;
  1888. }
  1889. if (cache.cells[i].is_empty()) {
  1890. // keep count of the number of used cells
  1891. if (cache.cells[i].pos >= 0) cache.used--;
  1892. cache.cells[i].pos = -1;
  1893. if (new_head == cache.size) new_head = i;
  1894. }
  1895. }
  1896. }
  1897. // If we freed up a slot, set head to it so searching can start there.
  1898. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1899. }
  1900. static void llama_kv_cache_seq_cp(
  1901. struct llama_kv_cache & cache,
  1902. llama_seq_id seq_id_src,
  1903. llama_seq_id seq_id_dst,
  1904. llama_pos p0,
  1905. llama_pos p1) {
  1906. if (p0 < 0) p0 = 0;
  1907. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1908. cache.head = 0;
  1909. for (uint32_t i = 0; i < cache.size; ++i) {
  1910. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1911. cache.cells[i].seq_id.insert(seq_id_dst);
  1912. }
  1913. }
  1914. }
  1915. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1916. uint32_t new_head = cache.size;
  1917. for (uint32_t i = 0; i < cache.size; ++i) {
  1918. if (!cache.cells[i].has_seq_id(seq_id)) {
  1919. if (cache.cells[i].pos >= 0) cache.used--;
  1920. cache.cells[i].pos = -1;
  1921. cache.cells[i].seq_id.clear();
  1922. if (new_head == cache.size) new_head = i;
  1923. } else {
  1924. cache.cells[i].seq_id.clear();
  1925. cache.cells[i].seq_id.insert(seq_id);
  1926. }
  1927. }
  1928. // If we freed up a slot, set head to it so searching can start there.
  1929. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1930. }
  1931. static void llama_kv_cache_seq_add(
  1932. struct llama_kv_cache & cache,
  1933. llama_seq_id seq_id,
  1934. llama_pos p0,
  1935. llama_pos p1,
  1936. llama_pos delta) {
  1937. uint32_t new_head = cache.size;
  1938. if (p0 < 0) p0 = 0;
  1939. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1940. for (uint32_t i = 0; i < cache.size; ++i) {
  1941. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1942. cache.has_shift = true;
  1943. cache.cells[i].pos += delta;
  1944. cache.cells[i].delta += delta;
  1945. if (cache.cells[i].pos < 0) {
  1946. if (!cache.cells[i].is_empty()) {
  1947. cache.used--;
  1948. }
  1949. cache.cells[i].pos = -1;
  1950. cache.cells[i].seq_id.clear();
  1951. if (new_head == cache.size) {
  1952. new_head = i;
  1953. }
  1954. }
  1955. }
  1956. }
  1957. // If we freed up a slot, set head to it so searching can start there.
  1958. // Otherwise we just start the next search from the beginning.
  1959. cache.head = new_head != cache.size ? new_head : 0;
  1960. }
  1961. static void llama_kv_cache_seq_div(
  1962. struct llama_kv_cache & cache,
  1963. llama_seq_id seq_id,
  1964. llama_pos p0,
  1965. llama_pos p1,
  1966. int d) {
  1967. if (p0 < 0) p0 = 0;
  1968. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1969. for (uint32_t i = 0; i < cache.size; ++i) {
  1970. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1971. cache.has_shift = true;
  1972. {
  1973. llama_pos p_old = cache.cells[i].pos;
  1974. cache.cells[i].pos /= d;
  1975. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1976. }
  1977. }
  1978. }
  1979. }
  1980. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1981. llama_pos result = 0;
  1982. for (uint32_t i = 0; i < cache.size; ++i) {
  1983. if (cache.cells[i].has_seq_id(seq_id)) {
  1984. result = std::max(result, cache.cells[i].pos);
  1985. }
  1986. }
  1987. return result;
  1988. }
  1989. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  1990. cache.do_defrag = true;
  1991. }
  1992. //
  1993. // model loading and saving
  1994. //
  1995. enum llama_fver {
  1996. GGUF_FILE_VERSION_V1 = 1,
  1997. GGUF_FILE_VERSION_V2 = 2,
  1998. GGUF_FILE_VERSION_V3 = 3,
  1999. };
  2000. static const char * llama_file_version_name(llama_fver version) {
  2001. switch (version) {
  2002. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2003. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2004. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2005. }
  2006. return "unknown";
  2007. }
  2008. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2009. char buf[256];
  2010. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2011. for (size_t i = 1; i < ne.size(); i++) {
  2012. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2013. }
  2014. return buf;
  2015. }
  2016. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2017. char buf[256];
  2018. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2019. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2020. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2021. }
  2022. return buf;
  2023. }
  2024. namespace GGUFMeta {
  2025. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2026. struct GKV_Base_Type {
  2027. static constexpr gguf_type gt = gt_;
  2028. static T getter(const gguf_context * ctx, const int kid) {
  2029. return gfun(ctx, kid);
  2030. }
  2031. };
  2032. template<typename T> struct GKV_Base;
  2033. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2034. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2035. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2036. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2037. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2038. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2039. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2040. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2041. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2042. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2043. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2044. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2045. template<> struct GKV_Base<std::string> {
  2046. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2047. static std::string getter(const gguf_context * ctx, const int kid) {
  2048. return gguf_get_val_str(ctx, kid);
  2049. }
  2050. };
  2051. struct ArrayInfo {
  2052. const gguf_type gt;
  2053. const size_t length;
  2054. const void * data;
  2055. };
  2056. template<> struct GKV_Base<ArrayInfo> {
  2057. public:
  2058. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2059. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2060. return ArrayInfo {
  2061. gguf_get_arr_type(ctx, k),
  2062. size_t(gguf_get_arr_n(ctx, k)),
  2063. gguf_get_arr_data(ctx, k),
  2064. };
  2065. }
  2066. };
  2067. template<typename T>
  2068. class GKV : public GKV_Base<T> {
  2069. GKV() = delete;
  2070. public:
  2071. static T get_kv(const gguf_context * ctx, const int k) {
  2072. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2073. if (kt != GKV::gt) {
  2074. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2075. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2076. }
  2077. return GKV::getter(ctx, k);
  2078. }
  2079. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2080. switch (ty) {
  2081. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2082. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2083. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2084. }
  2085. return "unknown";
  2086. }
  2087. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2088. if (!ovrd) { return false; }
  2089. if (ovrd->tag == expected_type) {
  2090. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2091. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2092. switch (ovrd->tag) {
  2093. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2094. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2095. } break;
  2096. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2097. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2098. } break;
  2099. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2100. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2101. } break;
  2102. default:
  2103. // Shouldn't be possible to end up here, but just in case...
  2104. throw std::runtime_error(
  2105. format("Unsupported attempt to override %s type for metadata key %s\n",
  2106. override_type_to_str(ovrd->tag), ovrd->key));
  2107. }
  2108. return true;
  2109. }
  2110. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2111. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2112. return false;
  2113. }
  2114. template<typename OT>
  2115. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2116. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2117. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2118. target = ovrd->bool_value;
  2119. return true;
  2120. }
  2121. return false;
  2122. }
  2123. template<typename OT>
  2124. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2125. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2126. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2127. target = ovrd->int_value;
  2128. return true;
  2129. }
  2130. return false;
  2131. }
  2132. template<typename OT>
  2133. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2134. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2135. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2136. target = ovrd->float_value;
  2137. return true;
  2138. }
  2139. return false;
  2140. }
  2141. template<typename OT>
  2142. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2143. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2144. (void)target;
  2145. (void)ovrd;
  2146. if (!ovrd) { return false; }
  2147. // Currently, we should never end up here so it would be a bug if we do.
  2148. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2149. ovrd ? ovrd->key : "NULL"));
  2150. }
  2151. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2152. if (try_override<T>(target, ovrd)) {
  2153. return true;
  2154. }
  2155. if (k < 0) { return false; }
  2156. target = get_kv(ctx, k);
  2157. return true;
  2158. }
  2159. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2160. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2161. }
  2162. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2163. return set(ctx, key.c_str(), target, ovrd);
  2164. }
  2165. };
  2166. }
  2167. struct llama_model_loader {
  2168. int n_kv = 0;
  2169. int n_tensors = 0;
  2170. int n_created = 0;
  2171. int64_t n_elements = 0;
  2172. size_t n_bytes = 0;
  2173. bool use_mmap = false;
  2174. llama_file file;
  2175. llama_ftype ftype;
  2176. llama_fver fver;
  2177. std::unique_ptr<llama_mmap> mapping;
  2178. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2179. struct gguf_context * ctx_gguf = NULL;
  2180. struct ggml_context * ctx_meta = NULL;
  2181. std::string arch_name;
  2182. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2183. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2184. int trace = 0;
  2185. if (getenv("LLAMA_TRACE")) {
  2186. trace = atoi(getenv("LLAMA_TRACE"));
  2187. }
  2188. struct gguf_init_params params = {
  2189. /*.no_alloc = */ true,
  2190. /*.ctx = */ &ctx_meta,
  2191. };
  2192. if (param_overrides_p != nullptr) {
  2193. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2194. kv_overrides.insert({std::string(p->key), *p});
  2195. }
  2196. }
  2197. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2198. if (!ctx_gguf) {
  2199. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2200. }
  2201. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2202. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2203. n_kv = gguf_get_n_kv(ctx_gguf);
  2204. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2205. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2206. for (int i = 0; i < n_tensors; i++) {
  2207. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2208. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2209. n_elements += ggml_nelements(t);
  2210. n_bytes += ggml_nbytes(t);
  2211. }
  2212. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2213. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2214. // determine file type based on the number of tensors for each quantization and print meta data
  2215. // TODO: make optional
  2216. {
  2217. std::map<enum ggml_type, uint32_t> n_type;
  2218. uint32_t n_type_max = 0;
  2219. enum ggml_type type_max = GGML_TYPE_F32;
  2220. for (int i = 0; i < n_tensors; i++) {
  2221. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2222. n_type[type]++;
  2223. if (n_type_max < n_type[type]) {
  2224. n_type_max = n_type[type];
  2225. type_max = type;
  2226. }
  2227. if (trace > 0) {
  2228. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2229. 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());
  2230. }
  2231. }
  2232. switch (type_max) {
  2233. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2234. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2235. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2236. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2237. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2238. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2239. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2240. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2241. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2242. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2243. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2244. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2245. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2246. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2247. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2248. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2249. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2250. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2251. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2252. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2253. default:
  2254. {
  2255. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2256. ftype = LLAMA_FTYPE_ALL_F32;
  2257. } break;
  2258. }
  2259. // this is a way to mark that we have "guessed" the file type
  2260. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2261. {
  2262. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2263. if (kid >= 0) {
  2264. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2265. }
  2266. }
  2267. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2268. for (int i = 0; i < n_kv; i++) {
  2269. const char * name = gguf_get_key(ctx_gguf, i);
  2270. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2271. const std::string type_name =
  2272. type == GGUF_TYPE_ARRAY
  2273. ? 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))
  2274. : gguf_type_name(type);
  2275. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2276. const size_t MAX_VALUE_LEN = 40;
  2277. if (value.size() > MAX_VALUE_LEN) {
  2278. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2279. }
  2280. replace_all(value, "\n", "\\n");
  2281. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2282. }
  2283. // print type counts
  2284. for (auto & kv : n_type) {
  2285. if (kv.second == 0) {
  2286. continue;
  2287. }
  2288. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2289. }
  2290. }
  2291. if (!llama_mmap::SUPPORTED) {
  2292. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2293. use_mmap = false;
  2294. }
  2295. this->use_mmap = use_mmap;
  2296. }
  2297. ~llama_model_loader() {
  2298. if (ctx_gguf) {
  2299. gguf_free(ctx_gguf);
  2300. }
  2301. if (ctx_meta) {
  2302. ggml_free(ctx_meta);
  2303. }
  2304. }
  2305. template<typename T>
  2306. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2307. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2308. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2309. if (kid < 0) {
  2310. if (required) {
  2311. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2312. }
  2313. return false;
  2314. }
  2315. struct GGUFMeta::ArrayInfo arr_info =
  2316. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2317. result = arr_info.length;
  2318. return true;
  2319. }
  2320. template<typename T>
  2321. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2322. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2323. return get_arr_n(llm_kv(kid), result, required);
  2324. }
  2325. template<typename T>
  2326. bool get_key(const std::string & key, T & result, const bool required = true) {
  2327. auto it = kv_overrides.find(key);
  2328. const struct llama_model_kv_override * override =
  2329. it != kv_overrides.end() ? &it->second : nullptr;
  2330. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2331. if (required && !found) {
  2332. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2333. }
  2334. return found;
  2335. }
  2336. template<typename T>
  2337. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2338. return get_key(llm_kv(kid), result, required);
  2339. }
  2340. std::string get_arch_name() const {
  2341. return arch_name;
  2342. }
  2343. enum llm_arch get_arch() const {
  2344. return llm_kv.arch;
  2345. }
  2346. const char * get_tensor_name(int i) const {
  2347. return gguf_get_tensor_name(ctx_gguf, i);
  2348. }
  2349. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2350. return ggml_get_tensor(ctx_meta, name);
  2351. }
  2352. struct ggml_tensor * get_tensor_meta(int i) const {
  2353. return get_tensor_meta(get_tensor_name(i));
  2354. }
  2355. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2356. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2357. ggml_set_name(tensor, ggml_get_name(meta));
  2358. n_created++;
  2359. return tensor;
  2360. }
  2361. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2362. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2363. if (cur == NULL) {
  2364. if (!required) {
  2365. return NULL;
  2366. }
  2367. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2368. }
  2369. {
  2370. bool is_ok = true;
  2371. for (size_t i = 0; i < ne.size(); ++i) {
  2372. if (ne[i] != cur->ne[i]) {
  2373. is_ok = false;
  2374. break;
  2375. }
  2376. }
  2377. if (!is_ok) {
  2378. throw std::runtime_error(
  2379. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2380. __func__, name.c_str(),
  2381. llama_format_tensor_shape(ne).c_str(),
  2382. llama_format_tensor_shape(cur).c_str()));
  2383. }
  2384. }
  2385. return create_tensor_for(ctx, cur);
  2386. }
  2387. void done_getting_tensors() const {
  2388. if (n_created != n_tensors) {
  2389. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2390. }
  2391. }
  2392. size_t file_offset(const char * name) const {
  2393. const int idx = gguf_find_tensor(ctx_gguf, name);
  2394. if (idx < 0) {
  2395. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2396. }
  2397. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2398. }
  2399. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2400. // prefetch the whole file - all the data is needed anyway
  2401. if (use_mmap) {
  2402. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2403. }
  2404. // compute the total size of all tensors for progress reporting
  2405. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2406. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2407. size_data += ggml_nbytes(cur);
  2408. }
  2409. if (use_mmap && mapping) {
  2410. if (lmlock) {
  2411. lmlock->init(mapping->addr);
  2412. }
  2413. mmap_used_first = mapping->size;
  2414. }
  2415. }
  2416. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2417. GGML_ASSERT(mapping);
  2418. *first = mapping->size;
  2419. *last = 0;
  2420. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2421. const size_t offs = file_offset(ggml_get_name(tensor));
  2422. *first = std::min(*first, offs);
  2423. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2424. }
  2425. }
  2426. // for backwards compatibility, does not support ggml-backend
  2427. void load_data_for(struct ggml_tensor * cur) const {
  2428. const size_t offs = file_offset(ggml_get_name(cur));
  2429. if (use_mmap && mapping) {
  2430. if (cur->data == nullptr) {
  2431. cur->data = (uint8_t *)mapping->addr + offs;
  2432. } else {
  2433. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2434. }
  2435. } else {
  2436. GGML_ASSERT(cur->data != nullptr);
  2437. file.seek(offs, SEEK_SET);
  2438. file.read_raw(cur->data, ggml_nbytes(cur));
  2439. }
  2440. }
  2441. size_t size_done = 0;
  2442. size_t size_data = 0;
  2443. size_t mmap_used_first = -1;
  2444. size_t mmap_used_last = 0;
  2445. // Returns false if cancelled by progress_callback
  2446. 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) {
  2447. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2448. std::vector<no_init<uint8_t>> read_buf;
  2449. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2450. if (progress_callback) {
  2451. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2452. return false;
  2453. }
  2454. }
  2455. const size_t offs = file_offset(ggml_get_name(cur));
  2456. if (use_mmap && mapping) {
  2457. if (buf_mmap && cur->data == nullptr) {
  2458. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2459. if (lmlock) {
  2460. lmlock->grow_to(offs + ggml_nbytes(cur));
  2461. }
  2462. mmap_used_first = std::min(mmap_used_first, offs);
  2463. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2464. } else {
  2465. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2466. }
  2467. } else {
  2468. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2469. file.seek(offs, SEEK_SET);
  2470. file.read_raw(cur->data, ggml_nbytes(cur));
  2471. } else {
  2472. read_buf.resize(ggml_nbytes(cur));
  2473. file.seek(offs, SEEK_SET);
  2474. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2475. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2476. }
  2477. }
  2478. size_done += ggml_nbytes(cur);
  2479. }
  2480. // check if this is the last call and do final cleanup
  2481. if (size_done >= size_data) {
  2482. // unmap offloaded tensors and metadata
  2483. if (use_mmap && mapping) {
  2484. mapping->unmap_fragment(0, mmap_used_first);
  2485. if (mmap_used_last != 0) {
  2486. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2487. }
  2488. }
  2489. if (progress_callback) {
  2490. // Even though the model is done loading, we still honor
  2491. // cancellation since we need to free allocations.
  2492. return progress_callback(1.0f, progress_callback_user_data);
  2493. }
  2494. }
  2495. return true;
  2496. }
  2497. };
  2498. template<>
  2499. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2500. uint32_t tmp;
  2501. const bool found = get_key(kid, tmp, required);
  2502. result = (enum llama_pooling_type) tmp;
  2503. return found;
  2504. }
  2505. //
  2506. // load LLaMA models
  2507. //
  2508. static const char * llama_model_arch_name(llm_arch arch) {
  2509. auto it = LLM_ARCH_NAMES.find(arch);
  2510. if (it == LLM_ARCH_NAMES.end()) {
  2511. return "unknown";
  2512. }
  2513. return it->second;
  2514. }
  2515. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2516. if (ftype & LLAMA_FTYPE_GUESSED) {
  2517. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2518. }
  2519. switch (ftype) {
  2520. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2521. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2522. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2523. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2524. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2525. return "Q4_1, some F16";
  2526. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2527. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2528. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2529. // K-quants
  2530. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2531. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2532. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2533. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2534. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2535. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2536. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2537. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2538. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2539. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2540. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2541. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2542. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2543. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2544. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2545. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2546. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2547. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2548. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2549. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2550. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2551. default: return "unknown, may not work";
  2552. }
  2553. }
  2554. static const char * llama_model_type_name(e_model type) {
  2555. switch (type) {
  2556. case MODEL_22M: return "22M";
  2557. case MODEL_33M: return "33M";
  2558. case MODEL_109M: return "109M";
  2559. case MODEL_137M: return "137M";
  2560. case MODEL_0_5B: return "0.5B";
  2561. case MODEL_1B: return "1B";
  2562. case MODEL_2B: return "2B";
  2563. case MODEL_3B: return "3B";
  2564. case MODEL_7B: return "7B";
  2565. case MODEL_8B: return "8B";
  2566. case MODEL_13B: return "13B";
  2567. case MODEL_14B: return "14B";
  2568. case MODEL_15B: return "15B";
  2569. case MODEL_20B: return "20B";
  2570. case MODEL_30B: return "30B";
  2571. case MODEL_34B: return "34B";
  2572. case MODEL_40B: return "40B";
  2573. case MODEL_65B: return "65B";
  2574. case MODEL_70B: return "70B";
  2575. case MODEL_SMALL: return "0.1B";
  2576. case MODEL_MEDIUM: return "0.4B";
  2577. case MODEL_LARGE: return "0.8B";
  2578. case MODEL_XL: return "1.5B";
  2579. default: return "?B";
  2580. }
  2581. }
  2582. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2583. switch (type) {
  2584. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2585. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2586. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2587. default: return "unknown";
  2588. }
  2589. }
  2590. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2591. model.arch = ml.get_arch();
  2592. if (model.arch == LLM_ARCH_UNKNOWN) {
  2593. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2594. }
  2595. }
  2596. static void llm_load_hparams(
  2597. llama_model_loader & ml,
  2598. llama_model & model) {
  2599. auto & hparams = model.hparams;
  2600. const gguf_context * ctx = ml.ctx_gguf;
  2601. // get metadata as string
  2602. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2603. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2604. if (type == GGUF_TYPE_ARRAY) {
  2605. continue;
  2606. }
  2607. const char * name = gguf_get_key(ctx, i);
  2608. const std::string value = gguf_kv_to_str(ctx, i);
  2609. model.gguf_kv.emplace(name, value);
  2610. }
  2611. // get general kv
  2612. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2613. // get hparams kv
  2614. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2615. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2616. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2617. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2618. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2619. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2620. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2621. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2622. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2623. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2624. if (hparams.n_expert > 0) {
  2625. GGML_ASSERT(hparams.n_expert_used > 0);
  2626. } else {
  2627. GGML_ASSERT(hparams.n_expert_used == 0);
  2628. }
  2629. // n_head_kv is optional, default to n_head
  2630. hparams.n_head_kv = hparams.n_head;
  2631. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2632. bool rope_finetuned = false;
  2633. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2634. hparams.rope_finetuned = rope_finetuned;
  2635. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2636. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2637. // rope_freq_base (optional)
  2638. hparams.rope_freq_base_train = 10000.0f;
  2639. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2640. std::string rope_scaling("linear");
  2641. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2642. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2643. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2644. // rope_freq_scale (inverse of the kv) is optional
  2645. float ropescale = 0.0f;
  2646. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2647. // try the old key name
  2648. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2649. }
  2650. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2651. // sanity check for n_rot (optional)
  2652. {
  2653. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2654. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2655. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2656. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2657. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2658. }
  2659. }
  2660. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2661. // gpt-j n_rot = rotary_dim
  2662. }
  2663. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2664. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2665. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2666. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2667. // arch-specific KVs
  2668. switch (model.arch) {
  2669. case LLM_ARCH_LLAMA:
  2670. {
  2671. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2672. switch (hparams.n_layer) {
  2673. case 22: model.type = e_model::MODEL_1B; break;
  2674. case 26: model.type = e_model::MODEL_3B; break;
  2675. case 32: model.type = e_model::MODEL_7B; break;
  2676. case 40: model.type = e_model::MODEL_13B; break;
  2677. case 48: model.type = e_model::MODEL_34B; break;
  2678. case 60: model.type = e_model::MODEL_30B; break;
  2679. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2680. default: model.type = e_model::MODEL_UNKNOWN;
  2681. }
  2682. } break;
  2683. case LLM_ARCH_MINICPM:
  2684. {
  2685. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2686. switch (hparams.n_layer) {
  2687. case 40: model.type = e_model::MODEL_2B; break;
  2688. default: model.type = e_model::MODEL_UNKNOWN;
  2689. }
  2690. } break;
  2691. case LLM_ARCH_FALCON:
  2692. {
  2693. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2694. switch (hparams.n_layer) {
  2695. case 32: model.type = e_model::MODEL_7B; break;
  2696. case 60: model.type = e_model::MODEL_40B; break;
  2697. default: model.type = e_model::MODEL_UNKNOWN;
  2698. }
  2699. } break;
  2700. case LLM_ARCH_BAICHUAN:
  2701. {
  2702. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2703. switch (hparams.n_layer) {
  2704. case 32: model.type = e_model::MODEL_7B; break;
  2705. case 40: model.type = e_model::MODEL_13B; break;
  2706. default: model.type = e_model::MODEL_UNKNOWN;
  2707. }
  2708. if (model.type == e_model::MODEL_13B) {
  2709. // TODO: become GGUF KV parameter
  2710. hparams.f_max_alibi_bias = 8.0f;
  2711. }
  2712. } break;
  2713. case LLM_ARCH_STARCODER:
  2714. {
  2715. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2716. switch (hparams.n_layer) {
  2717. case 24: model.type = e_model::MODEL_1B; break;
  2718. case 36: model.type = e_model::MODEL_3B; break;
  2719. case 42: model.type = e_model::MODEL_7B; break;
  2720. case 40: model.type = e_model::MODEL_15B; break;
  2721. default: model.type = e_model::MODEL_UNKNOWN;
  2722. }
  2723. } break;
  2724. case LLM_ARCH_PERSIMMON:
  2725. {
  2726. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2727. switch (hparams.n_layer) {
  2728. case 36: model.type = e_model::MODEL_8B; break;
  2729. default: model.type = e_model::MODEL_UNKNOWN;
  2730. }
  2731. } break;
  2732. case LLM_ARCH_REFACT:
  2733. {
  2734. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2735. switch (hparams.n_layer) {
  2736. case 32: model.type = e_model::MODEL_1B; break;
  2737. default: model.type = e_model::MODEL_UNKNOWN;
  2738. }
  2739. // TODO: become GGUF KV parameter
  2740. hparams.f_max_alibi_bias = 8.0f;
  2741. } break;
  2742. case LLM_ARCH_BERT:
  2743. {
  2744. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2745. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2746. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2747. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2748. switch (hparams.n_layer) {
  2749. case 3:
  2750. model.type = e_model::MODEL_17M; break; // bge-micro
  2751. case 6:
  2752. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2753. case 12:
  2754. switch (hparams.n_embd) {
  2755. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2756. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2757. } break;
  2758. case 24:
  2759. model.type = e_model::MODEL_335M; break; // bge-large
  2760. }
  2761. } break;
  2762. case LLM_ARCH_NOMIC_BERT:
  2763. {
  2764. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2765. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2766. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2767. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2768. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2769. model.type = e_model::MODEL_137M;
  2770. }
  2771. } break;
  2772. case LLM_ARCH_BLOOM:
  2773. {
  2774. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2775. switch (hparams.n_layer) {
  2776. case 24: model.type = e_model::MODEL_1B; break;
  2777. case 30:
  2778. switch (hparams.n_embd) {
  2779. case 2560: model.type = e_model::MODEL_3B; break;
  2780. case 4096: model.type = e_model::MODEL_7B; break;
  2781. } break;
  2782. }
  2783. // TODO: become GGUF KV parameter
  2784. hparams.f_max_alibi_bias = 8.0f;
  2785. } break;
  2786. case LLM_ARCH_MPT:
  2787. {
  2788. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2789. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2790. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2791. switch (hparams.n_layer) {
  2792. case 32: model.type = e_model::MODEL_7B; break;
  2793. case 48: model.type = e_model::MODEL_30B; break;
  2794. default: model.type = e_model::MODEL_UNKNOWN;
  2795. }
  2796. } break;
  2797. case LLM_ARCH_STABLELM:
  2798. {
  2799. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2800. switch (hparams.n_layer) {
  2801. case 24: model.type = e_model::MODEL_1B; break;
  2802. case 32: model.type = e_model::MODEL_3B; break;
  2803. default: model.type = e_model::MODEL_UNKNOWN;
  2804. }
  2805. } break;
  2806. case LLM_ARCH_QWEN:
  2807. {
  2808. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2809. switch (hparams.n_layer) {
  2810. case 32: model.type = e_model::MODEL_7B; break;
  2811. case 40: model.type = e_model::MODEL_13B; break;
  2812. default: model.type = e_model::MODEL_UNKNOWN;
  2813. }
  2814. } break;
  2815. case LLM_ARCH_QWEN2:
  2816. {
  2817. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2818. switch (hparams.n_layer) {
  2819. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2820. case 32: model.type = e_model::MODEL_7B; break;
  2821. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2822. case 80: model.type = e_model::MODEL_70B; break;
  2823. default: model.type = e_model::MODEL_UNKNOWN;
  2824. }
  2825. } break;
  2826. case LLM_ARCH_PHI2:
  2827. {
  2828. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2829. switch (hparams.n_layer) {
  2830. case 24: model.type = e_model::MODEL_1B; break;
  2831. case 32: model.type = e_model::MODEL_3B; break;
  2832. default: model.type = e_model::MODEL_UNKNOWN;
  2833. }
  2834. } break;
  2835. case LLM_ARCH_PLAMO:
  2836. {
  2837. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2838. switch (hparams.n_layer) {
  2839. case 40: model.type = e_model::MODEL_13B; break;
  2840. default: model.type = e_model::MODEL_UNKNOWN;
  2841. }
  2842. } break;
  2843. case LLM_ARCH_GPT2:
  2844. {
  2845. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2846. switch (hparams.n_layer) {
  2847. case 12: model.type = e_model::MODEL_SMALL; break;
  2848. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2849. case 36: model.type = e_model::MODEL_LARGE; break;
  2850. case 48: model.type = e_model::MODEL_XL; break;
  2851. default: model.type = e_model::MODEL_UNKNOWN;
  2852. }
  2853. } break;
  2854. case LLM_ARCH_CODESHELL:
  2855. {
  2856. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2857. switch (hparams.n_layer) {
  2858. case 42: model.type = e_model::MODEL_SMALL; break;
  2859. default: model.type = e_model::MODEL_UNKNOWN;
  2860. }
  2861. } break;
  2862. case LLM_ARCH_ORION:
  2863. {
  2864. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2865. switch (hparams.n_layer) {
  2866. case 40: model.type = e_model::MODEL_14B; break;
  2867. default: model.type = e_model::MODEL_UNKNOWN;
  2868. }
  2869. } break;
  2870. case LLM_ARCH_INTERNLM2:
  2871. {
  2872. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2873. switch (hparams.n_layer) {
  2874. case 32: model.type = e_model::MODEL_7B; break;
  2875. case 48: model.type = e_model::MODEL_20B; break;
  2876. default: model.type = e_model::MODEL_UNKNOWN;
  2877. }
  2878. } break;
  2879. case LLM_ARCH_GEMMA:
  2880. {
  2881. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2882. switch (hparams.n_layer) {
  2883. case 18: model.type = e_model::MODEL_2B; break;
  2884. case 28: model.type = e_model::MODEL_7B; break;
  2885. default: model.type = e_model::MODEL_UNKNOWN;
  2886. }
  2887. } break;
  2888. default: (void)0;
  2889. }
  2890. model.ftype = ml.ftype;
  2891. if (hparams.f_max_alibi_bias > 0.0f) {
  2892. hparams.need_kq_pos = true;
  2893. }
  2894. hparams.rope_type = llama_rope_type(&model);
  2895. }
  2896. // TODO: This should probably be in llama.h
  2897. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2898. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2899. static void llm_load_vocab(
  2900. llama_model_loader & ml,
  2901. llama_model & model) {
  2902. auto & vocab = model.vocab;
  2903. struct gguf_context * ctx = ml.ctx_gguf;
  2904. const auto kv = LLM_KV(model.arch);
  2905. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2906. if (token_idx == -1) {
  2907. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2908. }
  2909. const float * scores = nullptr;
  2910. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2911. if (score_idx != -1) {
  2912. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2913. }
  2914. const int * toktypes = nullptr;
  2915. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2916. if (toktype_idx != -1) {
  2917. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2918. }
  2919. // determine vocab type
  2920. {
  2921. std::string tokenizer_name;
  2922. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2923. if (tokenizer_name == "llama") {
  2924. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2925. // default special tokens
  2926. vocab.special_bos_id = 1;
  2927. vocab.special_eos_id = 2;
  2928. vocab.special_unk_id = 0;
  2929. vocab.special_sep_id = -1;
  2930. vocab.special_pad_id = -1;
  2931. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2932. if (add_space_prefix_keyidx != -1) {
  2933. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2934. } // The default value of add_space_prefix is true.
  2935. } else if (tokenizer_name == "gpt2") {
  2936. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2937. // read bpe merges and populate bpe ranks
  2938. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2939. if (merges_keyidx == -1) {
  2940. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2941. }
  2942. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2943. for (int i = 0; i < n_merges; i++) {
  2944. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2945. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2946. std::string first;
  2947. std::string second;
  2948. const size_t pos = word.find(' ', 1);
  2949. if (pos != std::string::npos) {
  2950. first = word.substr(0, pos);
  2951. second = word.substr(pos + 1);
  2952. }
  2953. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2954. }
  2955. // default special tokens
  2956. vocab.special_bos_id = 11;
  2957. vocab.special_eos_id = 11;
  2958. vocab.special_unk_id = -1;
  2959. vocab.special_sep_id = -1;
  2960. vocab.special_pad_id = -1;
  2961. } else if (tokenizer_name == "bert") {
  2962. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  2963. // default special tokens
  2964. vocab.special_bos_id = 101;
  2965. vocab.special_eos_id = 102;
  2966. vocab.special_unk_id = 100;
  2967. vocab.special_sep_id = -1;
  2968. vocab.special_pad_id = -1;
  2969. vocab.add_space_prefix = false;
  2970. } else {
  2971. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2972. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2973. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2974. }
  2975. }
  2976. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2977. vocab.id_to_token.resize(n_vocab);
  2978. for (uint32_t i = 0; i < n_vocab; i++) {
  2979. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2980. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2981. vocab.token_to_id[word] = i;
  2982. auto & token_data = vocab.id_to_token[i];
  2983. token_data.text = std::move(word);
  2984. token_data.score = scores ? scores[i] : 0.0f;
  2985. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2986. }
  2987. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2988. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2989. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2990. try {
  2991. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2992. } catch (const std::exception & e) {
  2993. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  2994. vocab.linefeed_id = vocab.special_pad_id;
  2995. }
  2996. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  2997. vocab.linefeed_id = vocab.special_pad_id;
  2998. } else {
  2999. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3000. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3001. vocab.linefeed_id = ids[0];
  3002. }
  3003. // special tokens
  3004. {
  3005. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3006. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3007. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3008. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3009. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3010. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3011. };
  3012. for (const auto & it : special_token_types) {
  3013. const std::string & key = kv(std::get<0>(it));
  3014. int32_t & id = std::get<1>(it);
  3015. uint32_t new_id;
  3016. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3017. continue;
  3018. }
  3019. if (new_id >= vocab.id_to_token.size()) {
  3020. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3021. __func__, key.c_str(), new_id, id);
  3022. } else {
  3023. id = new_id;
  3024. }
  3025. }
  3026. // Handle add_bos_token and add_eos_token
  3027. {
  3028. bool temp = true;
  3029. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3030. vocab.special_add_bos = int(temp);
  3031. }
  3032. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3033. vocab.special_add_eos = int(temp);
  3034. }
  3035. }
  3036. }
  3037. // build special tokens cache
  3038. {
  3039. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3040. // and will always be correctly labeled in 'added_tokens.json' etc.
  3041. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3042. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3043. // are special tokens.
  3044. // From testing, this appears to correlate 1:1 with special tokens.
  3045. //
  3046. // Counting special tokens and verifying in only one direction
  3047. // is sufficient to detect difference in those two sets.
  3048. //
  3049. uint32_t special_tokens_count_by_type = 0;
  3050. uint32_t special_tokens_count_from_verification = 0;
  3051. bool special_tokens_definition_mismatch = false;
  3052. for (const auto & t : vocab.token_to_id) {
  3053. const auto & token = t.first;
  3054. const auto & id = t.second;
  3055. // Count all non-normal tokens in the vocab while iterating
  3056. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3057. special_tokens_count_by_type++;
  3058. }
  3059. // Skip single character tokens
  3060. if (token.length() > 1) {
  3061. bool is_tokenizable = false;
  3062. // Split token string representation in two, in all possible ways
  3063. // and check if both halves can be matched to a valid token
  3064. for (unsigned i = 1; i < token.length();) {
  3065. const auto left = token.substr(0, i);
  3066. const auto right = token.substr(i);
  3067. // check if we didnt partition in the middle of a utf sequence
  3068. auto utf = utf8_len(left.at(left.length() - 1));
  3069. if (utf == 1) {
  3070. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3071. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3072. is_tokenizable = true;
  3073. break;
  3074. }
  3075. i++;
  3076. } else {
  3077. // skip over the rest of multibyte utf sequence
  3078. i += utf - 1;
  3079. }
  3080. }
  3081. if (!is_tokenizable) {
  3082. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3083. // it's faster to re-filter them here, since there are way less candidates now
  3084. // Calculate a total "utf" length of a token string representation
  3085. size_t utf8_str_len = 0;
  3086. for (unsigned i = 0; i < token.length();) {
  3087. utf8_str_len++;
  3088. i += utf8_len(token.at(i));
  3089. }
  3090. // And skip the ones which are one character
  3091. if (utf8_str_len > 1) {
  3092. // At this point what we have left are special tokens only
  3093. vocab.special_tokens_cache[token] = id;
  3094. // Count manually found special tokens
  3095. special_tokens_count_from_verification++;
  3096. // If this manually found special token is not marked as such, flag a mismatch
  3097. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3098. special_tokens_definition_mismatch = true;
  3099. }
  3100. }
  3101. }
  3102. }
  3103. }
  3104. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3105. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3106. __func__,
  3107. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3108. special_tokens_count_by_type, vocab.id_to_token.size()
  3109. );
  3110. } else {
  3111. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3112. __func__,
  3113. special_tokens_count_from_verification, vocab.id_to_token.size()
  3114. );
  3115. }
  3116. }
  3117. }
  3118. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3119. const auto & hparams = model.hparams;
  3120. const auto & vocab = model.vocab;
  3121. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3122. // hparams
  3123. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3124. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3125. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3126. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3127. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3128. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3129. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3130. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3131. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3132. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3133. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3134. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3135. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3136. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3137. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3138. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3139. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3140. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3141. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3142. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3143. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3144. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3145. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3146. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3147. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3148. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3149. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3150. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3151. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3152. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3153. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3154. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3155. if (ml.n_elements >= 1e12) {
  3156. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3157. } else if (ml.n_elements >= 1e9) {
  3158. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3159. } else if (ml.n_elements >= 1e6) {
  3160. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3161. } else {
  3162. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3163. }
  3164. if (ml.n_bytes < GiB) {
  3165. 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);
  3166. } else {
  3167. 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);
  3168. }
  3169. // general kv
  3170. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3171. // special tokens
  3172. 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() ); }
  3173. 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() ); }
  3174. 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() ); }
  3175. 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() ); }
  3176. 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() ); }
  3177. 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() ); }
  3178. }
  3179. // Returns false if cancelled by progress_callback
  3180. static bool llm_load_tensors(
  3181. llama_model_loader & ml,
  3182. llama_model & model,
  3183. int n_gpu_layers,
  3184. enum llama_split_mode split_mode,
  3185. int main_gpu,
  3186. const float * tensor_split,
  3187. bool use_mlock,
  3188. llama_progress_callback progress_callback,
  3189. void * progress_callback_user_data) {
  3190. model.t_start_us = ggml_time_us();
  3191. auto & hparams = model.hparams;
  3192. model.split_mode = split_mode;
  3193. model.main_gpu = main_gpu;
  3194. model.n_gpu_layers = n_gpu_layers;
  3195. const int64_t n_layer = hparams.n_layer;
  3196. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3197. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3198. model.buft_input = llama_default_buffer_type_cpu(true);
  3199. model.buft_layer.resize(n_layer);
  3200. // assign cpu layers
  3201. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3202. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3203. }
  3204. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3205. // calculate the split points
  3206. int device_count = llama_get_device_count();
  3207. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3208. std::vector<float> splits(device_count);
  3209. if (all_zero) {
  3210. // default split, by free memory
  3211. for (int i = 0; i < device_count; ++i) {
  3212. splits[i] = llama_get_device_memory(i);
  3213. }
  3214. } else {
  3215. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3216. }
  3217. // sum and normalize the splits to get the split points
  3218. float split_sum = 0.0f;
  3219. for (int i = 0; i < device_count; ++i) {
  3220. split_sum += splits[i];
  3221. splits[i] = split_sum;
  3222. }
  3223. for (int i = 0; i < device_count; ++i) {
  3224. splits[i] /= split_sum;
  3225. }
  3226. // assign the repeating layers to the devices according to the splits
  3227. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3228. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3229. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3230. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3231. }
  3232. // assign the output layer
  3233. if (n_gpu_layers > n_layer) {
  3234. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3235. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3236. } else {
  3237. model.buft_output = llama_default_buffer_type_cpu(true);
  3238. }
  3239. } else {
  3240. ggml_backend_buffer_type_t split_buft;
  3241. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3242. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3243. } else {
  3244. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3245. split_buft = llama_default_buffer_type_offload(main_gpu);
  3246. }
  3247. // assign the repeating layers
  3248. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3249. model.buft_layer[i] = {
  3250. split_buft,
  3251. llama_default_buffer_type_offload(main_gpu)
  3252. };
  3253. }
  3254. // assign the output layer
  3255. if (n_gpu_layers > n_layer) {
  3256. model.buft_output = {
  3257. split_buft,
  3258. llama_default_buffer_type_offload(main_gpu)
  3259. };
  3260. } else {
  3261. model.buft_output = llama_default_buffer_type_cpu(true);
  3262. }
  3263. }
  3264. // count used buffer types
  3265. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3266. buft_layer_count[model.buft_input.buft]++;
  3267. buft_layer_count[model.buft_input.buft_matrix]++;
  3268. buft_layer_count[model.buft_output.buft]++;
  3269. buft_layer_count[model.buft_output.buft_matrix]++;
  3270. for (int64_t i = 0; i < n_layer; ++i) {
  3271. buft_layer_count[model.buft_layer[i].buft]++;
  3272. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3273. }
  3274. // create one context per buffer type
  3275. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3276. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3277. for (auto & it : buft_layer_count) {
  3278. struct ggml_init_params params = {
  3279. /*.mem_size =*/ ctx_size,
  3280. /*.mem_buffer =*/ NULL,
  3281. /*.no_alloc =*/ true,
  3282. };
  3283. ggml_context * ctx = ggml_init(params);
  3284. if (!ctx) {
  3285. throw std::runtime_error(format("failed to create context"));
  3286. }
  3287. ctx_map[it.first] = ctx;
  3288. model.ctxs.push_back(ctx);
  3289. }
  3290. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3291. // create tensors for the weights
  3292. {
  3293. const int64_t n_embd = hparams.n_embd;
  3294. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3295. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3296. const int64_t n_embd_gqa = n_embd_v_gqa;
  3297. const int64_t n_vocab = hparams.n_vocab;
  3298. const int64_t n_vocab_type = hparams.n_vocab_type;
  3299. const int64_t n_ff = hparams.n_ff;
  3300. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3301. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3302. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3303. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3304. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3305. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3306. model.layers.resize(n_layer);
  3307. const auto tn = LLM_TN(model.arch);
  3308. switch (model.arch) {
  3309. case LLM_ARCH_LLAMA:
  3310. case LLM_ARCH_REFACT:
  3311. case LLM_ARCH_MINICPM:
  3312. {
  3313. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3314. // output
  3315. {
  3316. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3317. if (model.arch != LLM_ARCH_MINICPM){
  3318. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3319. }
  3320. }
  3321. for (int i = 0; i < n_layer; ++i) {
  3322. ggml_context * ctx_layer = ctx_for_layer(i);
  3323. ggml_context * ctx_split = ctx_for_layer_split(i);
  3324. auto & layer = model.layers[i];
  3325. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3326. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3327. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3328. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3329. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3330. // optional bias tensors
  3331. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3332. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3333. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3334. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3335. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3336. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3337. if (layer.ffn_gate_inp == nullptr) {
  3338. GGML_ASSERT(hparams.n_expert == 0);
  3339. GGML_ASSERT(hparams.n_expert_used == 0);
  3340. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3341. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3342. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3343. } else {
  3344. GGML_ASSERT(hparams.n_expert > 0);
  3345. GGML_ASSERT(hparams.n_expert_used > 0);
  3346. // MoE branch
  3347. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3348. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3349. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3350. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3351. }
  3352. }
  3353. }
  3354. } break;
  3355. case LLM_ARCH_BAICHUAN:
  3356. {
  3357. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3358. {
  3359. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3360. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3361. }
  3362. for (int i = 0; i < n_layer; ++i) {
  3363. ggml_context * ctx_layer = ctx_for_layer(i);
  3364. ggml_context * ctx_split = ctx_for_layer_split(i);
  3365. auto & layer = model.layers[i];
  3366. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3367. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3368. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3369. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3370. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3371. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3372. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3373. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3374. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3375. }
  3376. } break;
  3377. case LLM_ARCH_FALCON:
  3378. {
  3379. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3380. // output
  3381. {
  3382. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3383. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3384. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3385. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3386. } else {
  3387. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3388. ml.n_created--; // artificial tensor
  3389. ml.size_data += ggml_nbytes(model.output);
  3390. }
  3391. }
  3392. for (int i = 0; i < n_layer; ++i) {
  3393. ggml_context * ctx_layer = ctx_for_layer(i);
  3394. ggml_context * ctx_split = ctx_for_layer_split(i);
  3395. auto & layer = model.layers[i];
  3396. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3397. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3398. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3399. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3400. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3401. }
  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.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3404. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3405. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3406. }
  3407. } break;
  3408. case LLM_ARCH_STARCODER:
  3409. {
  3410. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3411. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3412. // output
  3413. {
  3414. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3415. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3416. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3417. }
  3418. for (int i = 0; i < n_layer; ++i) {
  3419. ggml_context * ctx_layer = ctx_for_layer(i);
  3420. ggml_context * ctx_split = ctx_for_layer_split(i);
  3421. auto & layer = model.layers[i];
  3422. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3423. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3424. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3425. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3426. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3427. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3428. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3429. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3430. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3431. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3432. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3433. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3434. }
  3435. } break;
  3436. case LLM_ARCH_PERSIMMON:
  3437. {
  3438. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3439. {
  3440. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3441. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3442. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3443. }
  3444. for (int i = 0; i < n_layer; ++i) {
  3445. ggml_context * ctx_layer = ctx_for_layer(i);
  3446. ggml_context * ctx_split = ctx_for_layer_split(i);
  3447. auto & layer = model.layers[i];
  3448. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3449. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3450. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3451. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3452. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3453. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3454. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3455. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3456. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3457. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3458. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3459. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3460. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3461. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3462. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3463. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3464. }
  3465. } break;
  3466. case LLM_ARCH_BERT:
  3467. case LLM_ARCH_NOMIC_BERT:
  3468. {
  3469. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3470. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3471. if (model.arch == LLM_ARCH_BERT) {
  3472. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3473. }
  3474. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3475. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3476. for (int i = 0; i < n_layer; ++i) {
  3477. ggml_context * ctx_layer = ctx_for_layer(i);
  3478. ggml_context * ctx_split = ctx_for_layer_split(i);
  3479. auto & layer = model.layers[i];
  3480. if (model.arch == LLM_ARCH_BERT) {
  3481. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3482. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3483. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3484. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3485. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3486. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3487. } else {
  3488. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3489. }
  3490. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3491. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3492. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3493. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3494. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3495. if (model.arch == LLM_ARCH_BERT) {
  3496. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3497. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3498. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3499. } else {
  3500. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3501. }
  3502. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3503. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3504. }
  3505. } break;
  3506. case LLM_ARCH_BLOOM:
  3507. {
  3508. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3509. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3510. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3511. // output
  3512. {
  3513. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3514. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3515. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3516. }
  3517. for (int i = 0; i < n_layer; ++i) {
  3518. ggml_context * ctx_layer = ctx_for_layer(i);
  3519. ggml_context * ctx_split = ctx_for_layer_split(i);
  3520. auto & layer = model.layers[i];
  3521. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3522. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3523. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3524. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3525. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3526. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3527. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3528. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3529. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3530. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3531. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3532. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3533. }
  3534. } break;
  3535. case LLM_ARCH_MPT:
  3536. {
  3537. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3538. // output
  3539. {
  3540. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3541. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3542. // same as tok_embd, duplicated to allow offloading
  3543. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3544. ml.n_created--; // artificial tensor
  3545. ml.size_data += ggml_nbytes(model.output);
  3546. }
  3547. for (int i = 0; i < n_layer; ++i) {
  3548. ggml_context * ctx_layer = ctx_for_layer(i);
  3549. ggml_context * ctx_split = ctx_for_layer_split(i);
  3550. auto & layer = model.layers[i];
  3551. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3552. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3553. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3554. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3555. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3556. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3557. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3558. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3559. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3560. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3561. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3562. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3563. // AWQ ScaleActivation layer
  3564. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3565. }
  3566. } break;
  3567. case LLM_ARCH_STABLELM:
  3568. {
  3569. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3570. // output
  3571. {
  3572. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  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.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3582. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3583. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3584. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3585. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3586. // optional bias tensors, present in Stable LM 2 1.6B
  3587. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3588. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3589. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3590. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3591. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3592. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3593. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3594. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3595. }
  3596. } break;
  3597. case LLM_ARCH_QWEN:
  3598. {
  3599. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3600. // output
  3601. {
  3602. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3603. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, 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.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3611. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3612. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3613. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3614. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3615. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3616. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3617. }
  3618. } break;
  3619. case LLM_ARCH_QWEN2:
  3620. {
  3621. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3622. // output
  3623. {
  3624. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3625. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3626. }
  3627. for (int i = 0; i < n_layer; ++i) {
  3628. ggml_context * ctx_layer = ctx_for_layer(i);
  3629. ggml_context * ctx_split = ctx_for_layer_split(i);
  3630. auto & layer = model.layers[i];
  3631. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3632. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3633. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3634. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3635. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3636. // optional bias tensors
  3637. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3638. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3639. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3640. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3641. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3642. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3643. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3644. }
  3645. } break;
  3646. case LLM_ARCH_PHI2:
  3647. {
  3648. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3649. // output
  3650. {
  3651. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3652. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3653. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3654. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3655. }
  3656. for (int i = 0; i < n_layer; ++i) {
  3657. ggml_context * ctx_layer = ctx_for_layer(i);
  3658. ggml_context * ctx_split = ctx_for_layer_split(i);
  3659. auto & layer = model.layers[i];
  3660. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3661. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3662. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3663. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3664. if (layer.wqkv == nullptr) {
  3665. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3666. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3667. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3668. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3669. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3670. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3671. }
  3672. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3673. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3674. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3675. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3676. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3677. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3678. }
  3679. } break;
  3680. case LLM_ARCH_PLAMO:
  3681. {
  3682. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3683. // output
  3684. {
  3685. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {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.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3694. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3695. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3696. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3697. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3698. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3699. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3700. }
  3701. } break;
  3702. case LLM_ARCH_GPT2:
  3703. {
  3704. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3705. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3706. // output
  3707. {
  3708. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3709. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3710. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3711. }
  3712. for (int i = 0; i < n_layer; ++i) {
  3713. ggml_context * ctx_layer = ctx_for_layer(i);
  3714. ggml_context * ctx_split = ctx_for_layer_split(i);
  3715. auto & layer = model.layers[i];
  3716. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3717. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3718. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3719. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3720. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3721. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3722. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3723. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3724. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3725. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3726. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3727. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3728. }
  3729. } break;
  3730. case LLM_ARCH_CODESHELL:
  3731. {
  3732. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3733. // output
  3734. {
  3735. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3736. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {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.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3745. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3746. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3747. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3748. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3749. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3750. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3751. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3752. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3753. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3754. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3755. }
  3756. } break;
  3757. case LLM_ARCH_ORION:
  3758. {
  3759. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3760. {
  3761. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3762. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3763. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3764. }
  3765. for (int i = 0; i < n_layer; ++i) {
  3766. ggml_context * ctx_layer = ctx_for_layer(i);
  3767. ggml_context * ctx_split = ctx_for_layer_split(i);
  3768. auto & layer = model.layers[i];
  3769. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3770. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3771. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3772. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3773. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3774. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3775. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3776. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", 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_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3779. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3780. }
  3781. } break;
  3782. case LLM_ARCH_INTERNLM2:
  3783. {
  3784. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3785. // output
  3786. {
  3787. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3788. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3789. }
  3790. for (int i = 0; i < n_layer; ++i) {
  3791. ggml_context * ctx_layer = ctx_for_layer(i);
  3792. ggml_context * ctx_split = ctx_for_layer_split(i);
  3793. auto & layer = model.layers[i];
  3794. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3795. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3796. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3797. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3798. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3799. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3800. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3801. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3802. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3803. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3804. }
  3805. } break;
  3806. case LLM_ARCH_GEMMA:
  3807. {
  3808. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3809. // output
  3810. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3811. 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
  3812. ml.n_created--; // artificial tensor
  3813. ml.size_data += ggml_nbytes(model.output);
  3814. const int64_t n_ff = hparams.n_ff;
  3815. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3816. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3817. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3818. for (uint32_t i = 0; i < n_layer; ++i) {
  3819. ggml_context * ctx_layer = ctx_for_layer(i);
  3820. ggml_context * ctx_split = ctx_for_layer_split(i);
  3821. auto & layer = model.layers[i];
  3822. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3823. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3824. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3825. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3826. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3827. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3828. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3829. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3830. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3831. }
  3832. } break;
  3833. default:
  3834. throw std::runtime_error("unknown architecture");
  3835. }
  3836. }
  3837. ml.done_getting_tensors();
  3838. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3839. // create the backend buffers
  3840. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3841. for (auto & it : ctx_map) {
  3842. ggml_backend_buffer_type_t buft = it.first;
  3843. ggml_context * ctx = it.second;
  3844. ggml_backend_buffer_t buf = nullptr;
  3845. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3846. // 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
  3847. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3848. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3849. size_t first, last;
  3850. ml.get_mapping_range(&first, &last, ctx);
  3851. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3852. }
  3853. #ifdef GGML_USE_METAL
  3854. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3855. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3856. size_t first, last;
  3857. ml.get_mapping_range(&first, &last, ctx);
  3858. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3859. }
  3860. #endif
  3861. else {
  3862. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3863. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3864. model.mlock_bufs.emplace_back(new llama_mlock);
  3865. auto & mlock_buf = model.mlock_bufs.back();
  3866. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3867. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3868. }
  3869. }
  3870. if (buf == nullptr) {
  3871. throw std::runtime_error("failed to allocate buffer");
  3872. }
  3873. // indicate that this buffer contains weights
  3874. // 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
  3875. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3876. model.bufs.push_back(buf);
  3877. ctx_bufs.emplace_back(ctx, buf);
  3878. }
  3879. if (llama_supports_gpu_offload()) {
  3880. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3881. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3882. if (n_gpu_layers > (int) hparams.n_layer) {
  3883. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3884. }
  3885. const int max_backend_supported_layers = hparams.n_layer + 1;
  3886. const int max_offloadable_layers = hparams.n_layer + 1;
  3887. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3888. }
  3889. // print memory requirements
  3890. for (ggml_backend_buffer_t buf : model.bufs) {
  3891. 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);
  3892. }
  3893. // populate tensors_by_name
  3894. for (ggml_context * ctx : model.ctxs) {
  3895. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3896. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3897. }
  3898. }
  3899. // load tensor data
  3900. for (auto & it : ctx_bufs) {
  3901. ggml_context * ctx = it.first;
  3902. ggml_backend_buffer_t buf = it.second;
  3903. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3904. return false;
  3905. }
  3906. }
  3907. model.mapping = std::move(ml.mapping);
  3908. // loading time will be recalculate after the first eval, so
  3909. // we take page faults deferred by mmap() into consideration
  3910. model.t_load_us = ggml_time_us() - model.t_start_us;
  3911. return true;
  3912. }
  3913. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3914. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3915. try {
  3916. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3917. model.hparams.vocab_only = params.vocab_only;
  3918. try {
  3919. llm_load_arch(ml, model);
  3920. } catch(const std::exception & e) {
  3921. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  3922. }
  3923. try {
  3924. llm_load_hparams(ml, model);
  3925. } catch(const std::exception & e) {
  3926. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  3927. }
  3928. try {
  3929. llm_load_vocab(ml, model);
  3930. } catch(const std::exception & e) {
  3931. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  3932. }
  3933. llm_load_print_meta(ml, model);
  3934. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3935. throw std::runtime_error("vocab size mismatch");
  3936. }
  3937. if (params.vocab_only) {
  3938. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3939. return 0;
  3940. }
  3941. #ifdef GGML_USE_KOMPUTE
  3942. if (params.n_gpu_layers > 0 && (
  3943. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3944. || !(
  3945. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3946. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3947. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3948. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3949. )
  3950. )) {
  3951. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3952. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3953. params.n_gpu_layers = 0;
  3954. }
  3955. #endif
  3956. if (!llm_load_tensors(
  3957. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3958. params.progress_callback, params.progress_callback_user_data
  3959. )) {
  3960. return -2;
  3961. }
  3962. } catch (const std::exception & err) {
  3963. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3964. return -1;
  3965. }
  3966. return 0;
  3967. }
  3968. //
  3969. // llm_build
  3970. //
  3971. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3972. enum llm_ffn_op_type {
  3973. LLM_FFN_SILU,
  3974. LLM_FFN_GELU,
  3975. LLM_FFN_RELU,
  3976. LLM_FFN_RELU_SQR,
  3977. };
  3978. enum llm_ffn_gate_type {
  3979. LLM_FFN_SEQ,
  3980. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3981. };
  3982. enum llm_norm_type {
  3983. LLM_NORM,
  3984. LLM_NORM_RMS,
  3985. };
  3986. static struct ggml_tensor * llm_build_inp_embd(
  3987. struct ggml_context * ctx,
  3988. const llama_hparams & hparams,
  3989. const llama_batch & batch,
  3990. struct ggml_tensor * tok_embd,
  3991. struct ggml_tensor * inp_tokens,
  3992. struct ggml_tensor * inp_embd,
  3993. const llm_build_cb & cb) {
  3994. const int64_t n_embd = hparams.n_embd;
  3995. struct ggml_tensor * inpL;
  3996. if (batch.token) {
  3997. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3998. cb(inp_tokens, "inp_tokens", -1);
  3999. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  4000. } else {
  4001. #ifdef GGML_USE_MPI
  4002. GGML_ASSERT(false && "not implemented");
  4003. #endif
  4004. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  4005. }
  4006. return inpL;
  4007. }
  4008. static void llm_build_kv_store(
  4009. struct ggml_context * ctx,
  4010. const llama_hparams & hparams,
  4011. const llama_kv_cache & kv,
  4012. struct ggml_cgraph * graph,
  4013. struct ggml_tensor * k_cur,
  4014. struct ggml_tensor * v_cur,
  4015. int64_t n_ctx,
  4016. int32_t n_tokens,
  4017. int32_t kv_head,
  4018. const llm_build_cb & cb,
  4019. int64_t il) {
  4020. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4021. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4022. // compute the transposed [n_tokens, n_embd] V matrix
  4023. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4024. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4025. cb(v_cur_t, "v_cur_t", il);
  4026. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4027. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4028. cb(k_cache_view, "k_cache_view", il);
  4029. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4030. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4031. (kv_head)*ggml_element_size(kv.v_l[il]));
  4032. cb(v_cache_view, "v_cache_view", il);
  4033. // important: storing RoPE-ed version of K in the KV cache!
  4034. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4035. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4036. }
  4037. static struct ggml_tensor * llm_build_norm(
  4038. struct ggml_context * ctx,
  4039. struct ggml_tensor * cur,
  4040. const llama_hparams & hparams,
  4041. struct ggml_tensor * mw,
  4042. struct ggml_tensor * mb,
  4043. llm_norm_type type,
  4044. const llm_build_cb & cb,
  4045. int il) {
  4046. switch (type) {
  4047. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4048. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4049. }
  4050. if (mw || mb) {
  4051. cb(cur, "norm", il);
  4052. }
  4053. if (mw) {
  4054. cur = ggml_mul(ctx, cur, mw);
  4055. if (mb) {
  4056. cb(cur, "norm_w", il);
  4057. }
  4058. }
  4059. if (mb) {
  4060. cur = ggml_add(ctx, cur, mb);
  4061. }
  4062. return cur;
  4063. }
  4064. static struct ggml_tensor * llm_build_ffn(
  4065. struct ggml_context * ctx,
  4066. struct ggml_tensor * cur,
  4067. struct ggml_tensor * up,
  4068. struct ggml_tensor * up_b,
  4069. struct ggml_tensor * gate,
  4070. struct ggml_tensor * gate_b,
  4071. struct ggml_tensor * down,
  4072. struct ggml_tensor * down_b,
  4073. struct ggml_tensor * act_scales,
  4074. llm_ffn_op_type type_op,
  4075. llm_ffn_gate_type type_gate,
  4076. const llm_build_cb & cb,
  4077. int il) {
  4078. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4079. cb(tmp, "ffn_up", il);
  4080. if (up_b) {
  4081. tmp = ggml_add(ctx, tmp, up_b);
  4082. cb(tmp, "ffn_up_b", il);
  4083. }
  4084. if (gate) {
  4085. switch (type_gate) {
  4086. case LLM_FFN_SEQ:
  4087. {
  4088. cur = ggml_mul_mat(ctx, gate, tmp);
  4089. cb(cur, "ffn_gate", il);
  4090. } break;
  4091. case LLM_FFN_PAR:
  4092. {
  4093. cur = ggml_mul_mat(ctx, gate, cur);
  4094. cb(cur, "ffn_gate", il);
  4095. } break;
  4096. }
  4097. if (gate_b) {
  4098. cur = ggml_add(ctx, cur, gate_b);
  4099. cb(cur, "ffn_gate_b", il);
  4100. }
  4101. } else {
  4102. cur = tmp;
  4103. }
  4104. switch (type_op) {
  4105. case LLM_FFN_SILU:
  4106. {
  4107. cur = ggml_silu(ctx, cur);
  4108. cb(cur, "ffn_silu", il);
  4109. } break;
  4110. case LLM_FFN_GELU:
  4111. {
  4112. cur = ggml_gelu(ctx, cur);
  4113. cb(cur, "ffn_gelu", il);
  4114. if (act_scales != NULL) {
  4115. cur = ggml_div(ctx, cur, act_scales);
  4116. cb(cur, "ffn_act", il);
  4117. }
  4118. } break;
  4119. case LLM_FFN_RELU:
  4120. {
  4121. cur = ggml_relu(ctx, cur);
  4122. cb(cur, "ffn_relu", il);
  4123. } break;
  4124. case LLM_FFN_RELU_SQR:
  4125. {
  4126. cur = ggml_relu(ctx, cur);
  4127. cb(cur, "ffn_relu", il);
  4128. cur = ggml_sqr(ctx, cur);
  4129. cb(cur, "ffn_sqr(relu)", il);
  4130. } break;
  4131. }
  4132. if (type_gate == LLM_FFN_PAR) {
  4133. cur = ggml_mul(ctx, cur, tmp);
  4134. cb(cur, "ffn_gate_par", il);
  4135. }
  4136. cur = ggml_mul_mat(ctx, down, cur);
  4137. if (down_b) {
  4138. cb(cur, "ffn_down", il);
  4139. }
  4140. if (down_b) {
  4141. cur = ggml_add(ctx, cur, down_b);
  4142. }
  4143. return cur;
  4144. }
  4145. // if max_alibi_bias > 0 then apply ALiBi
  4146. static struct ggml_tensor * llm_build_kqv(
  4147. struct ggml_context * ctx,
  4148. const llama_model & model,
  4149. const llama_hparams & hparams,
  4150. const llama_kv_cache & kv,
  4151. struct ggml_cgraph * graph,
  4152. struct ggml_tensor * wo,
  4153. struct ggml_tensor * wo_b,
  4154. struct ggml_tensor * q_cur,
  4155. struct ggml_tensor * kq_mask,
  4156. struct ggml_tensor * kq_pos,
  4157. int64_t n_ctx,
  4158. int32_t n_tokens,
  4159. int32_t n_kv,
  4160. float kq_scale,
  4161. const llm_build_cb & cb,
  4162. int il) {
  4163. const int64_t n_head = hparams.n_head;
  4164. const int64_t n_head_kv = hparams.n_head_kv;
  4165. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4166. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4167. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4168. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4169. cb(q, "q", il);
  4170. struct ggml_tensor * k =
  4171. ggml_view_3d(ctx, kv.k_l[il],
  4172. n_embd_head_k, n_kv, n_head_kv,
  4173. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4174. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4175. 0);
  4176. cb(k, "k", il);
  4177. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4178. cb(kq, "kq", il);
  4179. if (model.arch == LLM_ARCH_PHI2) {
  4180. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4181. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4182. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4183. }
  4184. #if defined(GGML_USE_VULKAN) || defined(GGML_USE_KOMPUTE)
  4185. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Vulkan, and Kompute")
  4186. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4187. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4188. if (hparams.f_max_alibi_bias > 0.0f) {
  4189. kq = ggml_scale(ctx, kq, kq_scale);
  4190. cb(kq, "kq_scaled", il);
  4191. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4192. cb(kq, "kq_scaled_alibi", il);
  4193. kq = ggml_add(ctx, kq, kq_mask);
  4194. cb(kq, "kq_masked", il);
  4195. kq = ggml_soft_max(ctx, kq);
  4196. cb(kq, "kq_soft_max", il);
  4197. } else
  4198. #endif
  4199. {
  4200. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4201. cb(kq, "kq_soft_max_ext", il);
  4202. }
  4203. // split cached v into n_head heads
  4204. struct ggml_tensor * v =
  4205. ggml_view_3d(ctx, kv.v_l[il],
  4206. n_kv, n_embd_head_v, n_head_kv,
  4207. ggml_element_size(kv.v_l[il])*n_ctx,
  4208. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4209. 0);
  4210. cb(v, "v", il);
  4211. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4212. cb(kqv, "kqv", il);
  4213. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4214. cb(kqv_merged, "kqv_merged", il);
  4215. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4216. cb(cur, "kqv_merged_cont", il);
  4217. ggml_build_forward_expand(graph, cur);
  4218. cur = ggml_mul_mat(ctx, wo, cur);
  4219. if (wo_b) {
  4220. cb(cur, "kqv_wo", il);
  4221. }
  4222. if (wo_b) {
  4223. cur = ggml_add(ctx, cur, wo_b);
  4224. }
  4225. return cur;
  4226. }
  4227. static struct ggml_tensor * llm_build_kv(
  4228. struct ggml_context * ctx,
  4229. const llama_model & model,
  4230. const llama_hparams & hparams,
  4231. const llama_kv_cache & kv,
  4232. struct ggml_cgraph * graph,
  4233. struct ggml_tensor * wo,
  4234. struct ggml_tensor * wo_b,
  4235. struct ggml_tensor * k_cur,
  4236. struct ggml_tensor * v_cur,
  4237. struct ggml_tensor * q_cur,
  4238. struct ggml_tensor * kq_mask,
  4239. struct ggml_tensor * kq_pos,
  4240. int64_t n_ctx,
  4241. int32_t n_tokens,
  4242. int32_t kv_head,
  4243. int32_t n_kv,
  4244. float kq_scale,
  4245. const llm_build_cb & cb,
  4246. int il) {
  4247. // these nodes are added to the graph together so that they are not reordered
  4248. // by doing so, the number of splits in the graph is reduced
  4249. ggml_build_forward_expand(graph, q_cur);
  4250. ggml_build_forward_expand(graph, k_cur);
  4251. ggml_build_forward_expand(graph, v_cur);
  4252. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4253. struct ggml_tensor * cur;
  4254. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4255. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4256. cb(cur, "kqv_out", il);
  4257. return cur;
  4258. }
  4259. struct llm_build_context {
  4260. const llama_model & model;
  4261. const llama_context & lctx;
  4262. const llama_hparams & hparams;
  4263. const llama_cparams & cparams;
  4264. const llama_batch & batch;
  4265. const llama_kv_cache & kv_self;
  4266. const int64_t n_embd;
  4267. const int64_t n_layer;
  4268. const int64_t n_rot;
  4269. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4270. const int64_t n_head;
  4271. const int64_t n_head_kv;
  4272. const int64_t n_embd_head_k;
  4273. const int64_t n_embd_k_gqa;
  4274. const int64_t n_embd_head_v;
  4275. const int64_t n_embd_v_gqa;
  4276. const int64_t n_expert;
  4277. const int64_t n_expert_used;
  4278. const float freq_base;
  4279. const float freq_scale;
  4280. const float ext_factor;
  4281. const float attn_factor;
  4282. const float beta_fast;
  4283. const float beta_slow;
  4284. const float norm_eps;
  4285. const float norm_rms_eps;
  4286. const int32_t n_tokens;
  4287. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4288. const int32_t kv_head; // index of where we store new KV data in the cache
  4289. const int32_t n_orig_ctx;
  4290. const enum llama_pooling_type pooling_type;
  4291. const enum llama_rope_type rope_type;
  4292. const llm_build_cb & cb;
  4293. std::vector<uint8_t> & buf_compute_meta;
  4294. struct ggml_context * ctx0 = nullptr;
  4295. // TODO: consider making the entire interface noexcept
  4296. llm_build_context(
  4297. llama_context & lctx,
  4298. const llama_batch & batch,
  4299. const llm_build_cb & cb,
  4300. bool worst_case) :
  4301. model (lctx.model),
  4302. lctx (lctx),
  4303. hparams (model.hparams),
  4304. cparams (lctx.cparams),
  4305. batch (batch),
  4306. kv_self (lctx.kv_self),
  4307. n_embd (hparams.n_embd),
  4308. n_layer (hparams.n_layer),
  4309. n_rot (hparams.n_rot),
  4310. n_ctx (cparams.n_ctx),
  4311. n_head (hparams.n_head),
  4312. n_head_kv (hparams.n_head_kv),
  4313. n_embd_head_k (hparams.n_embd_head_k),
  4314. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4315. n_embd_head_v (hparams.n_embd_head_v),
  4316. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4317. n_expert (hparams.n_expert),
  4318. n_expert_used (hparams.n_expert_used),
  4319. freq_base (cparams.rope_freq_base),
  4320. freq_scale (cparams.rope_freq_scale),
  4321. ext_factor (cparams.yarn_ext_factor),
  4322. attn_factor (cparams.yarn_attn_factor),
  4323. beta_fast (cparams.yarn_beta_fast),
  4324. beta_slow (cparams.yarn_beta_slow),
  4325. norm_eps (hparams.f_norm_eps),
  4326. norm_rms_eps (hparams.f_norm_rms_eps),
  4327. n_tokens (batch.n_tokens),
  4328. n_kv (worst_case ? n_ctx : kv_self.n),
  4329. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4330. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4331. pooling_type (cparams.do_pooling ? hparams.pooling_type : LLAMA_POOLING_TYPE_NONE),
  4332. rope_type (hparams.rope_type),
  4333. cb (cb),
  4334. buf_compute_meta (lctx.buf_compute_meta) {
  4335. // all initializations should be done in init()
  4336. }
  4337. void init() {
  4338. struct ggml_init_params params = {
  4339. /*.mem_size =*/ buf_compute_meta.size(),
  4340. /*.mem_buffer =*/ buf_compute_meta.data(),
  4341. /*.no_alloc =*/ true,
  4342. };
  4343. ctx0 = ggml_init(params);
  4344. }
  4345. void free() {
  4346. if (ctx0) {
  4347. ggml_free(ctx0);
  4348. ctx0 = nullptr;
  4349. }
  4350. }
  4351. struct ggml_cgraph * build_k_shift() {
  4352. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4353. for (int il = 0; il < n_layer; ++il) {
  4354. struct ggml_tensor * tmp =
  4355. // we rotate only the first n_rot dimensions
  4356. ggml_rope_custom_inplace(ctx0,
  4357. ggml_view_3d(ctx0, kv_self.k_l[il],
  4358. n_embd_head_k, n_head_kv, n_ctx,
  4359. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  4360. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4361. 0),
  4362. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4363. ext_factor, attn_factor, beta_fast, beta_slow);
  4364. cb(tmp, "K_shifted", il);
  4365. ggml_build_forward_expand(gf, tmp);
  4366. }
  4367. return gf;
  4368. }
  4369. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  4370. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4371. for (uint32_t i = 0; i < ids.size(); ++i) {
  4372. const uint32_t id = ids[i];
  4373. if (i == id || id == ids.size()) {
  4374. continue;
  4375. }
  4376. uint32_t nm = 1;
  4377. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  4378. nm++;
  4379. }
  4380. for (int il = 0; il < n_layer; ++il) {
  4381. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  4382. n_embd_k_gqa, nm,
  4383. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4384. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  4385. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  4386. n_embd_k_gqa, nm,
  4387. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4388. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  4389. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  4390. nm, n_embd_v_gqa,
  4391. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4392. ggml_row_size(kv_self.v_l[il]->type, i));
  4393. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  4394. nm, n_embd_v_gqa,
  4395. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4396. ggml_row_size(kv_self.v_l[il]->type, id));
  4397. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  4398. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  4399. }
  4400. i += nm - 1;
  4401. }
  4402. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  4403. return gf;
  4404. }
  4405. struct ggml_cgraph * build_llama() {
  4406. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4407. const int64_t n_embd_head = hparams.n_embd_head_v;
  4408. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4409. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4410. struct ggml_tensor * cur;
  4411. struct ggml_tensor * inpL;
  4412. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4413. cb(inpL, "inp_embd", -1);
  4414. // inp_pos - contains the positions
  4415. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4416. cb(inp_pos, "inp_pos", -1);
  4417. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4418. 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);
  4419. cb(KQ_mask, "KQ_mask", -1);
  4420. for (int il = 0; il < n_layer; ++il) {
  4421. struct ggml_tensor * inpSA = inpL;
  4422. // norm
  4423. cur = llm_build_norm(ctx0, inpL, hparams,
  4424. model.layers[il].attn_norm, NULL,
  4425. LLM_NORM_RMS, cb, il);
  4426. cb(cur, "attn_norm", il);
  4427. // self-attention
  4428. {
  4429. // compute Q and K and RoPE them
  4430. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4431. cb(Qcur, "Qcur", il);
  4432. if (model.layers[il].bq) {
  4433. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4434. cb(Qcur, "Qcur", il);
  4435. }
  4436. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4437. cb(Kcur, "Kcur", il);
  4438. if (model.layers[il].bk) {
  4439. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4440. cb(Kcur, "Kcur", il);
  4441. }
  4442. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4443. cb(Vcur, "Vcur", il);
  4444. if (model.layers[il].bv) {
  4445. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4446. cb(Vcur, "Vcur", il);
  4447. }
  4448. Qcur = ggml_rope_custom(
  4449. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4450. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4451. ext_factor, attn_factor, beta_fast, beta_slow
  4452. );
  4453. cb(Qcur, "Qcur", il);
  4454. Kcur = ggml_rope_custom(
  4455. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4456. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4457. ext_factor, attn_factor, beta_fast, beta_slow
  4458. );
  4459. cb(Kcur, "Kcur", il);
  4460. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4461. model.layers[il].wo, model.layers[il].bo,
  4462. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4463. cb(cur, "kqv_out", il);
  4464. }
  4465. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4466. cb(ffn_inp, "ffn_inp", il);
  4467. // feed-forward network
  4468. if (model.layers[il].ffn_gate_inp == nullptr) {
  4469. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4470. model.layers[il].ffn_norm, NULL,
  4471. LLM_NORM_RMS, cb, il);
  4472. cb(cur, "ffn_norm", il);
  4473. cur = llm_build_ffn(ctx0, cur,
  4474. model.layers[il].ffn_up, NULL,
  4475. model.layers[il].ffn_gate, NULL,
  4476. model.layers[il].ffn_down, NULL,
  4477. NULL,
  4478. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4479. cb(cur, "ffn_out", il);
  4480. } else {
  4481. // MoE branch
  4482. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4483. model.layers[il].ffn_norm, NULL,
  4484. LLM_NORM_RMS, cb, il);
  4485. cb(cur, "ffn_norm", il);
  4486. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4487. cb(logits, "ffn_moe_logits", il);
  4488. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4489. cb(probs, "ffn_moe_probs", il);
  4490. // select experts
  4491. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4492. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4493. ggml_tensor * weights = ggml_get_rows(ctx0,
  4494. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4495. cb(weights, "ffn_moe_weights", il);
  4496. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4497. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4498. cb(weights_sum, "ffn_moe_weights_sum", il);
  4499. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4500. cb(weights, "ffn_moe_weights_norm", il);
  4501. // compute expert outputs
  4502. ggml_tensor * moe_out = nullptr;
  4503. for (int i = 0; i < n_expert_used; ++i) {
  4504. ggml_tensor * cur_expert;
  4505. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4506. cb(cur_up, "ffn_moe_up", il);
  4507. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4508. cb(cur_gate, "ffn_moe_gate", il);
  4509. cur_gate = ggml_silu(ctx0, cur_gate);
  4510. cb(cur_gate, "ffn_moe_silu", il);
  4511. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4512. cb(cur_expert, "ffn_moe_gate_par", il);
  4513. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4514. cb(cur_expert, "ffn_moe_down", il);
  4515. cur_expert = ggml_mul(ctx0, cur_expert,
  4516. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4517. cb(cur_expert, "ffn_moe_weighted", il);
  4518. if (i == 0) {
  4519. moe_out = cur_expert;
  4520. } else {
  4521. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4522. cb(moe_out, "ffn_moe_out", il);
  4523. }
  4524. }
  4525. cur = moe_out;
  4526. }
  4527. cur = ggml_add(ctx0, cur, ffn_inp);
  4528. cb(cur, "l_out", il);
  4529. // input for next layer
  4530. inpL = cur;
  4531. }
  4532. cur = inpL;
  4533. cur = llm_build_norm(ctx0, cur, hparams,
  4534. model.output_norm, NULL,
  4535. LLM_NORM_RMS, cb, -1);
  4536. cb(cur, "result_norm", -1);
  4537. // lm_head
  4538. cur = ggml_mul_mat(ctx0, model.output, cur);
  4539. cb(cur, "result_output", -1);
  4540. ggml_build_forward_expand(gf, cur);
  4541. return gf;
  4542. }
  4543. struct ggml_cgraph * build_baichuan() {
  4544. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4545. const int64_t n_embd_head = hparams.n_embd_head_v;
  4546. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4547. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4548. struct ggml_tensor * cur;
  4549. struct ggml_tensor * inpL;
  4550. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4551. cb(inpL, "inp_embd", -1);
  4552. // inp_pos - contains the positions
  4553. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4554. cb(inp_pos, "inp_pos", -1);
  4555. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4556. 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);
  4557. cb(KQ_mask, "KQ_mask", -1);
  4558. // positions of the tokens in the KV cache
  4559. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4560. cb(KQ_pos, "KQ_pos", -1);
  4561. for (int il = 0; il < n_layer; ++il) {
  4562. struct ggml_tensor * inpSA = inpL;
  4563. cur = llm_build_norm(ctx0, inpL, hparams,
  4564. model.layers[il].attn_norm, NULL,
  4565. LLM_NORM_RMS, cb, il);
  4566. cb(cur, "attn_norm", il);
  4567. // self-attention
  4568. {
  4569. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4570. cb(Qcur, "Qcur", il);
  4571. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4572. cb(Kcur, "Kcur", il);
  4573. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4574. cb(Vcur, "Vcur", il);
  4575. switch (model.type) {
  4576. case MODEL_7B:
  4577. Qcur = ggml_rope_custom(
  4578. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4579. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4580. ext_factor, attn_factor, beta_fast, beta_slow
  4581. );
  4582. Kcur = ggml_rope_custom(
  4583. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4584. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4585. ext_factor, attn_factor, beta_fast, beta_slow
  4586. );
  4587. break;
  4588. case MODEL_13B:
  4589. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4590. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4591. break;
  4592. default:
  4593. GGML_ASSERT(false);
  4594. }
  4595. cb(Qcur, "Qcur", il);
  4596. cb(Kcur, "Kcur", il);
  4597. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4598. model.layers[il].wo, NULL,
  4599. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4600. cb(cur, "kqv_out", il);
  4601. }
  4602. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4603. cb(ffn_inp, "ffn_inp", il);
  4604. // feed-forward network
  4605. {
  4606. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4607. model.layers[il].ffn_norm, NULL,
  4608. LLM_NORM_RMS, cb, il);
  4609. cb(cur, "ffn_norm", il);
  4610. cur = llm_build_ffn(ctx0, cur,
  4611. model.layers[il].ffn_up, NULL,
  4612. model.layers[il].ffn_gate, NULL,
  4613. model.layers[il].ffn_down, NULL,
  4614. NULL,
  4615. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4616. cb(cur, "ffn_out", il);
  4617. }
  4618. cur = ggml_add(ctx0, cur, ffn_inp);
  4619. cb(cur, "l_out", il);
  4620. // input for next layer
  4621. inpL = cur;
  4622. }
  4623. cur = inpL;
  4624. cur = llm_build_norm(ctx0, cur, hparams,
  4625. model.output_norm, NULL,
  4626. LLM_NORM_RMS, cb, -1);
  4627. cb(cur, "result_norm", -1);
  4628. // lm_head
  4629. cur = ggml_mul_mat(ctx0, model.output, cur);
  4630. cb(cur, "result_output", -1);
  4631. ggml_build_forward_expand(gf, cur);
  4632. return gf;
  4633. }
  4634. struct ggml_cgraph * build_falcon() {
  4635. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4636. const int64_t n_embd_head = hparams.n_embd_head_v;
  4637. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4638. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4639. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4640. struct ggml_tensor * cur;
  4641. struct ggml_tensor * inpL;
  4642. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4643. cb(inpL, "inp_embd", -1);
  4644. // inp_pos - contains the positions
  4645. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4646. cb(inp_pos, "inp_pos", -1);
  4647. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4648. 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);
  4649. cb(KQ_mask, "KQ_mask", -1);
  4650. for (int il = 0; il < n_layer; ++il) {
  4651. struct ggml_tensor * attn_norm;
  4652. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4653. model.layers[il].attn_norm,
  4654. model.layers[il].attn_norm_b,
  4655. LLM_NORM, cb, il);
  4656. cb(attn_norm, "attn_norm", il);
  4657. // self-attention
  4658. {
  4659. if (model.layers[il].attn_norm_2) {
  4660. // Falcon-40B
  4661. cur = llm_build_norm(ctx0, inpL, hparams,
  4662. model.layers[il].attn_norm_2,
  4663. model.layers[il].attn_norm_2_b,
  4664. LLM_NORM, cb, il);
  4665. cb(cur, "attn_norm_2", il);
  4666. } else {
  4667. cur = attn_norm;
  4668. }
  4669. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4670. cb(cur, "wqkv", il);
  4671. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4672. 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)));
  4673. 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)));
  4674. cb(Qcur, "Qcur", il);
  4675. cb(Kcur, "Kcur", il);
  4676. cb(Vcur, "Vcur", il);
  4677. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4678. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4679. // using mode = 2 for neox mode
  4680. Qcur = ggml_rope_custom(
  4681. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4682. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4683. );
  4684. cb(Qcur, "Qcur", il);
  4685. Kcur = ggml_rope_custom(
  4686. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4687. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4688. );
  4689. cb(Kcur, "Kcur", il);
  4690. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4691. model.layers[il].wo, NULL,
  4692. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4693. cb(cur, "kqv_out", il);
  4694. }
  4695. struct ggml_tensor * ffn_inp = cur;
  4696. // feed forward
  4697. {
  4698. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4699. model.layers[il].ffn_up, NULL,
  4700. NULL, NULL,
  4701. model.layers[il].ffn_down, NULL,
  4702. NULL,
  4703. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4704. cb(cur, "ffn_out", il);
  4705. }
  4706. cur = ggml_add(ctx0, cur, ffn_inp);
  4707. cb(cur, "l_out", il);
  4708. cur = ggml_add(ctx0, cur, inpL);
  4709. cb(cur, "l_out", il);
  4710. // input for next layer
  4711. inpL = cur;
  4712. }
  4713. cur = inpL;
  4714. // norm
  4715. cur = llm_build_norm(ctx0, cur, hparams,
  4716. model.output_norm,
  4717. model.output_norm_b,
  4718. LLM_NORM, cb, -1);
  4719. cb(cur, "result_norm", -1);
  4720. cur = ggml_mul_mat(ctx0, model.output, cur);
  4721. cb(cur, "result_output", -1);
  4722. ggml_build_forward_expand(gf, cur);
  4723. return gf;
  4724. }
  4725. struct ggml_cgraph * build_starcoder() {
  4726. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4727. const int64_t n_embd_head = hparams.n_embd_head_v;
  4728. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4729. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4730. struct ggml_tensor * cur;
  4731. struct ggml_tensor * pos;
  4732. struct ggml_tensor * inpL;
  4733. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4734. cb(inpL, "inp_embd", -1);
  4735. // inp_pos - contains the positions
  4736. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4737. cb(inp_pos, "inp_pos", -1);
  4738. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4739. 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);
  4740. cb(KQ_mask, "KQ_mask", -1);
  4741. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4742. cb(pos, "pos_embd", -1);
  4743. inpL = ggml_add(ctx0, inpL, pos);
  4744. cb(inpL, "inpL", -1);
  4745. for (int il = 0; il < n_layer; ++il) {
  4746. cur = llm_build_norm(ctx0, inpL, hparams,
  4747. model.layers[il].attn_norm,
  4748. model.layers[il].attn_norm_b,
  4749. LLM_NORM, cb, il);
  4750. cb(cur, "attn_norm", il);
  4751. // self-attention
  4752. {
  4753. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4754. cb(cur, "wqkv", il);
  4755. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4756. cb(cur, "bqkv", il);
  4757. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4758. 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)));
  4759. 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)));
  4760. cb(Qcur, "Qcur", il);
  4761. cb(Kcur, "Kcur", il);
  4762. cb(Vcur, "Vcur", il);
  4763. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4764. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4765. model.layers[il].wo, model.layers[il].bo,
  4766. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4767. cb(cur, "kqv_out", il);
  4768. }
  4769. // add the input
  4770. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4771. cb(ffn_inp, "ffn_inp", il);
  4772. // FF
  4773. {
  4774. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4775. model.layers[il].ffn_norm,
  4776. model.layers[il].ffn_norm_b,
  4777. LLM_NORM, cb, il);
  4778. cb(cur, "ffn_norm", il);
  4779. cur = llm_build_ffn(ctx0, cur,
  4780. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4781. NULL, NULL,
  4782. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4783. NULL,
  4784. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4785. cb(cur, "ffn_out", il);
  4786. }
  4787. inpL = ggml_add(ctx0, cur, ffn_inp);
  4788. cb(inpL, "l_out", il);
  4789. }
  4790. cur = llm_build_norm(ctx0, inpL, hparams,
  4791. model.output_norm,
  4792. model.output_norm_b,
  4793. LLM_NORM, cb, -1);
  4794. cb(cur, "result_norm", -1);
  4795. cur = ggml_mul_mat(ctx0, model.output, cur);
  4796. cb(cur, "result_output", -1);
  4797. ggml_build_forward_expand(gf, cur);
  4798. return gf;
  4799. }
  4800. struct ggml_cgraph * build_persimmon() {
  4801. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4802. const int64_t n_embd_head = hparams.n_embd_head_v;
  4803. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4804. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4805. struct ggml_tensor * cur;
  4806. struct ggml_tensor * inpL;
  4807. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4808. cb(inpL, "inp_embd", -1);
  4809. // inp_pos - contains the positions
  4810. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4811. cb(inp_pos, "inp_pos", -1);
  4812. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4813. 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);
  4814. cb(KQ_mask, "KQ_mask", -1);
  4815. for (int il = 0; il < n_layer; ++il) {
  4816. struct ggml_tensor * residual = inpL;
  4817. cur = llm_build_norm(ctx0, inpL, hparams,
  4818. model.layers[il].attn_norm,
  4819. model.layers[il].attn_norm_b,
  4820. LLM_NORM, cb, il);
  4821. cb(cur, "attn_norm", il);
  4822. // self attention
  4823. {
  4824. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4825. cb(cur, "wqkv", il);
  4826. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4827. cb(cur, "bqkv", il);
  4828. // split qkv
  4829. GGML_ASSERT(n_head_kv == n_head);
  4830. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4831. cb(tmpqkv, "tmpqkv", il);
  4832. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4833. cb(tmpqkv_perm, "tmpqkv", il);
  4834. struct ggml_tensor * tmpq = ggml_view_3d(
  4835. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4836. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4837. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4838. 0
  4839. );
  4840. cb(tmpq, "tmpq", il);
  4841. struct ggml_tensor * tmpk = ggml_view_3d(
  4842. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4843. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4844. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4845. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4846. );
  4847. cb(tmpk, "tmpk", il);
  4848. // Q/K Layernorm
  4849. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4850. model.layers[il].attn_q_norm,
  4851. model.layers[il].attn_q_norm_b,
  4852. LLM_NORM, cb, il);
  4853. cb(tmpq, "tmpq", il);
  4854. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4855. model.layers[il].attn_k_norm,
  4856. model.layers[il].attn_k_norm_b,
  4857. LLM_NORM, cb, il);
  4858. cb(tmpk, "tmpk", il);
  4859. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4860. struct ggml_tensor * qrot = ggml_view_3d(
  4861. ctx0, tmpq, n_rot, n_head, n_tokens,
  4862. ggml_element_size(tmpq) * n_embd_head,
  4863. ggml_element_size(tmpq) * n_embd_head * n_head,
  4864. 0
  4865. );
  4866. cb(qrot, "qrot", il);
  4867. struct ggml_tensor * krot = ggml_view_3d(
  4868. ctx0, tmpk, n_rot, n_head, n_tokens,
  4869. ggml_element_size(tmpk) * n_embd_head,
  4870. ggml_element_size(tmpk) * n_embd_head * n_head,
  4871. 0
  4872. );
  4873. cb(krot, "krot", il);
  4874. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4875. struct ggml_tensor * qpass = ggml_view_3d(
  4876. ctx0, tmpq, n_rot, n_head, n_tokens,
  4877. ggml_element_size(tmpq) * n_embd_head,
  4878. ggml_element_size(tmpq) * n_embd_head * n_head,
  4879. ggml_element_size(tmpq) * n_rot
  4880. );
  4881. cb(qpass, "qpass", il);
  4882. struct ggml_tensor * kpass = ggml_view_3d(
  4883. ctx0, tmpk, n_rot, n_head, n_tokens,
  4884. ggml_element_size(tmpk) * n_embd_head,
  4885. ggml_element_size(tmpk) * n_embd_head * n_head,
  4886. ggml_element_size(tmpk) * n_rot
  4887. );
  4888. cb(kpass, "kpass", il);
  4889. struct ggml_tensor * qrotated = ggml_rope_custom(
  4890. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4891. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4892. );
  4893. cb(qrotated, "qrotated", il);
  4894. struct ggml_tensor * krotated = ggml_rope_custom(
  4895. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4896. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4897. );
  4898. cb(krotated, "krotated", il);
  4899. // ggml currently only supports concatenation on dim=2
  4900. // so we need to permute qrot, qpass, concat, then permute back.
  4901. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4902. cb(qrotated, "qrotated", il);
  4903. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4904. cb(krotated, "krotated", il);
  4905. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4906. cb(qpass, "qpass", il);
  4907. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4908. cb(kpass, "kpass", il);
  4909. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4910. cb(Qcur, "Qcur", il);
  4911. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4912. cb(Kcur, "Kcur", il);
  4913. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4914. cb(Q, "Q", il);
  4915. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4916. cb(Kcur, "Kcur", il);
  4917. struct ggml_tensor * Vcur = ggml_view_3d(
  4918. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4919. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4920. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4921. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4922. );
  4923. cb(Vcur, "Vcur", il);
  4924. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4925. model.layers[il].wo, model.layers[il].bo,
  4926. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4927. cb(cur, "kqv_out", il);
  4928. }
  4929. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4930. cb(ffn_inp, "ffn_inp", il);
  4931. // feed-forward network
  4932. {
  4933. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4934. model.layers[il].ffn_norm,
  4935. model.layers[il].ffn_norm_b,
  4936. LLM_NORM, cb, il);
  4937. cb(cur, "ffn_norm", il);
  4938. cur = llm_build_ffn(ctx0, cur,
  4939. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4940. NULL, NULL,
  4941. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4942. NULL,
  4943. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4944. cb(cur, "ffn_out", il);
  4945. }
  4946. cur = ggml_add(ctx0, cur, ffn_inp);
  4947. cb(cur, "l_out", il);
  4948. inpL = cur;
  4949. }
  4950. cur = inpL;
  4951. cur = llm_build_norm(ctx0, cur, hparams,
  4952. model.output_norm,
  4953. model.output_norm_b,
  4954. LLM_NORM, cb, -1);
  4955. cb(cur, "result_norm", -1);
  4956. cur = ggml_mul_mat(ctx0, model.output, cur);
  4957. cb(cur, "result_output", -1);
  4958. ggml_build_forward_expand(gf, cur);
  4959. return gf;
  4960. }
  4961. struct ggml_cgraph * build_refact() {
  4962. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4963. const int64_t n_embd_head = hparams.n_embd_head_v;
  4964. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4965. struct ggml_tensor * cur;
  4966. struct ggml_tensor * inpL;
  4967. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4968. cb(inpL, "inp_embd", -1);
  4969. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4970. 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);
  4971. cb(KQ_mask, "KQ_mask", -1);
  4972. // positions of the tokens in the KV cache
  4973. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4974. cb(KQ_pos, "KQ_pos", -1);
  4975. for (int il = 0; il < n_layer; ++il) {
  4976. struct ggml_tensor * inpSA = inpL;
  4977. cur = llm_build_norm(ctx0, inpL, hparams,
  4978. model.layers[il].attn_norm, NULL,
  4979. LLM_NORM_RMS, cb, il);
  4980. cb(cur, "attn_norm", il);
  4981. // self-attention
  4982. {
  4983. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4984. cb(Qcur, "Qcur", il);
  4985. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4986. cb(Kcur, "Kcur", il);
  4987. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4988. cb(Vcur, "Vcur", il);
  4989. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4990. cb(Kcur, "Kcur", il);
  4991. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4992. cb(Qcur, "Qcur", il);
  4993. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4994. model.layers[il].wo, NULL,
  4995. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4996. cb(cur, "kqv_out", il);
  4997. }
  4998. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4999. cb(ffn_inp, "ffn_inp", il);
  5000. // feed-forward network
  5001. {
  5002. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5003. model.layers[il].ffn_norm, NULL,
  5004. LLM_NORM_RMS, cb, il);
  5005. cb(cur, "ffn_norm", il);
  5006. cur = llm_build_ffn(ctx0, cur,
  5007. model.layers[il].ffn_up, NULL,
  5008. model.layers[il].ffn_gate, NULL,
  5009. model.layers[il].ffn_down, NULL,
  5010. NULL,
  5011. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5012. cb(cur, "ffn_out", il);
  5013. }
  5014. cur = ggml_add(ctx0, cur, ffn_inp);
  5015. cb(cur, "l_out", il);
  5016. // input for next layer
  5017. inpL = cur;
  5018. }
  5019. cur = inpL;
  5020. cur = llm_build_norm(ctx0, cur, hparams,
  5021. model.output_norm, NULL,
  5022. LLM_NORM_RMS, cb, -1);
  5023. cb(cur, "result_norm", -1);
  5024. // lm_head
  5025. cur = ggml_mul_mat(ctx0, model.output, cur);
  5026. cb(cur, "result_output", -1);
  5027. ggml_build_forward_expand(gf, cur);
  5028. return gf;
  5029. }
  5030. struct ggml_cgraph * build_bert() {
  5031. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5032. const int64_t n_embd_head = hparams.n_embd_head_v;
  5033. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5034. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5035. struct ggml_tensor * cur;
  5036. struct ggml_tensor * inpL;
  5037. // get input vectors with right size
  5038. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  5039. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5040. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  5041. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  5042. // construct input embeddings (token, type, position)
  5043. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5044. // token types are hardcoded to zero ("Sentence A")
  5045. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5046. inpL = ggml_add(ctx0, inpL, type_row0);
  5047. if (model.arch == LLM_ARCH_BERT) {
  5048. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5049. }
  5050. cb(inpL, "inp_embd", -1);
  5051. // embed layer norm
  5052. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5053. cb(inpL, "inp_norm", -1);
  5054. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5055. 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);
  5056. cb(KQ_mask, "KQ_mask", -1); // [n_kv, n_tokens]
  5057. // iterate layers
  5058. for (int il = 0; il < n_layer; ++il) {
  5059. struct ggml_tensor * cur = inpL;
  5060. // self-attention
  5061. if (model.arch == LLM_ARCH_BERT) {
  5062. struct ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5063. cb(Qcur, "Qcur", il);
  5064. struct ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5065. cb(Kcur, "Kcur", il);
  5066. struct ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5067. cb(Vcur, "Vcur", il);
  5068. // seems like we just need to do this for Q?
  5069. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5070. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5071. model.layers[il].wo, model.layers[il].bo,
  5072. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5073. cb(cur, "kqv_out", il);
  5074. } else {
  5075. // compute Q and K and RoPE them
  5076. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5077. cb(cur, "wqkv", il);
  5078. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5079. 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)));
  5080. 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)));
  5081. cb(Qcur, "Qcur", il);
  5082. cb(Kcur, "Kcur", il);
  5083. cb(Vcur, "Vcur", il);
  5084. Qcur = ggml_rope_custom(
  5085. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5086. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5087. ext_factor, attn_factor, beta_fast, beta_slow
  5088. );
  5089. cb(Qcur, "Qcur", il);
  5090. Kcur = ggml_rope_custom(
  5091. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5092. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5093. ext_factor, attn_factor, beta_fast, beta_slow
  5094. );
  5095. cb(Kcur, "Kcur", il);
  5096. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5097. model.layers[il].wo, model.layers[il].bo,
  5098. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5099. cb(cur, "kqv_out", il);
  5100. }
  5101. // re-add the layer input
  5102. cur = ggml_add(ctx0, cur, inpL);
  5103. // attention layer norm
  5104. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5105. struct ggml_tensor * ffn_inp = cur;
  5106. cb(ffn_inp, "ffn_inp", il);
  5107. // feed-forward network
  5108. if (model.arch == LLM_ARCH_BERT) {
  5109. cur = llm_build_ffn(ctx0, cur,
  5110. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5111. NULL, NULL,
  5112. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5113. NULL,
  5114. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5115. } else {
  5116. cur = llm_build_ffn(ctx0, cur,
  5117. model.layers[il].ffn_up, NULL,
  5118. model.layers[il].ffn_gate, NULL,
  5119. model.layers[il].ffn_down, NULL,
  5120. NULL,
  5121. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5122. }
  5123. cb(cur, "ffn_out", il);
  5124. // attentions bypass the intermediate layer
  5125. cur = ggml_add(ctx0, cur, ffn_inp);
  5126. // output layer norm
  5127. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5128. // input for next layer
  5129. inpL = cur;
  5130. }
  5131. // final output
  5132. cur = inpL;
  5133. // pooling layer
  5134. if (pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  5135. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5136. } else if (pooling_type == LLAMA_POOLING_TYPE_CLS) {
  5137. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5138. } else {
  5139. GGML_ASSERT(pooling_type == LLAMA_POOLING_TYPE_NONE && "Invalid pooling type");
  5140. }
  5141. cb(cur, "result_embd", -1);
  5142. ggml_build_forward_expand(gf, cur);
  5143. return gf;
  5144. }
  5145. struct ggml_cgraph * build_bloom() {
  5146. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5147. const int64_t n_embd_head = hparams.n_embd_head_v;
  5148. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5149. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5150. struct ggml_tensor * cur;
  5151. struct ggml_tensor * inpL;
  5152. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5153. cb(inpL, "inp_embd", -1);
  5154. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5155. 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);
  5156. cb(KQ_mask, "KQ_mask", -1);
  5157. // positions of the tokens in the KV cache
  5158. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5159. cb(KQ_pos, "KQ_pos", -1);
  5160. inpL = llm_build_norm(ctx0, inpL, hparams,
  5161. model.tok_norm,
  5162. model.tok_norm_b,
  5163. LLM_NORM, cb, -1);
  5164. cb(inpL, "inp_norm", -1);
  5165. for (int il = 0; il < n_layer; ++il) {
  5166. cur = llm_build_norm(ctx0, inpL, hparams,
  5167. model.layers[il].attn_norm,
  5168. model.layers[il].attn_norm_b,
  5169. LLM_NORM, cb, il);
  5170. cb(cur, "attn_norm", il);
  5171. // self-attention
  5172. {
  5173. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5174. cb(cur, "wqkv", il);
  5175. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5176. cb(cur, "bqkv", il);
  5177. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5178. 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)));
  5179. 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)));
  5180. cb(Qcur, "Qcur", il);
  5181. cb(Kcur, "Kcur", il);
  5182. cb(Vcur, "Vcur", il);
  5183. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5184. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5185. model.layers[il].wo, model.layers[il].bo,
  5186. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5187. cb(cur, "kqv_out", il);
  5188. }
  5189. // Add the input
  5190. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5191. cb(ffn_inp, "ffn_inp", il);
  5192. // FF
  5193. {
  5194. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5195. model.layers[il].ffn_norm,
  5196. model.layers[il].ffn_norm_b,
  5197. LLM_NORM, cb, il);
  5198. cb(cur, "ffn_norm", il);
  5199. cur = llm_build_ffn(ctx0, cur,
  5200. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5201. NULL, NULL,
  5202. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5203. NULL,
  5204. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5205. cb(cur, "ffn_out", il);
  5206. }
  5207. inpL = ggml_add(ctx0, cur, ffn_inp);
  5208. cb(inpL, "l_out", il);
  5209. }
  5210. cur = llm_build_norm(ctx0, inpL, hparams,
  5211. model.output_norm,
  5212. model.output_norm_b,
  5213. LLM_NORM, cb, -1);
  5214. cb(cur, "result_norm", -1);
  5215. cur = ggml_mul_mat(ctx0, model.output, cur);
  5216. cb(cur, "result_output", -1);
  5217. ggml_build_forward_expand(gf, cur);
  5218. return gf;
  5219. }
  5220. struct ggml_cgraph * build_mpt() {
  5221. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5222. const int64_t n_embd_head = hparams.n_embd_head_v;
  5223. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5224. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5225. struct ggml_tensor * cur;
  5226. struct ggml_tensor * inpL;
  5227. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5228. cb(inpL, "inp_embd", -1);
  5229. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5230. 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);
  5231. cb(KQ_mask, "KQ_mask", -1);
  5232. // positions of the tokens in the KV cache
  5233. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5234. cb(KQ_pos, "KQ_pos", -1);
  5235. for (int il = 0; il < n_layer; ++il) {
  5236. struct ggml_tensor * attn_norm;
  5237. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5238. model.layers[il].attn_norm,
  5239. model.layers[il].attn_norm_b,
  5240. LLM_NORM, cb, il);
  5241. cb(attn_norm, "attn_norm", il);
  5242. // self-attention
  5243. {
  5244. cur = attn_norm;
  5245. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5246. cb(cur, "wqkv", il);
  5247. if (model.layers[il].bqkv){
  5248. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5249. cb(cur, "bqkv", il);
  5250. }
  5251. if (hparams.f_clamp_kqv > 0.0f) {
  5252. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5253. cb(cur, "wqkv_clamped", il);
  5254. }
  5255. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5256. 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)));
  5257. 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)));
  5258. cb(Qcur, "Qcur", il);
  5259. cb(Kcur, "Kcur", il);
  5260. cb(Vcur, "Vcur", il);
  5261. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5262. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5263. model.layers[il].wo, model.layers[il].bo,
  5264. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5265. cb(cur, "kqv_out", il);
  5266. }
  5267. // Add the input
  5268. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5269. cb(ffn_inp, "ffn_inp", il);
  5270. // feed forward
  5271. {
  5272. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5273. model.layers[il].ffn_norm,
  5274. model.layers[il].ffn_norm_b,
  5275. LLM_NORM, cb, il);
  5276. cb(cur, "ffn_norm", il);
  5277. cur = llm_build_ffn(ctx0, cur,
  5278. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5279. NULL, NULL,
  5280. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5281. model.layers[il].ffn_act,
  5282. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5283. cb(cur, "ffn_out", il);
  5284. }
  5285. cur = ggml_add(ctx0, cur, ffn_inp);
  5286. cb(cur, "l_out", il);
  5287. // input for next layer
  5288. inpL = cur;
  5289. }
  5290. cur = inpL;
  5291. cur = llm_build_norm(ctx0, cur, hparams,
  5292. model.output_norm,
  5293. model.output_norm_b,
  5294. LLM_NORM, cb, -1);
  5295. cb(cur, "result_norm", -1);
  5296. cur = ggml_mul_mat(ctx0, model.output, cur);
  5297. cb(cur, "result_output", -1);
  5298. ggml_build_forward_expand(gf, cur);
  5299. return gf;
  5300. }
  5301. struct ggml_cgraph * build_stablelm() {
  5302. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5303. const int64_t n_embd_head = hparams.n_embd_head_v;
  5304. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5305. struct ggml_tensor * cur;
  5306. struct ggml_tensor * inpL;
  5307. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5308. cb(inpL, "inp_embd", -1);
  5309. // inp_pos - contains the positions
  5310. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5311. cb(inp_pos, "inp_pos", -1);
  5312. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5313. 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);
  5314. cb(KQ_mask, "KQ_mask", -1);
  5315. for (int il = 0; il < n_layer; ++il) {
  5316. struct ggml_tensor * inpSA = inpL;
  5317. // norm
  5318. cur = llm_build_norm(ctx0, inpL, hparams,
  5319. model.layers[il].attn_norm,
  5320. model.layers[il].attn_norm_b,
  5321. LLM_NORM, cb, il);
  5322. cb(cur, "attn_norm", il);
  5323. // self-attention
  5324. {
  5325. // compute Q and K and RoPE them
  5326. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5327. cb(Qcur, "Qcur", il);
  5328. if (model.layers[il].bq) {
  5329. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5330. cb(Qcur, "Qcur", il);
  5331. }
  5332. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5333. cb(Kcur, "Kcur", il);
  5334. if (model.layers[il].bk) {
  5335. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5336. cb(Kcur, "Kcur", il);
  5337. }
  5338. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5339. cb(Vcur, "Vcur", il);
  5340. if (model.layers[il].bv) {
  5341. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5342. cb(Vcur, "Vcur", il);
  5343. }
  5344. Qcur = ggml_rope_custom(
  5345. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5346. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5347. ext_factor, attn_factor, beta_fast, beta_slow
  5348. );
  5349. cb(Qcur, "Qcur", il);
  5350. Kcur = ggml_rope_custom(
  5351. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5352. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5353. ext_factor, attn_factor, beta_fast, beta_slow
  5354. );
  5355. cb(Kcur, "Kcur", il);
  5356. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5357. model.layers[il].wo, NULL,
  5358. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5359. cb(cur, "kqv_out", il);
  5360. }
  5361. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5362. cb(ffn_inp, "ffn_inp", il);
  5363. // feed-forward network
  5364. {
  5365. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5366. model.layers[il].ffn_norm,
  5367. model.layers[il].ffn_norm_b,
  5368. LLM_NORM, cb, il);
  5369. cb(cur, "ffn_norm", il);
  5370. cur = llm_build_ffn(ctx0, cur,
  5371. model.layers[il].ffn_up, NULL,
  5372. model.layers[il].ffn_gate, NULL,
  5373. model.layers[il].ffn_down, NULL,
  5374. NULL,
  5375. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5376. cb(cur, "ffn_out", il);
  5377. }
  5378. cur = ggml_add(ctx0, cur, ffn_inp);
  5379. cb(cur, "l_out", il);
  5380. // input for next layer
  5381. inpL = cur;
  5382. }
  5383. cur = inpL;
  5384. cur = llm_build_norm(ctx0, cur, hparams,
  5385. model.output_norm,
  5386. model.output_norm_b,
  5387. LLM_NORM, cb, -1);
  5388. cb(cur, "result_norm", -1);
  5389. // lm_head
  5390. cur = ggml_mul_mat(ctx0, model.output, cur);
  5391. cb(cur, "result_output", -1);
  5392. ggml_build_forward_expand(gf, cur);
  5393. return gf;
  5394. }
  5395. struct ggml_cgraph * build_qwen() {
  5396. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5397. const int64_t n_embd_head = hparams.n_embd_head_v;
  5398. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5399. struct ggml_tensor * cur;
  5400. struct ggml_tensor * inpL;
  5401. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5402. cb(inpL, "inp_embd", -1);
  5403. // inp_pos - contains the positions
  5404. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5405. cb(inp_pos, "inp_pos", -1);
  5406. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5407. 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);
  5408. cb(KQ_mask, "KQ_mask", -1);
  5409. for (int il = 0; il < n_layer; ++il) {
  5410. struct ggml_tensor * inpSA = inpL;
  5411. cur = llm_build_norm(ctx0, inpL, hparams,
  5412. model.layers[il].attn_norm, NULL,
  5413. LLM_NORM_RMS, cb, il);
  5414. cb(cur, "attn_norm", il);
  5415. // self-attention
  5416. {
  5417. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5418. cb(cur, "wqkv", il);
  5419. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5420. cb(cur, "bqkv", il);
  5421. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5422. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5423. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5424. cb(Qcur, "Qcur", il);
  5425. cb(Kcur, "Kcur", il);
  5426. cb(Vcur, "Vcur", il);
  5427. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5428. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5429. // using mode = 2 for neox mode
  5430. Qcur = ggml_rope_custom(
  5431. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5432. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5433. );
  5434. cb(Qcur, "Qcur", il);
  5435. Kcur = ggml_rope_custom(
  5436. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5437. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5438. );
  5439. cb(Kcur, "Kcur", il);
  5440. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5441. model.layers[il].wo, NULL,
  5442. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5443. cb(cur, "kqv_out", il);
  5444. }
  5445. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5446. cb(ffn_inp, "ffn_inp", il);
  5447. // feed-forward forward
  5448. {
  5449. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5450. model.layers[il].ffn_norm, NULL,
  5451. LLM_NORM_RMS, cb, il);
  5452. cb(cur, "ffn_norm", il);
  5453. cur = llm_build_ffn(ctx0, cur,
  5454. model.layers[il].ffn_up, NULL,
  5455. model.layers[il].ffn_gate, NULL,
  5456. model.layers[il].ffn_down, NULL,
  5457. NULL,
  5458. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5459. cb(cur, "ffn_out", il);
  5460. }
  5461. cur = ggml_add(ctx0, cur, ffn_inp);
  5462. cb(cur, "l_out", il);
  5463. // input for next layer
  5464. inpL = cur;
  5465. }
  5466. cur = inpL;
  5467. cur = llm_build_norm(ctx0, cur, hparams,
  5468. model.output_norm, NULL,
  5469. LLM_NORM_RMS, cb, -1);
  5470. cb(cur, "result_norm", -1);
  5471. // lm_head
  5472. cur = ggml_mul_mat(ctx0, model.output, cur);
  5473. cb(cur, "result_output", -1);
  5474. ggml_build_forward_expand(gf, cur);
  5475. return gf;
  5476. }
  5477. struct ggml_cgraph * build_qwen2() {
  5478. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5479. const int64_t n_embd_head = hparams.n_embd_head_v;
  5480. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5481. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5482. struct ggml_tensor * cur;
  5483. struct ggml_tensor * inpL;
  5484. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5485. cb(inpL, "inp_embd", -1);
  5486. // inp_pos - contains the positions
  5487. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5488. cb(inp_pos, "inp_pos", -1);
  5489. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5490. 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);
  5491. cb(KQ_mask, "KQ_mask", -1);
  5492. for (int il = 0; il < n_layer; ++il) {
  5493. struct ggml_tensor * inpSA = inpL;
  5494. // norm
  5495. cur = llm_build_norm(ctx0, inpL, hparams,
  5496. model.layers[il].attn_norm, NULL,
  5497. LLM_NORM_RMS, cb, il);
  5498. cb(cur, "attn_norm", il);
  5499. // self-attention
  5500. {
  5501. // compute Q and K and RoPE them
  5502. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5503. cb(Qcur, "Qcur", il);
  5504. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5505. cb(Qcur, "Qcur", il);
  5506. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5507. cb(Kcur, "Kcur", il);
  5508. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5509. cb(Kcur, "Kcur", il);
  5510. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5511. cb(Vcur, "Vcur", il);
  5512. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5513. cb(Vcur, "Vcur", il);
  5514. // these nodes are added to the graph together so that they are not reordered
  5515. // by doing so, the number of splits in the graph is reduced
  5516. ggml_build_forward_expand(gf, Qcur);
  5517. ggml_build_forward_expand(gf, Kcur);
  5518. ggml_build_forward_expand(gf, Vcur);
  5519. Qcur = ggml_rope_custom(
  5520. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5521. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5522. ext_factor, attn_factor, beta_fast, beta_slow
  5523. );
  5524. cb(Qcur, "Qcur", il);
  5525. Kcur = ggml_rope_custom(
  5526. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5527. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5528. ext_factor, attn_factor, beta_fast, beta_slow
  5529. );
  5530. cb(Kcur, "Kcur", il);
  5531. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5532. model.layers[il].wo, model.layers[il].bo,
  5533. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5534. cb(cur, "kqv_out", il);
  5535. }
  5536. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5537. cb(ffn_inp, "ffn_inp", il);
  5538. // feed-forward network
  5539. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5540. model.layers[il].ffn_norm, NULL,
  5541. LLM_NORM_RMS, cb, il);
  5542. cb(cur, "ffn_norm", il);
  5543. cur = llm_build_ffn(ctx0, cur,
  5544. model.layers[il].ffn_up, NULL,
  5545. model.layers[il].ffn_gate, NULL,
  5546. model.layers[il].ffn_down, NULL,
  5547. NULL,
  5548. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5549. cb(cur, "ffn_out", il);
  5550. cur = ggml_add(ctx0, cur, ffn_inp);
  5551. cb(cur, "l_out", il);
  5552. // input for next layer
  5553. inpL = cur;
  5554. }
  5555. cur = inpL;
  5556. cur = llm_build_norm(ctx0, cur, hparams,
  5557. model.output_norm, NULL,
  5558. LLM_NORM_RMS, cb, -1);
  5559. cb(cur, "result_norm", -1);
  5560. // lm_head
  5561. cur = ggml_mul_mat(ctx0, model.output, cur);
  5562. cb(cur, "result_output", -1);
  5563. ggml_build_forward_expand(gf, cur);
  5564. return gf;
  5565. }
  5566. struct ggml_cgraph * build_phi2() {
  5567. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5568. const int64_t n_embd_head = hparams.n_embd_head_v;
  5569. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5570. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5571. struct ggml_tensor * cur;
  5572. struct ggml_tensor * attn_norm_output;
  5573. struct ggml_tensor * ffn_output;
  5574. struct ggml_tensor * inpL;
  5575. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5576. cb(inpL, "inp_embd", -1);
  5577. // inp_pos - contains the positions
  5578. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5579. cb(inp_pos, "inp_pos", -1);
  5580. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5581. 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);
  5582. cb(KQ_mask, "KQ_mask", -1);
  5583. for (int il = 0; il < n_layer; ++il) {
  5584. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5585. model.layers[il].attn_norm,
  5586. model.layers[il].attn_norm_b,
  5587. LLM_NORM, cb, il);
  5588. cb(attn_norm_output, "attn_norm", il);
  5589. // self-attention
  5590. {
  5591. struct ggml_tensor * Qcur = nullptr;
  5592. struct ggml_tensor * Kcur = nullptr;
  5593. struct ggml_tensor * Vcur = nullptr;
  5594. if (model.layers[il].wqkv) {
  5595. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5596. cb(cur, "wqkv", il);
  5597. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5598. cb(cur, "bqkv", il);
  5599. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5600. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5601. 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)));
  5602. } else {
  5603. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5604. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5605. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5606. }
  5607. cb(Qcur, "Qcur", il);
  5608. cb(Kcur, "Kcur", il);
  5609. cb(Vcur, "Vcur", il);
  5610. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5611. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5612. Qcur = ggml_rope_custom(
  5613. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5614. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5615. );
  5616. cb(Qcur, "Qcur", il);
  5617. // with phi2, we scale the Q to avoid precision issues
  5618. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5619. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5620. cb(Qcur, "Qcur", il);
  5621. Kcur = ggml_rope_custom(
  5622. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5623. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5624. );
  5625. cb(Kcur, "Kcur", il);
  5626. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5627. model.layers[il].wo, model.layers[il].bo,
  5628. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5629. cb(cur, "kqv_out", il);
  5630. }
  5631. // FF
  5632. {
  5633. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5634. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5635. NULL, NULL,
  5636. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5637. NULL,
  5638. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5639. cb(ffn_output, "ffn_out", il);
  5640. }
  5641. cur = ggml_add(ctx0, cur, ffn_output);
  5642. cb(cur, "l_out", il);
  5643. cur = ggml_add(ctx0, cur, inpL);
  5644. cb(cur, "l_out", il);
  5645. inpL = cur;
  5646. }
  5647. cur = llm_build_norm(ctx0, inpL, hparams,
  5648. model.output_norm,
  5649. model.output_norm_b,
  5650. LLM_NORM, cb, -1);
  5651. cb(cur, "result_norm", -1);
  5652. cur = ggml_mul_mat(ctx0, model.output, cur);
  5653. cb(cur, "result_output_no_bias", -1);
  5654. cur = ggml_add(ctx0, cur, model.output_b);
  5655. cb(cur, "result_output", -1);
  5656. ggml_build_forward_expand(gf, cur);
  5657. return gf;
  5658. }
  5659. struct ggml_cgraph * build_plamo() {
  5660. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5661. const int64_t n_embd_head = hparams.n_embd_head_v;
  5662. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5663. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5664. struct ggml_tensor * cur;
  5665. struct ggml_tensor * inpL;
  5666. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5667. cb(inpL, "inp_embd", -1);
  5668. // inp_pos - contains the positions
  5669. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5670. cb(inp_pos, "inp_pos", -1);
  5671. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5672. 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);
  5673. cb(KQ_mask, "KQ_mask", -1);
  5674. for (int il = 0; il < n_layer; ++il) {
  5675. // norm
  5676. cur = llm_build_norm(ctx0, inpL, hparams,
  5677. model.layers[il].attn_norm, NULL,
  5678. LLM_NORM_RMS, cb, il);
  5679. cb(cur, "attn_norm", il);
  5680. struct ggml_tensor * attention_norm = cur;
  5681. // self-attention
  5682. {
  5683. // compute Q and K and RoPE them
  5684. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5685. cb(Qcur, "Qcur", il);
  5686. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5687. cb(Kcur, "Kcur", il);
  5688. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5689. cb(Vcur, "Vcur", il);
  5690. Qcur = ggml_rope_custom(
  5691. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  5692. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5693. ext_factor, attn_factor, beta_fast, beta_slow);
  5694. cb(Qcur, "Qcur", il);
  5695. Kcur = ggml_rope_custom(
  5696. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  5697. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5698. ext_factor, attn_factor, beta_fast, beta_slow);
  5699. cb(Kcur, "Kcur", il);
  5700. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5701. model.layers[il].wo, NULL,
  5702. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5703. cb(cur, "kqv_out", il);
  5704. }
  5705. struct ggml_tensor * sa_out = cur;
  5706. cur = attention_norm;
  5707. // feed-forward network
  5708. {
  5709. cur = llm_build_ffn(ctx0, cur,
  5710. model.layers[il].ffn_up, NULL,
  5711. model.layers[il].ffn_gate, NULL,
  5712. model.layers[il].ffn_down, NULL,
  5713. NULL,
  5714. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5715. cb(cur, "ffn_out", il);
  5716. }
  5717. cur = ggml_add(ctx0, cur, sa_out);
  5718. cb(cur, "l_out", il);
  5719. cur = ggml_add(ctx0, cur, inpL);
  5720. cb(cur, "l_out", il);
  5721. // input for next layer
  5722. inpL = cur;
  5723. }
  5724. cur = inpL;
  5725. cur = llm_build_norm(ctx0, cur, hparams,
  5726. model.output_norm, NULL,
  5727. LLM_NORM_RMS, cb, -1);
  5728. cb(cur, "result_norm", -1);
  5729. // lm_head
  5730. cur = ggml_mul_mat(ctx0, model.output, cur);
  5731. cb(cur, "result_output", -1);
  5732. ggml_build_forward_expand(gf, cur);
  5733. return gf;
  5734. }
  5735. struct ggml_cgraph * build_gpt2() {
  5736. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5737. const int64_t n_embd_head = hparams.n_embd_head_v;
  5738. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5739. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5740. struct ggml_tensor * cur;
  5741. struct ggml_tensor * pos;
  5742. struct ggml_tensor * inpL;
  5743. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5744. cb(inpL, "inp_embd", -1);
  5745. // inp_pos - contains the positions
  5746. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5747. cb(inp_pos, "inp_pos", -1);
  5748. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5749. 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);
  5750. cb(KQ_mask, "KQ_mask", -1);
  5751. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5752. cb(pos, "pos_embd", -1);
  5753. inpL = ggml_add(ctx0, inpL, pos);
  5754. cb(inpL, "inpL", -1);
  5755. for (int il = 0; il < n_layer; ++il) {
  5756. cur = llm_build_norm(ctx0, inpL, hparams,
  5757. model.layers[il].attn_norm,
  5758. model.layers[il].attn_norm_b,
  5759. LLM_NORM, cb, il);
  5760. cb(cur, "attn_norm", il);
  5761. // self-attention
  5762. {
  5763. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5764. cb(cur, "wqkv", il);
  5765. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5766. cb(cur, "bqkv", il);
  5767. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5768. 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)));
  5769. 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)));
  5770. cb(Qcur, "Qcur", il);
  5771. cb(Kcur, "Kcur", il);
  5772. cb(Vcur, "Vcur", il);
  5773. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5774. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5775. model.layers[il].wo, model.layers[il].bo,
  5776. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5777. cb(cur, "kqv_out", il);
  5778. }
  5779. // add the input
  5780. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5781. cb(ffn_inp, "ffn_inp", il);
  5782. // FF
  5783. {
  5784. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5785. model.layers[il].ffn_norm,
  5786. model.layers[il].ffn_norm_b,
  5787. LLM_NORM, cb, il);
  5788. cb(cur, "ffn_norm", il);
  5789. cur = llm_build_ffn(ctx0, cur,
  5790. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5791. NULL, NULL,
  5792. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5793. NULL,
  5794. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5795. cb(cur, "ffn_out", il);
  5796. }
  5797. inpL = ggml_add(ctx0, cur, ffn_inp);
  5798. cb(inpL, "l_out", il);
  5799. }
  5800. cur = llm_build_norm(ctx0, inpL, hparams,
  5801. model.output_norm,
  5802. model.output_norm_b,
  5803. LLM_NORM, cb, -1);
  5804. cb(cur, "result_norm", -1);
  5805. cur = ggml_mul_mat(ctx0, model.output, cur);
  5806. cb(cur, "result_output", -1);
  5807. ggml_build_forward_expand(gf, cur);
  5808. return gf;
  5809. }
  5810. struct ggml_cgraph * build_codeshell() {
  5811. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5812. const int64_t n_embd_head = hparams.n_embd_head_v;
  5813. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5814. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5815. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5816. struct ggml_tensor * cur;
  5817. struct ggml_tensor * inpL;
  5818. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5819. cb(inpL, "inp_embd", -1);
  5820. // inp_pos - contains the positions
  5821. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5822. cb(inp_pos, "inp_pos", -1);
  5823. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5824. 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);
  5825. cb(KQ_mask, "KQ_mask", -1);
  5826. for (int il = 0; il < n_layer; ++il) {
  5827. cur = llm_build_norm(ctx0, inpL, hparams,
  5828. model.layers[il].attn_norm,
  5829. model.layers[il].attn_norm_b,
  5830. LLM_NORM, cb, il);
  5831. cb(cur, "attn_norm", il);
  5832. // self-attention
  5833. {
  5834. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5835. cb(cur, "wqkv", il);
  5836. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5837. cb(cur, "bqkv", il);
  5838. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5839. 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)));
  5840. 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)));
  5841. cb(tmpq, "tmpq", il);
  5842. cb(tmpk, "tmpk", il);
  5843. cb(Vcur, "Vcur", il);
  5844. struct ggml_tensor * Qcur = ggml_rope_custom(
  5845. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5846. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5847. ext_factor, attn_factor, beta_fast, beta_slow
  5848. );
  5849. cb(Qcur, "Qcur", il);
  5850. struct ggml_tensor * Kcur = ggml_rope_custom(
  5851. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5852. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5853. ext_factor, attn_factor, beta_fast, beta_slow
  5854. );
  5855. cb(Kcur, "Kcur", il);
  5856. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5857. model.layers[il].wo, model.layers[il].bo,
  5858. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5859. cb(cur, "kqv_out", il);
  5860. }
  5861. // add the input
  5862. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5863. cb(ffn_inp, "ffn_inp", il);
  5864. // FF
  5865. {
  5866. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5867. model.layers[il].ffn_norm,
  5868. model.layers[il].ffn_norm_b,
  5869. LLM_NORM, cb, il);
  5870. cb(cur, "ffn_norm", il);
  5871. cur = llm_build_ffn(ctx0, cur,
  5872. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5873. NULL, NULL,
  5874. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5875. NULL,
  5876. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5877. cb(cur, "ffn_out", il);
  5878. }
  5879. inpL = ggml_add(ctx0, cur, ffn_inp);
  5880. cb(inpL, "l_out", il);
  5881. }
  5882. cur = llm_build_norm(ctx0, inpL, hparams,
  5883. model.output_norm,
  5884. model.output_norm_b,
  5885. LLM_NORM, cb, -1);
  5886. cb(cur, "result_norm", -1);
  5887. cur = ggml_mul_mat(ctx0, model.output, cur);
  5888. cb(cur, "result_output", -1);
  5889. ggml_build_forward_expand(gf, cur);
  5890. return gf;
  5891. }
  5892. struct ggml_cgraph * build_orion() {
  5893. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5894. const int64_t n_embd_head = hparams.n_embd_head_v;
  5895. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5896. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5897. struct ggml_tensor * cur;
  5898. struct ggml_tensor * inpL;
  5899. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5900. cb(inpL, "inp_embd", -1);
  5901. // inp_pos - contains the positions
  5902. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5903. cb(inp_pos, "inp_pos", -1);
  5904. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5905. 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);
  5906. cb(KQ_mask, "KQ_mask", -1);
  5907. for (int il = 0; il < n_layer; ++il) {
  5908. struct ggml_tensor * inpSA = inpL;
  5909. // norm
  5910. cur = llm_build_norm(ctx0, inpL, hparams,
  5911. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5912. LLM_NORM, cb, il);
  5913. cb(cur, "attn_norm", il);
  5914. // self-attention
  5915. {
  5916. // compute Q and K and RoPE them
  5917. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5918. cb(Qcur, "Qcur", il);
  5919. // if (model.layers[il].bq) {
  5920. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5921. // cb(Qcur, "Qcur", il);
  5922. // }
  5923. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5924. cb(Kcur, "Kcur", il);
  5925. // if (model.layers[il].bk) {
  5926. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5927. // cb(Kcur, "Kcur", il);
  5928. // }
  5929. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5930. cb(Vcur, "Vcur", il);
  5931. // if (model.layers[il].bv) {
  5932. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5933. // cb(Vcur, "Vcur", il);
  5934. // }
  5935. Qcur = ggml_rope_custom(
  5936. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5937. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5938. ext_factor, attn_factor, beta_fast, beta_slow
  5939. );
  5940. cb(Qcur, "Qcur", il);
  5941. Kcur = ggml_rope_custom(
  5942. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5943. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5944. ext_factor, attn_factor, beta_fast, beta_slow
  5945. );
  5946. cb(Kcur, "Kcur", il);
  5947. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5948. model.layers[il].wo, NULL,
  5949. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5950. cb(cur, "kqv_out", il);
  5951. }
  5952. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5953. cb(ffn_inp, "ffn_inp", il);
  5954. // feed-forward network
  5955. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5956. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  5957. LLM_NORM, cb, il);
  5958. cb(cur, "ffn_norm", il);
  5959. cur = llm_build_ffn(ctx0, cur,
  5960. model.layers[il].ffn_up, NULL,
  5961. model.layers[il].ffn_gate, NULL,
  5962. model.layers[il].ffn_down, NULL,
  5963. NULL,
  5964. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5965. cb(cur, "ffn_out", il);
  5966. cur = ggml_add(ctx0, cur, ffn_inp);
  5967. cb(cur, "l_out", il);
  5968. // input for next layer
  5969. inpL = cur;
  5970. }
  5971. cur = inpL;
  5972. cur = llm_build_norm(ctx0, cur, hparams,
  5973. model.output_norm, model.output_norm_b,
  5974. LLM_NORM, cb, -1);
  5975. cb(cur, "result_norm", -1);
  5976. // lm_head
  5977. cur = ggml_mul_mat(ctx0, model.output, cur);
  5978. cb(cur, "result_output", -1);
  5979. ggml_build_forward_expand(gf, cur);
  5980. return gf;
  5981. }
  5982. struct ggml_cgraph * build_internlm2() {
  5983. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5984. const int64_t n_embd_head = hparams.n_embd_head_v;
  5985. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5986. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5987. struct ggml_tensor * cur;
  5988. struct ggml_tensor * inpL;
  5989. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5990. cb(inpL, "inp_embd", -1);
  5991. // inp_pos - contains the positions
  5992. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5993. cb(inp_pos, "inp_pos", -1);
  5994. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5995. 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);
  5996. cb(KQ_mask, "KQ_mask", -1);
  5997. for (int il = 0; il < n_layer; ++il) {
  5998. struct ggml_tensor * inpSA = inpL;
  5999. // norm
  6000. cur = llm_build_norm(ctx0, inpL, hparams,
  6001. model.layers[il].attn_norm, NULL,
  6002. LLM_NORM_RMS, cb, il);
  6003. cb(cur, "attn_norm", il);
  6004. // self-attention
  6005. {
  6006. // compute Q and K and RoPE them
  6007. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6008. cb(Qcur, "Qcur", il);
  6009. if (model.layers[il].bq) {
  6010. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6011. cb(Qcur, "Qcur", il);
  6012. }
  6013. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6014. cb(Kcur, "Kcur", il);
  6015. if (model.layers[il].bk) {
  6016. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6017. cb(Kcur, "Kcur", il);
  6018. }
  6019. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6020. cb(Vcur, "Vcur", il);
  6021. if (model.layers[il].bv) {
  6022. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6023. cb(Vcur, "Vcur", il);
  6024. }
  6025. Qcur = ggml_rope_custom(
  6026. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6027. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6028. ext_factor, attn_factor, beta_fast, beta_slow
  6029. );
  6030. cb(Qcur, "Qcur", il);
  6031. Kcur = ggml_rope_custom(
  6032. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6033. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6034. ext_factor, attn_factor, beta_fast, beta_slow
  6035. );
  6036. cb(Kcur, "Kcur", il);
  6037. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6038. model.layers[il].wo, model.layers[il].bo,
  6039. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6040. cb(cur, "kqv_out", il);
  6041. }
  6042. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6043. cb(ffn_inp, "ffn_inp", il);
  6044. // feed-forward network
  6045. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6046. model.layers[il].ffn_norm, NULL,
  6047. LLM_NORM_RMS, cb, il);
  6048. cb(cur, "ffn_norm", il);
  6049. cur = llm_build_ffn(ctx0, cur,
  6050. model.layers[il].ffn_up, NULL,
  6051. model.layers[il].ffn_gate, NULL,
  6052. model.layers[il].ffn_down, NULL,
  6053. NULL,
  6054. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6055. cb(cur, "ffn_out", il);
  6056. cur = ggml_add(ctx0, cur, ffn_inp);
  6057. cb(cur, "l_out", il);
  6058. // input for next layer
  6059. inpL = cur;
  6060. }
  6061. cur = inpL;
  6062. cur = llm_build_norm(ctx0, cur, hparams,
  6063. model.output_norm, NULL,
  6064. LLM_NORM_RMS, cb, -1);
  6065. cb(cur, "result_norm", -1);
  6066. // lm_head
  6067. cur = ggml_mul_mat(ctx0, model.output, cur);
  6068. cb(cur, "result_output", -1);
  6069. ggml_build_forward_expand(gf, cur);
  6070. return gf;
  6071. }
  6072. // ref: https://arxiv.org/abs/2203.03466
  6073. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6074. // based on the original build_llama() function
  6075. struct ggml_cgraph * build_minicpm() {
  6076. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6077. const int64_t n_embd_head = hparams.n_embd_head_v;
  6078. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6079. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6080. const int64_t n_embd = hparams.n_embd;
  6081. //TODO: if the model varies, these parameters need to be read from the model
  6082. const int64_t n_embd_base = 256;
  6083. const float scale_embd = 12.0f;
  6084. const float scale_depth = 1.4f;
  6085. struct ggml_tensor * cur;
  6086. struct ggml_tensor * inpL;
  6087. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6088. cb(inpL, "inp_embd", -1);
  6089. // scale the input embeddings
  6090. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6091. cb(inpL, "inp_scaled", -1);
  6092. // inp_pos - contains the positions
  6093. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6094. cb(inp_pos, "inp_pos", -1);
  6095. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6096. 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);
  6097. cb(KQ_mask, "KQ_mask", -1);
  6098. for (int il = 0; il < n_layer; ++il) {
  6099. struct ggml_tensor * inpSA = inpL;
  6100. // norm
  6101. cur = llm_build_norm(ctx0, inpL, hparams,
  6102. model.layers[il].attn_norm, NULL,
  6103. LLM_NORM_RMS, cb, il);
  6104. cb(cur, "attn_norm", il);
  6105. // self-attention
  6106. {
  6107. // compute Q and K and RoPE them
  6108. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6109. cb(Qcur, "Qcur", il);
  6110. if (model.layers[il].bq) {
  6111. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6112. cb(Qcur, "Qcur", il);
  6113. }
  6114. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6115. cb(Kcur, "Kcur", il);
  6116. if (model.layers[il].bk) {
  6117. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6118. cb(Kcur, "Kcur", il);
  6119. }
  6120. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6121. cb(Vcur, "Vcur", il);
  6122. if (model.layers[il].bv) {
  6123. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6124. cb(Vcur, "Vcur", il);
  6125. }
  6126. Qcur = ggml_rope_custom(
  6127. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6128. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6129. ext_factor, attn_factor, beta_fast, beta_slow
  6130. );
  6131. cb(Qcur, "Qcur", il);
  6132. Kcur = ggml_rope_custom(
  6133. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6134. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6135. ext_factor, attn_factor, beta_fast, beta_slow
  6136. );
  6137. cb(Kcur, "Kcur", il);
  6138. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6139. model.layers[il].wo, model.layers[il].bo,
  6140. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6141. cb(cur, "kqv_out", il);
  6142. }
  6143. // scale_res - scale the hidden states for residual connection
  6144. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6145. cur = ggml_scale(ctx0, cur, scale_res);
  6146. cb(cur, "hidden_scaled", -1);
  6147. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6148. cb(ffn_inp, "ffn_inp", il);
  6149. // feed-forward network
  6150. {
  6151. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6152. model.layers[il].ffn_norm, NULL,
  6153. LLM_NORM_RMS, cb, il);
  6154. cb(cur, "ffn_norm", il);
  6155. cur = llm_build_ffn(ctx0, cur,
  6156. model.layers[il].ffn_up, NULL,
  6157. model.layers[il].ffn_gate, NULL,
  6158. model.layers[il].ffn_down, NULL,
  6159. NULL,
  6160. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6161. cb(cur, "ffn_out", il);
  6162. }
  6163. // scale the hidden states for residual connection
  6164. cur = ggml_scale(ctx0, cur, scale_res);
  6165. cb(cur, "hidden_scaled_ffn", -1);
  6166. cur = ggml_add(ctx0, cur, ffn_inp);
  6167. cb(cur, "l_out", il);
  6168. // input for next layer
  6169. inpL = cur;
  6170. }
  6171. cur = inpL;
  6172. cur = llm_build_norm(ctx0, cur, hparams,
  6173. model.output_norm, NULL,
  6174. LLM_NORM_RMS, cb, -1);
  6175. cb(cur, "result_norm", -1);
  6176. // lm_head scaling
  6177. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6178. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6179. cb(cur, "lmhead_scaling", -1);
  6180. // lm_head
  6181. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6182. cb(cur, "result_output", -1);
  6183. ggml_build_forward_expand(gf, cur);
  6184. return gf;
  6185. }
  6186. struct ggml_cgraph * build_gemma() {
  6187. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6188. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6189. struct ggml_tensor * cur;
  6190. struct ggml_tensor * inpL;
  6191. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6192. cb(inpL, "inp_embd", -1);
  6193. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6194. cb(inpL, "inp_scaled", -1);
  6195. // inp_pos - contains the positions
  6196. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6197. cb(inp_pos, "inp_pos", -1);
  6198. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6199. 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);
  6200. cb(KQ_mask, "KQ_mask", -1);
  6201. for (int il = 0; il < n_layer; ++il) {
  6202. // norm
  6203. cur = llm_build_norm(ctx0, inpL, hparams,
  6204. model.layers[il].attn_norm, NULL,
  6205. LLM_NORM_RMS, cb, il);
  6206. cb(cur, "attn_norm", il);
  6207. // self-attention
  6208. {
  6209. // compute Q and K and RoPE them
  6210. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6211. cb(Qcur, "Qcur", il);
  6212. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6213. cb(Kcur, "Kcur", il);
  6214. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6215. cb(Vcur, "Vcur", il);
  6216. Qcur = ggml_rope_custom(
  6217. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6218. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6219. ext_factor, attn_factor, beta_fast, beta_slow);
  6220. cb(Qcur, "Qcur", il);
  6221. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6222. cb(Qcur, "Qcur_scaled", il);
  6223. Kcur = ggml_rope_custom(
  6224. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6225. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6226. ext_factor, attn_factor, beta_fast, beta_slow);
  6227. cb(Kcur, "Kcur", il);
  6228. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6229. model.layers[il].wo, NULL,
  6230. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6231. cb(cur, "kqv_out", il);
  6232. }
  6233. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6234. cb(sa_out, "sa_out", il);
  6235. cur = llm_build_norm(ctx0, sa_out, hparams,
  6236. model.layers[il].ffn_norm, NULL,
  6237. LLM_NORM_RMS, cb, il);
  6238. cb(cur, "ffn_norm", il);
  6239. // feed-forward network
  6240. {
  6241. cur = llm_build_ffn(ctx0, cur,
  6242. model.layers[il].ffn_up, NULL,
  6243. model.layers[il].ffn_gate, NULL,
  6244. model.layers[il].ffn_down, NULL,
  6245. NULL,
  6246. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6247. cb(cur, "ffn_out", il);
  6248. }
  6249. cur = ggml_add(ctx0, cur, sa_out);
  6250. cb(cur, "l_out", il);
  6251. // input for next layer
  6252. inpL = cur;
  6253. }
  6254. cur = inpL;
  6255. cur = llm_build_norm(ctx0, cur, hparams,
  6256. model.output_norm, NULL,
  6257. LLM_NORM_RMS, cb, -1);
  6258. cb(cur, "result_norm", -1);
  6259. // lm_head
  6260. cur = ggml_mul_mat(ctx0, model.output, cur);
  6261. cb(cur, "result_output", -1);
  6262. ggml_build_forward_expand(gf, cur);
  6263. return gf;
  6264. }
  6265. };
  6266. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  6267. llama_batch dummy;
  6268. dummy.n_tokens = 0;
  6269. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6270. struct llm_build_context llm(lctx, dummy, cb, false);
  6271. llm.init();
  6272. struct ggml_cgraph * result = llm.build_defrag(ids);
  6273. llm.free();
  6274. return result;
  6275. }
  6276. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  6277. llama_batch dummy;
  6278. dummy.n_tokens = 0;
  6279. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6280. struct llm_build_context llm(lctx, dummy, cb, false);
  6281. llm.init();
  6282. struct ggml_cgraph * result = llm.build_k_shift();
  6283. llm.free();
  6284. return result;
  6285. }
  6286. static struct ggml_cgraph * llama_build_graph(
  6287. llama_context & lctx,
  6288. const llama_batch & batch,
  6289. bool worst_case) {
  6290. const auto & model = lctx.model;
  6291. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6292. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6293. if (il >= 0) {
  6294. ggml_format_name(cur, "%s-%d", name, il);
  6295. } else {
  6296. ggml_set_name(cur, name);
  6297. }
  6298. if (!lctx.cparams.offload_kqv) {
  6299. if (strcmp(name, "kqv_merged_cont") == 0) {
  6300. // all nodes between the KV store and the attention output are run on the CPU
  6301. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6302. }
  6303. }
  6304. };
  6305. struct ggml_cgraph * result = NULL;
  6306. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6307. llm.init();
  6308. switch (model.arch) {
  6309. case LLM_ARCH_LLAMA:
  6310. {
  6311. result = llm.build_llama();
  6312. } break;
  6313. case LLM_ARCH_BAICHUAN:
  6314. {
  6315. result = llm.build_baichuan();
  6316. } break;
  6317. case LLM_ARCH_FALCON:
  6318. {
  6319. result = llm.build_falcon();
  6320. } break;
  6321. case LLM_ARCH_STARCODER:
  6322. {
  6323. result = llm.build_starcoder();
  6324. } break;
  6325. case LLM_ARCH_PERSIMMON:
  6326. {
  6327. result = llm.build_persimmon();
  6328. } break;
  6329. case LLM_ARCH_REFACT:
  6330. {
  6331. result = llm.build_refact();
  6332. } break;
  6333. case LLM_ARCH_BERT:
  6334. case LLM_ARCH_NOMIC_BERT:
  6335. {
  6336. result = llm.build_bert();
  6337. } break;
  6338. case LLM_ARCH_BLOOM:
  6339. {
  6340. result = llm.build_bloom();
  6341. } break;
  6342. case LLM_ARCH_MPT:
  6343. {
  6344. result = llm.build_mpt();
  6345. } break;
  6346. case LLM_ARCH_STABLELM:
  6347. {
  6348. result = llm.build_stablelm();
  6349. } break;
  6350. case LLM_ARCH_QWEN:
  6351. {
  6352. result = llm.build_qwen();
  6353. } break;
  6354. case LLM_ARCH_QWEN2:
  6355. {
  6356. result = llm.build_qwen2();
  6357. } break;
  6358. case LLM_ARCH_PHI2:
  6359. {
  6360. result = llm.build_phi2();
  6361. } break;
  6362. case LLM_ARCH_PLAMO:
  6363. {
  6364. result = llm.build_plamo();
  6365. } break;
  6366. case LLM_ARCH_GPT2:
  6367. {
  6368. result = llm.build_gpt2();
  6369. } break;
  6370. case LLM_ARCH_CODESHELL:
  6371. {
  6372. result = llm.build_codeshell();
  6373. } break;
  6374. case LLM_ARCH_ORION:
  6375. {
  6376. result = llm.build_orion();
  6377. } break;
  6378. case LLM_ARCH_INTERNLM2:
  6379. {
  6380. result = llm.build_internlm2();
  6381. } break;
  6382. case LLM_ARCH_MINICPM:
  6383. {
  6384. result = llm.build_minicpm();
  6385. } break;
  6386. case LLM_ARCH_GEMMA:
  6387. {
  6388. result = llm.build_gemma();
  6389. } break;
  6390. default:
  6391. GGML_ASSERT(false);
  6392. }
  6393. llm.free();
  6394. return result;
  6395. }
  6396. static void llama_set_k_shift(llama_context & lctx) {
  6397. const auto & cparams = lctx.cparams;
  6398. const int64_t n_ctx = cparams.n_ctx;
  6399. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6400. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6401. for (int i = 0; i < n_ctx; ++i) {
  6402. data[i] = lctx.kv_self.cells[i].delta;
  6403. }
  6404. }
  6405. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6406. //
  6407. // set input data
  6408. //
  6409. const auto & hparams = lctx.model.hparams;
  6410. const auto & cparams = lctx.cparams;
  6411. const auto & kv_self = lctx.kv_self;
  6412. if (batch.token) {
  6413. const int64_t n_tokens = batch.n_tokens;
  6414. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6415. }
  6416. if (batch.embd) {
  6417. const int64_t n_embd = hparams.n_embd;
  6418. const int64_t n_tokens = batch.n_tokens;
  6419. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6420. }
  6421. if (batch.pos) {
  6422. const int64_t n_tokens = batch.n_tokens;
  6423. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6424. }
  6425. {
  6426. const int64_t n_kv = kv_self.n;
  6427. const int64_t n_tokens = batch.n_tokens;
  6428. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6429. float * data = (float *) lctx.inp_KQ_mask->data;
  6430. for (int h = 0; h < 1; ++h) {
  6431. for (int j = 0; j < n_tokens; ++j) {
  6432. const llama_pos pos = batch.pos[j];
  6433. const llama_seq_id seq_id = batch.seq_id[j][0];
  6434. for (int i = 0; i < n_kv; ++i) {
  6435. float f;
  6436. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) ||
  6437. (hparams.causal_attn && lctx.kv_self.cells[i].pos > pos)) {
  6438. f = -INFINITY;
  6439. } else {
  6440. f = 0;
  6441. }
  6442. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6443. }
  6444. }
  6445. }
  6446. }
  6447. if (hparams.need_kq_pos) {
  6448. const int64_t n_kv = kv_self.n;
  6449. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6450. float * data = (float *) lctx.inp_KQ_pos->data;
  6451. for (int i = 0; i < n_kv; ++i) {
  6452. data[i] = float(lctx.kv_self.cells[i].pos);
  6453. }
  6454. }
  6455. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  6456. const int64_t n_tokens = batch.n_tokens;
  6457. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6458. float * data = (float *) lctx.inp_mean->data;
  6459. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6460. std::vector<uint64_t> sum(n_tokens, 0);
  6461. for (int i = 0; i < n_tokens; ++i) {
  6462. const llama_seq_id seq_id = batch.seq_id[i][0];
  6463. sum[seq_id] += 1;
  6464. }
  6465. std::vector<float> div(n_tokens, 0.0f);
  6466. for (int i = 0; i < n_tokens; ++i) {
  6467. const uint64_t s = sum[i];
  6468. if (s > 0) {
  6469. div[i] = 1.0f/float(s);
  6470. }
  6471. }
  6472. for (int i = 0; i < n_tokens; ++i) {
  6473. const llama_seq_id seq_id = batch.seq_id[i][0];
  6474. data[seq_id*n_tokens + i] = div[seq_id];
  6475. }
  6476. }
  6477. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  6478. const int64_t n_tokens = batch.n_tokens;
  6479. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6480. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6481. for (int i = 0; i < n_tokens; ++i) {
  6482. const llama_seq_id seq_id = batch.seq_id[i][0];
  6483. const llama_pos pos = batch.pos[i];
  6484. if (pos == 0) {
  6485. data[seq_id] = i;
  6486. }
  6487. }
  6488. }
  6489. }
  6490. static void llama_graph_compute(
  6491. llama_context & lctx,
  6492. ggml_cgraph * gf,
  6493. int n_threads) {
  6494. #ifdef GGML_USE_MPI
  6495. const int64_t n_layer = lctx.model.hparams.n_layer;
  6496. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6497. #endif
  6498. #ifdef GGML_USE_METAL
  6499. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6500. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6501. }
  6502. #endif
  6503. if (lctx.backend_cpu != nullptr) {
  6504. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6505. }
  6506. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6507. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6508. #ifdef GGML_USE_MPI
  6509. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6510. #endif
  6511. }
  6512. // decode a batch of tokens by evaluating the transformer
  6513. //
  6514. // - lctx: llama context
  6515. // - batch: batch to evaluate
  6516. //
  6517. // return 0 on success
  6518. // return positive int on warning
  6519. // return negative int on error
  6520. //
  6521. static int llama_decode_internal(
  6522. llama_context & lctx,
  6523. llama_batch batch) {
  6524. const uint32_t n_tokens = batch.n_tokens;
  6525. if (n_tokens == 0) {
  6526. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6527. return -1;
  6528. }
  6529. const auto & model = lctx.model;
  6530. const auto & hparams = model.hparams;
  6531. const auto & cparams = lctx.cparams;
  6532. const auto n_batch = cparams.n_batch;
  6533. GGML_ASSERT(n_tokens <= n_batch);
  6534. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6535. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6536. const int64_t t_start_us = ggml_time_us();
  6537. #ifdef GGML_USE_MPI
  6538. // TODO: needs fix after #3228
  6539. GGML_ASSERT(false && "not implemented");
  6540. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6541. #endif
  6542. GGML_ASSERT(n_threads > 0);
  6543. auto & kv_self = lctx.kv_self;
  6544. const int64_t n_embd = hparams.n_embd;
  6545. const int64_t n_vocab = hparams.n_vocab;
  6546. // helpers for smoother batch API transition
  6547. // after deprecating the llama_eval calls, these will be removed
  6548. std::vector<llama_pos> pos;
  6549. std::vector<int32_t> n_seq_id;
  6550. std::vector<llama_seq_id *> seq_id_arr;
  6551. std::vector<std::vector<llama_seq_id>> seq_id;
  6552. if (batch.pos == nullptr) {
  6553. pos.resize(n_tokens);
  6554. for (uint32_t i = 0; i < n_tokens; i++) {
  6555. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6556. }
  6557. batch.pos = pos.data();
  6558. }
  6559. if (batch.seq_id == nullptr) {
  6560. n_seq_id.resize(n_tokens);
  6561. seq_id.resize(n_tokens);
  6562. seq_id_arr.resize(n_tokens);
  6563. for (uint32_t i = 0; i < n_tokens; i++) {
  6564. n_seq_id[i] = 1;
  6565. seq_id[i].resize(1);
  6566. seq_id[i][0] = batch.all_seq_id;
  6567. seq_id_arr[i] = seq_id[i].data();
  6568. }
  6569. batch.n_seq_id = n_seq_id.data();
  6570. batch.seq_id = seq_id_arr.data();
  6571. }
  6572. llama_kv_cache_update(&lctx);
  6573. // if we have enough unused cells before the current head ->
  6574. // better to start searching from the beginning of the cache, hoping to fill it
  6575. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6576. kv_self.head = 0;
  6577. }
  6578. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6579. return 1;
  6580. }
  6581. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6582. // after enough generations, the benefit from this heuristic disappears
  6583. // if we start defragmenting the cache, the benefit from this will be more important
  6584. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6585. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6586. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6587. ggml_backend_sched_reset(lctx.sched);
  6588. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6589. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6590. // the output is always the last tensor in the graph
  6591. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6592. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  6593. if (strcmp(res->name, "result_output") == 0) {
  6594. // the embeddings could be the second to last tensor, or the third to last tensor
  6595. if (strcmp(embeddings->name, "result_norm") != 0) {
  6596. embeddings = gf->nodes[gf->n_nodes - 3];
  6597. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  6598. }
  6599. } else if (strcmp(res->name, "result_embd") == 0) {
  6600. embeddings = res;
  6601. res = nullptr;
  6602. } else {
  6603. GGML_ASSERT(false);
  6604. }
  6605. // 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);
  6606. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6607. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6608. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6609. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6610. // with the BLAS calls. need a better solution
  6611. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6612. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6613. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6614. n_threads = std::min(4, n_threads);
  6615. }
  6616. llama_set_inputs(lctx, batch);
  6617. llama_graph_compute(lctx, gf, n_threads);
  6618. // update the kv ring buffer
  6619. {
  6620. kv_self.head += n_tokens;
  6621. // Ensure kv cache head points to a valid index.
  6622. if (kv_self.head >= kv_self.size) {
  6623. kv_self.head = 0;
  6624. }
  6625. }
  6626. // decide if we need to defrag the kv cache
  6627. if (cparams.defrag_thold >= 0.0f) {
  6628. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used + n_tokens)/float(kv_self.n) : 0.0f;
  6629. // queue defragmentation for next llama_kv_cache_update
  6630. if (fragmentation > cparams.defrag_thold) {
  6631. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  6632. llama_kv_cache_defrag(kv_self);
  6633. }
  6634. }
  6635. #ifdef GGML_PERF
  6636. // print timing information per ggml operation (for debugging purposes)
  6637. // requires GGML_PERF to be defined
  6638. ggml_graph_print(gf);
  6639. #endif
  6640. // plot the computation graph in dot format (for debugging purposes)
  6641. //if (n_past%100 == 0) {
  6642. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6643. //}
  6644. // extract logits
  6645. // TODO: do not compute and extract logits if only embeddings are needed
  6646. // need to update the graphs to skip "result_output"
  6647. if (res) {
  6648. auto & logits_out = lctx.logits;
  6649. #ifndef NDEBUG
  6650. auto & logits_valid = lctx.logits_valid;
  6651. logits_valid.clear();
  6652. logits_valid.resize(n_tokens);
  6653. logits_out.clear();
  6654. #endif
  6655. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6656. GGML_ASSERT(res_backend != nullptr);
  6657. if (batch.logits) {
  6658. logits_out.resize(n_vocab * n_tokens);
  6659. for (uint32_t i = 0; i < n_tokens; i++) {
  6660. if (batch.logits[i] == 0) {
  6661. continue;
  6662. }
  6663. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6664. #ifndef NDEBUG
  6665. logits_valid[i] = true;
  6666. #endif
  6667. }
  6668. } else if (lctx.logits_all) {
  6669. logits_out.resize(n_vocab * n_tokens);
  6670. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6671. #ifndef NDEBUG
  6672. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6673. #endif
  6674. } else {
  6675. logits_out.resize(n_vocab);
  6676. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6677. #ifndef NDEBUG
  6678. logits_valid[0] = true;
  6679. #endif
  6680. }
  6681. ggml_backend_synchronize(res_backend);
  6682. }
  6683. // extract embeddings
  6684. if (!lctx.embedding.empty()) {
  6685. auto & embedding_out = lctx.embedding;
  6686. const int64_t embd_pos = res ? n_embd * (n_tokens-1) : 0;
  6687. const int64_t embd_size = res ? n_embd : n_embd * n_tokens;
  6688. embedding_out.resize(embd_size);
  6689. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  6690. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), embd_pos*sizeof(float), embd_size*sizeof(float));
  6691. ggml_backend_synchronize(embeddings_backend);
  6692. }
  6693. // measure the performance only for the single-token evals
  6694. if (n_tokens == 1) {
  6695. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6696. lctx.n_eval++;
  6697. }
  6698. else if (n_tokens > 1) {
  6699. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6700. lctx.n_p_eval += n_tokens;
  6701. }
  6702. // get a more accurate load time, upon first eval
  6703. // TODO: fix this
  6704. if (!lctx.has_evaluated_once) {
  6705. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6706. lctx.has_evaluated_once = true;
  6707. }
  6708. return 0;
  6709. }
  6710. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  6711. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  6712. auto & kv_self = lctx.kv_self;
  6713. const auto & hparams = lctx.model.hparams;
  6714. const uint32_t n_layer = hparams.n_layer;
  6715. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  6716. const uint32_t n_used = kv_self.used;
  6717. assert(n_used <= n_kv);
  6718. //const int64_t t_start = ggml_time_us();
  6719. // number of cells moved
  6720. uint32_t n_moves = 0;
  6721. // determine which KV cells to move where
  6722. //
  6723. // cell i moves to ids[i]
  6724. //
  6725. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  6726. //
  6727. std::vector<uint32_t> ids(n_kv, n_kv);
  6728. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  6729. const auto & cell0 = kv_self.cells[i0];
  6730. if (!cell0.is_empty()) {
  6731. ids[i0] = i0;
  6732. continue;
  6733. }
  6734. // found a hole - fill it with data from the end of the cache
  6735. uint32_t nh = 1;
  6736. // determine the size of the hole
  6737. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  6738. nh++;
  6739. }
  6740. // each move requires 6*n_layer tensors (see build_defrag)
  6741. // - source view, destination view, copy operation
  6742. // - x2 for keys and values
  6743. //
  6744. if (6*(n_moves + nh)*n_layer >= LLAMA_MAX_NODES) {
  6745. // the graph is too big, we cannot move more cells
  6746. break;
  6747. }
  6748. uint32_t nf = 0;
  6749. uint32_t is = n_kv - 1;
  6750. // starting from the end, find nh non-empty cells
  6751. for (; is > i0; --is) {
  6752. const auto & cell1 = kv_self.cells[is];
  6753. if (cell1.is_empty() || ids[is] != n_kv) {
  6754. continue;
  6755. }
  6756. // non-empty cell which is not yet moved
  6757. nf++;
  6758. if (nf == nh) {
  6759. break;
  6760. }
  6761. }
  6762. // this can only happen if `n_used` is not accurate, which would be a bug
  6763. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  6764. nf = 0;
  6765. uint32_t i1 = is;
  6766. // are we moving a continuous block of memory?
  6767. bool cont = false;
  6768. // go back and move the nf cells to the hole
  6769. for (; i1 < n_kv; ++i1) {
  6770. auto & cell1 = kv_self.cells[i1];
  6771. if (cell1.is_empty() || ids[i1] != n_kv) {
  6772. cont = false;
  6773. continue;
  6774. }
  6775. // this cell goes to (i0 + nf)
  6776. ids[i1] = i0 + nf;
  6777. // move the cell meta data
  6778. kv_self.cells[i0 + nf] = cell1;
  6779. // clear the old cell and move the head there
  6780. cell1 = llama_kv_cell();
  6781. kv_self.head = n_used;
  6782. if (!cont) {
  6783. n_moves++;
  6784. cont = true;
  6785. }
  6786. nf++;
  6787. if (nf == nh) {
  6788. break;
  6789. }
  6790. }
  6791. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  6792. i0 += nh - 1;
  6793. }
  6794. if (n_moves == 0) {
  6795. return;
  6796. }
  6797. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  6798. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  6799. #if 0
  6800. // CPU defrag
  6801. //
  6802. // TODO: optimizations are possible:
  6803. // - multiple threads
  6804. // - avoid copying to the host memory when already there
  6805. //
  6806. // likely not worth the effort, as we have ggml_graph based defrag
  6807. //
  6808. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6809. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6810. const uint32_t kv_size = kv_self.size;
  6811. std::vector<uint8_t> buf_k;
  6812. std::vector<uint8_t> buf_v;
  6813. for (uint32_t il = 0; il < n_layer; ++il) {
  6814. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  6815. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  6816. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  6817. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  6818. buf_k.resize(k_size);
  6819. buf_v.resize(v_size);
  6820. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  6821. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  6822. // batch move [i, i+nm) to [id, id+nm)
  6823. // note: cells can move only to a lower index
  6824. for (uint32_t i = 0; i < n_kv; ++i) {
  6825. const uint32_t id = ids[i];
  6826. if (i == id || id == n_kv) {
  6827. continue;
  6828. }
  6829. uint32_t nm = 1;
  6830. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  6831. nm++;
  6832. }
  6833. // move keys
  6834. {
  6835. const int64_t os = i*k_size_row;
  6836. const int64_t od = id*k_size_row;
  6837. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  6838. }
  6839. // move values (note: they are transposed)
  6840. {
  6841. const int64_t os = i;
  6842. const int64_t od = id;
  6843. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  6844. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  6845. }
  6846. }
  6847. i += nm - 1;
  6848. }
  6849. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  6850. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  6851. }
  6852. #else
  6853. // ggml_graph defrag
  6854. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  6855. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  6856. #endif
  6857. //const int64_t t_end = ggml_time_us();
  6858. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  6859. }
  6860. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  6861. // apply K-shift if needed
  6862. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  6863. llama_set_k_shift(lctx);
  6864. {
  6865. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  6866. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  6867. }
  6868. {
  6869. auto & kv_self = lctx.kv_self;
  6870. kv_self.has_shift = false;
  6871. for (uint32_t i = 0; i < kv_self.size; ++i) {
  6872. kv_self.cells[i].delta = 0;
  6873. }
  6874. }
  6875. }
  6876. // defragment the KV cache if needed
  6877. if (lctx.kv_self.do_defrag) {
  6878. llama_kv_cache_defrag_internal(lctx);
  6879. lctx.kv_self.do_defrag = false;
  6880. }
  6881. }
  6882. //
  6883. // tokenizer
  6884. //
  6885. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  6886. return vocab.type;
  6887. }
  6888. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  6889. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  6890. }
  6891. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  6892. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  6893. }
  6894. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  6895. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  6896. }
  6897. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  6898. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  6899. }
  6900. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  6901. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  6902. }
  6903. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  6904. GGML_ASSERT(llama_is_byte_token(vocab, id));
  6905. const auto& token_data = vocab.id_to_token.at(id);
  6906. switch (llama_vocab_get_type(vocab)) {
  6907. case LLAMA_VOCAB_TYPE_SPM: {
  6908. auto buf = token_data.text.substr(3, 2);
  6909. return strtol(buf.c_str(), NULL, 16);
  6910. }
  6911. case LLAMA_VOCAB_TYPE_BPE: {
  6912. GGML_ASSERT(false);
  6913. return unicode_to_bytes_bpe(token_data.text);
  6914. }
  6915. case LLAMA_VOCAB_TYPE_WPM: {
  6916. GGML_ASSERT(false);
  6917. }
  6918. default:
  6919. GGML_ASSERT(false);
  6920. }
  6921. }
  6922. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  6923. static const char * hex = "0123456789ABCDEF";
  6924. switch (llama_vocab_get_type(vocab)) {
  6925. case LLAMA_VOCAB_TYPE_SPM: {
  6926. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  6927. auto token = vocab.token_to_id.find(buf);
  6928. if (token != vocab.token_to_id.end()) {
  6929. return (*token).second;
  6930. }
  6931. // Try to fall back to just the byte as a string
  6932. const char buf2[2] = { (char)ch, 0 };
  6933. return vocab.token_to_id.at(buf2);
  6934. }
  6935. case LLAMA_VOCAB_TYPE_WPM:
  6936. case LLAMA_VOCAB_TYPE_BPE: {
  6937. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  6938. }
  6939. default:
  6940. GGML_ASSERT(false);
  6941. }
  6942. }
  6943. static void llama_escape_whitespace(std::string & text) {
  6944. replace_all(text, " ", "\xe2\x96\x81");
  6945. }
  6946. static void llama_unescape_whitespace(std::string & word) {
  6947. replace_all(word, "\xe2\x96\x81", " ");
  6948. }
  6949. struct llm_symbol {
  6950. using index = int;
  6951. index prev;
  6952. index next;
  6953. const char * text;
  6954. size_t n;
  6955. };
  6956. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  6957. // SPM tokenizer
  6958. // original implementation:
  6959. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  6960. struct llm_bigram_spm {
  6961. struct comparator {
  6962. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  6963. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  6964. }
  6965. };
  6966. using queue_storage = std::vector<llm_bigram_spm>;
  6967. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  6968. llm_symbol::index left;
  6969. llm_symbol::index right;
  6970. float score;
  6971. size_t size;
  6972. };
  6973. struct llm_tokenizer_spm {
  6974. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  6975. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6976. // split string into utf8 chars
  6977. int index = 0;
  6978. size_t offs = 0;
  6979. while (offs < text.size()) {
  6980. llm_symbol sym;
  6981. size_t len = utf8_len(text[offs]);
  6982. sym.text = text.c_str() + offs;
  6983. sym.n = std::min(len, text.size() - offs);
  6984. offs += sym.n;
  6985. sym.prev = index - 1;
  6986. sym.next = offs == text.size() ? -1 : index + 1;
  6987. index++;
  6988. symbols.emplace_back(sym);
  6989. }
  6990. // seed the work queue with all possible 2-character tokens.
  6991. for (size_t i = 1; i < symbols.size(); ++i) {
  6992. try_add_bigram(i - 1, i);
  6993. }
  6994. // keep substituting the highest frequency pairs for as long as we can.
  6995. while (!work_queue.empty()) {
  6996. auto bigram = work_queue.top();
  6997. work_queue.pop();
  6998. auto & left_sym = symbols[bigram.left];
  6999. auto & right_sym = symbols[bigram.right];
  7000. // if one of the symbols already got merged, skip it.
  7001. if (left_sym.n == 0 || right_sym.n == 0 ||
  7002. left_sym.n + right_sym.n != bigram.size) {
  7003. continue;
  7004. }
  7005. // merge the right sym into the left one
  7006. left_sym.n += right_sym.n;
  7007. right_sym.n = 0;
  7008. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  7009. // remove the right sym from the chain
  7010. left_sym.next = right_sym.next;
  7011. if (right_sym.next >= 0) {
  7012. symbols[right_sym.next].prev = bigram.left;
  7013. }
  7014. // find more substitutions
  7015. try_add_bigram(left_sym.prev, bigram.left);
  7016. try_add_bigram(bigram.left, left_sym.next);
  7017. }
  7018. for (int i = 0; i != -1; i = symbols[i].next) {
  7019. auto & symbol = symbols[i];
  7020. resegment(symbol, output);
  7021. }
  7022. }
  7023. private:
  7024. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  7025. auto text = std::string(symbol.text, symbol.n);
  7026. auto token = vocab.token_to_id.find(text);
  7027. // Do we need to support is_unused?
  7028. if (token != vocab.token_to_id.end()) {
  7029. output.push_back((*token).second);
  7030. return;
  7031. }
  7032. const auto p = rev_merge.find(text);
  7033. if (p == rev_merge.end()) {
  7034. // output any symbols that did not form tokens as bytes.
  7035. output.reserve(output.size() + symbol.n);
  7036. for (int j = 0; j < (int)symbol.n; ++j) {
  7037. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  7038. output.push_back(token_id);
  7039. }
  7040. return;
  7041. }
  7042. resegment(symbols[p->second.first], output);
  7043. resegment(symbols[p->second.second], output);
  7044. }
  7045. void try_add_bigram(int left, int right) {
  7046. if (left == -1 || right == -1) {
  7047. return;
  7048. }
  7049. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  7050. auto token = vocab.token_to_id.find(text);
  7051. if (token == vocab.token_to_id.end()) {
  7052. return;
  7053. }
  7054. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  7055. return;
  7056. }
  7057. const auto & tok_data = vocab.id_to_token[(*token).second];
  7058. llm_bigram_spm bigram;
  7059. bigram.left = left;
  7060. bigram.right = right;
  7061. bigram.score = tok_data.score;
  7062. bigram.size = text.size();
  7063. work_queue.push(bigram);
  7064. // Do we need to support is_unused?
  7065. rev_merge[text] = std::make_pair(left, right);
  7066. }
  7067. const llama_vocab & vocab;
  7068. std::vector<llm_symbol> symbols;
  7069. llm_bigram_spm::queue work_queue;
  7070. std::map<std::string, std::pair<int, int>> rev_merge;
  7071. };
  7072. // BPE tokenizer
  7073. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  7074. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  7075. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  7076. struct llm_bigram_bpe {
  7077. struct comparator {
  7078. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  7079. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  7080. }
  7081. };
  7082. using queue_storage = std::vector<llm_bigram_bpe>;
  7083. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  7084. llm_symbol::index left;
  7085. llm_symbol::index right;
  7086. std::string text;
  7087. int rank;
  7088. size_t size;
  7089. };
  7090. struct llm_tokenizer_bpe {
  7091. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  7092. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7093. int final_prev_index = -1;
  7094. auto word_collection = bpe_gpt2_preprocess(text);
  7095. symbols_final.clear();
  7096. for (auto & word : word_collection) {
  7097. work_queue = llm_bigram_bpe::queue();
  7098. symbols.clear();
  7099. int index = 0;
  7100. size_t offset = 0;
  7101. while (offset < word.size()) {
  7102. llm_symbol sym;
  7103. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  7104. sym.text = word.c_str() + offset;
  7105. sym.n = char_len;
  7106. offset += sym.n;
  7107. sym.prev = index - 1;
  7108. sym.next = offset == word.size() ? -1 : index + 1;
  7109. index++;
  7110. symbols.emplace_back(sym);
  7111. }
  7112. for (size_t i = 1; i < symbols.size(); ++i) {
  7113. add_new_bigram(i - 1, i);
  7114. }
  7115. // build token(s)
  7116. while (!work_queue.empty()) {
  7117. auto bigram = work_queue.top();
  7118. work_queue.pop();
  7119. auto & left_symbol = symbols[bigram.left];
  7120. auto & right_symbol = symbols[bigram.right];
  7121. if (left_symbol.n == 0 || right_symbol.n == 0) {
  7122. continue;
  7123. }
  7124. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  7125. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  7126. if (left_token + right_token != bigram.text) {
  7127. continue; // Skip this bigram if it's outdated
  7128. }
  7129. // merge the right sym into the left one
  7130. left_symbol.n += right_symbol.n;
  7131. right_symbol.n = 0;
  7132. // remove the right sym from the chain
  7133. left_symbol.next = right_symbol.next;
  7134. if (right_symbol.next >= 0) {
  7135. symbols[right_symbol.next].prev = bigram.left;
  7136. }
  7137. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  7138. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  7139. }
  7140. // add the fnished tokens to the final list keeping correct order for next and prev
  7141. for (auto & sym : symbols) {
  7142. if (sym.n > 0) {
  7143. sym.prev = final_prev_index;
  7144. sym.next = -1;
  7145. if (final_prev_index != -1) {
  7146. symbols_final[final_prev_index].next = symbols_final.size();
  7147. }
  7148. symbols_final.emplace_back(sym);
  7149. final_prev_index = symbols_final.size() - 1;
  7150. }
  7151. }
  7152. }
  7153. symbols = symbols_final;
  7154. if (!symbols.empty()) {
  7155. for (int i = 0; i != -1; i = symbols[i].next) {
  7156. auto & symbol = symbols[i];
  7157. if (symbol.n == 0) {
  7158. continue;
  7159. }
  7160. const std::string str = std::string(symbol.text, symbol.n);
  7161. const auto token = vocab.token_to_id.find(str);
  7162. if (token == vocab.token_to_id.end()) {
  7163. for (auto j = str.begin(); j != str.end(); ++j) {
  7164. std::string byte_str(1, *j);
  7165. auto token_multibyte = vocab.token_to_id.find(byte_str);
  7166. if (token_multibyte == vocab.token_to_id.end()) {
  7167. throw std::runtime_error("ERROR: byte not found in vocab");
  7168. }
  7169. output.push_back((*token_multibyte).second);
  7170. }
  7171. } else {
  7172. output.push_back((*token).second);
  7173. }
  7174. }
  7175. }
  7176. }
  7177. private:
  7178. void add_new_bigram(int left, int right) {
  7179. if (left == -1 || right == -1) {
  7180. return;
  7181. }
  7182. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  7183. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  7184. int rank_found = -1;
  7185. rank_found = vocab.find_bpe_rank(left_token, right_token);
  7186. if (rank_found < 0) {
  7187. return;
  7188. }
  7189. llm_bigram_bpe bigram;
  7190. bigram.left = left;
  7191. bigram.right = right;
  7192. bigram.text = left_token + right_token;
  7193. bigram.size = left_token.size() + right_token.size();
  7194. bigram.rank = rank_found;
  7195. work_queue.push(bigram);
  7196. }
  7197. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  7198. std::vector<std::string> bpe_words;
  7199. std::vector<std::string> bpe_encoded_words;
  7200. std::string token = "";
  7201. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  7202. bool collecting_numeric = false;
  7203. bool collecting_letter = false;
  7204. bool collecting_special = false;
  7205. bool collecting_whitespace_lookahead = false;
  7206. bool collecting = false;
  7207. std::vector<std::string> text_utf;
  7208. text_utf.reserve(text.size());
  7209. bpe_words.reserve(text.size());
  7210. bpe_encoded_words.reserve(text.size());
  7211. auto cps = codepoints_from_utf8(text);
  7212. for (size_t i = 0; i < cps.size(); ++i)
  7213. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7214. for (int i = 0; i < (int)text_utf.size(); i++) {
  7215. const std::string & utf_char = text_utf[i];
  7216. bool split_condition = false;
  7217. int bytes_remain = text_utf.size() - i;
  7218. // forward backward lookups
  7219. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7220. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7221. // handling contractions
  7222. if (!split_condition && bytes_remain >= 2) {
  7223. // 's|'t|'m|'d
  7224. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7225. split_condition = true;
  7226. }
  7227. if (split_condition) {
  7228. if (token.size()) {
  7229. bpe_words.emplace_back(token); // push previous content as token
  7230. }
  7231. token = utf_char + utf_char_next;
  7232. bpe_words.emplace_back(token);
  7233. token = "";
  7234. i++;
  7235. continue;
  7236. }
  7237. }
  7238. if (!split_condition && bytes_remain >= 3) {
  7239. // 're|'ve|'ll
  7240. if (utf_char == "\'" && (
  7241. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7242. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7243. (utf_char_next == "l" && utf_char_next_next == "l"))
  7244. ) {
  7245. split_condition = true;
  7246. }
  7247. if (split_condition) {
  7248. // current token + next token can be defined
  7249. if (token.size()) {
  7250. bpe_words.emplace_back(token); // push previous content as token
  7251. }
  7252. token = utf_char + utf_char_next + utf_char_next_next;
  7253. bpe_words.emplace_back(token); // the contraction
  7254. token = "";
  7255. i += 2;
  7256. continue;
  7257. }
  7258. }
  7259. if (!split_condition && !collecting) {
  7260. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7261. collecting_letter = true;
  7262. collecting = true;
  7263. }
  7264. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7265. collecting_numeric = true;
  7266. collecting = true;
  7267. }
  7268. else if (
  7269. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7270. (!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)
  7271. ) {
  7272. collecting_special = true;
  7273. collecting = true;
  7274. }
  7275. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7276. collecting_whitespace_lookahead = true;
  7277. collecting = true;
  7278. }
  7279. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7280. split_condition = true;
  7281. }
  7282. }
  7283. else if (!split_condition && collecting) {
  7284. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7285. split_condition = true;
  7286. }
  7287. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7288. split_condition = true;
  7289. }
  7290. 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)) {
  7291. split_condition = true;
  7292. }
  7293. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7294. split_condition = true;
  7295. }
  7296. }
  7297. if (utf_char_next == "") {
  7298. split_condition = true; // final
  7299. token += utf_char;
  7300. }
  7301. if (split_condition) {
  7302. if (token.size()) {
  7303. bpe_words.emplace_back(token);
  7304. }
  7305. token = utf_char;
  7306. collecting = false;
  7307. collecting_letter = false;
  7308. collecting_numeric = false;
  7309. collecting_special = false;
  7310. collecting_whitespace_lookahead = false;
  7311. }
  7312. else {
  7313. token += utf_char;
  7314. }
  7315. }
  7316. for (std::string & word : bpe_words) {
  7317. std::string encoded_token = "";
  7318. for (char & c : word) {
  7319. encoded_token += bytes_to_unicode_bpe(c);
  7320. }
  7321. bpe_encoded_words.emplace_back(encoded_token);
  7322. }
  7323. return bpe_encoded_words;
  7324. }
  7325. const llama_vocab & vocab;
  7326. std::vector<llm_symbol> symbols;
  7327. std::vector<llm_symbol> symbols_final;
  7328. llm_bigram_bpe::queue work_queue;
  7329. };
  7330. struct llm_tokenizer_wpm {
  7331. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7332. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7333. auto * token_map = &vocab.token_to_id;
  7334. // normalize and split by whitespace
  7335. std::vector<std::string> words = preprocess(text);
  7336. // bos token prepended already
  7337. // find the longest tokens that form the words
  7338. for (const std::string &word : words) {
  7339. // skip empty words
  7340. if (word.size() == 0) {
  7341. continue;
  7342. }
  7343. // prepend phantom space
  7344. std::string word1 = "\xe2\x96\x81" + word;
  7345. int n = word1.size();
  7346. // we're at the start of a new word
  7347. int i = 0;
  7348. bool match_any = false;
  7349. // move through character position in word
  7350. while (i < n) {
  7351. // loop through possible match length
  7352. bool match = false;
  7353. for (int j = n; j > i; j--) {
  7354. auto it = token_map->find(word1.substr(i, j - i));
  7355. if (it != token_map->end()) {
  7356. output.push_back(it->second);
  7357. match = true;
  7358. match_any = true;
  7359. i = j;
  7360. break;
  7361. }
  7362. }
  7363. // must be an unknown character
  7364. if (!match) {
  7365. i++;
  7366. }
  7367. }
  7368. // we didn't find any matches for this word
  7369. if (!match_any) {
  7370. output.push_back(vocab.special_unk_id);
  7371. }
  7372. }
  7373. // append eos token
  7374. output.push_back(vocab.special_eos_id);
  7375. }
  7376. std::vector<std::string> preprocess(const std::string & text) {
  7377. // normalalization form D
  7378. std::vector<uint32_t> codepoints = codepoints_from_utf8(text);
  7379. std::vector<uint32_t> nfd_codepoints;
  7380. for (uint32_t code : codepoints) {
  7381. auto it = nfd_map.find(code);
  7382. if (it != nfd_map.end()) {
  7383. for (uint32_t c : it->second) {
  7384. nfd_codepoints.push_back(c);
  7385. }
  7386. } else {
  7387. nfd_codepoints.push_back(code);
  7388. }
  7389. }
  7390. // strip accents, strip control, uniformize whitespace,
  7391. // to lowercase, pad chinese characters, pad punctuation
  7392. std::string new_str = "";
  7393. for (uint32_t code : nfd_codepoints) {
  7394. int type = codepoint_type(code);
  7395. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  7396. continue;
  7397. }
  7398. code = to_lower(code);
  7399. if (type == CODEPOINT_TYPE_WHITESPACE) {
  7400. code = ' ';
  7401. }
  7402. std::string s = codepoint_to_utf8(code);
  7403. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  7404. new_str += " ";
  7405. new_str += s;
  7406. new_str += " ";
  7407. } else {
  7408. new_str += s;
  7409. }
  7410. }
  7411. // split by whitespace
  7412. uint64_t l = 0;
  7413. uint64_t r = 0;
  7414. std::vector<std::string> words;
  7415. while (r < new_str.size()) {
  7416. // if is whitespace
  7417. if (isspace(new_str[r])) {
  7418. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7419. l = r + 1;
  7420. r = l;
  7421. }
  7422. else {
  7423. r += 1;
  7424. }
  7425. }
  7426. if (r > l) {
  7427. words.push_back(new_str.substr(l, (r - l)));
  7428. }
  7429. return words;
  7430. }
  7431. uint32_t to_lower(uint32_t code) {
  7432. #if defined(_WIN32)
  7433. if (code > 0xFFFF) {
  7434. return code;
  7435. }
  7436. #endif
  7437. return std::tolower(wchar_t(code), std::locale("en_US.UTF-8"));
  7438. }
  7439. bool is_ascii_punct(uint32_t code) {
  7440. return code < 256 && ispunct(code);
  7441. }
  7442. bool is_chinese_char(uint32_t codepoint) {
  7443. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7444. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7445. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7446. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7447. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7448. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7449. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7450. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7451. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7452. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7453. return true; // NOLINT
  7454. }
  7455. return false;
  7456. }
  7457. const llama_vocab & vocab;
  7458. };
  7459. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7460. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7461. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7462. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7463. struct fragment_buffer_variant {
  7464. fragment_buffer_variant(llama_vocab::id _token)
  7465. :
  7466. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7467. token(_token),
  7468. raw_text(_dummy),
  7469. offset(0),
  7470. length(0) {}
  7471. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7472. :
  7473. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7474. token((llama_vocab::id) - 1),
  7475. raw_text(_raw_text),
  7476. offset(_offset),
  7477. length(_length){
  7478. GGML_ASSERT(_offset >= 0);
  7479. GGML_ASSERT(_length >= 1);
  7480. GGML_ASSERT(offset + length <= raw_text.length());
  7481. }
  7482. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7483. const llama_vocab::id token;
  7484. const std::string _dummy;
  7485. const std::string & raw_text;
  7486. const uint64_t offset;
  7487. const uint64_t length;
  7488. };
  7489. // #define PRETOKENIZERDEBUG
  7490. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7491. // for each special token
  7492. for (const auto & st: vocab.special_tokens_cache) {
  7493. const auto & special_token = st.first;
  7494. const auto & special_id = st.second;
  7495. // for each text fragment
  7496. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7497. while (it != buffer.end()) {
  7498. auto & fragment = (*it);
  7499. // if a fragment is text ( not yet processed )
  7500. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7501. auto * raw_text = &(fragment.raw_text);
  7502. auto raw_text_base_offset = fragment.offset;
  7503. auto raw_text_base_length = fragment.length;
  7504. // loop over the text
  7505. while (true) {
  7506. // find the first occurrence of a given special token in this fragment
  7507. // passing offset argument only limit the "search area" but match coordinates
  7508. // are still relative to the source full raw_text
  7509. auto match = raw_text->find(special_token, raw_text_base_offset);
  7510. // no occurrences found, stop processing this fragment for a given special token
  7511. if (match == std::string::npos) break;
  7512. // check if match is within bounds of offset <-> length
  7513. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7514. #ifdef PRETOKENIZERDEBUG
  7515. 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());
  7516. #endif
  7517. auto source = std::distance(buffer.begin(), it);
  7518. // if match is further than base offset
  7519. // then we have some text to the left of it
  7520. if (match > raw_text_base_offset) {
  7521. // left
  7522. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7523. const int64_t left_reminder_length = match - raw_text_base_offset;
  7524. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7525. #ifdef PRETOKENIZERDEBUG
  7526. 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());
  7527. #endif
  7528. it++;
  7529. }
  7530. // special token
  7531. buffer.emplace_after(it, special_id);
  7532. it++;
  7533. // right
  7534. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7535. const int64_t right_reminder_offset = match + special_token.length();
  7536. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7537. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7538. #ifdef PRETOKENIZERDEBUG
  7539. 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());
  7540. #endif
  7541. it++;
  7542. if (source == 0) {
  7543. buffer.erase_after(buffer.before_begin());
  7544. } else {
  7545. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7546. }
  7547. // repeat for the right side
  7548. raw_text_base_offset = right_reminder_offset;
  7549. raw_text_base_length = right_reminder_length;
  7550. #ifdef PRETOKENIZERDEBUG
  7551. 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());
  7552. #endif
  7553. } else {
  7554. if (source == 0) {
  7555. buffer.erase_after(buffer.before_begin());
  7556. } else {
  7557. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7558. }
  7559. break;
  7560. }
  7561. }
  7562. }
  7563. it++;
  7564. }
  7565. }
  7566. }
  7567. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7568. std::vector<llama_vocab::id> output;
  7569. // OG tokenizer behavior:
  7570. //
  7571. // tokenizer.encode('', add_bos=True) returns [1]
  7572. // tokenizer.encode('', add_bos=False) returns []
  7573. if (bos && vocab.special_bos_id != -1) {
  7574. output.push_back(vocab.special_bos_id);
  7575. }
  7576. if (raw_text.empty()) {
  7577. return output;
  7578. }
  7579. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7580. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7581. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7582. switch (vocab.type) {
  7583. case LLAMA_VOCAB_TYPE_SPM:
  7584. {
  7585. for (const auto & fragment : fragment_buffer) {
  7586. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7587. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7588. // TODO: It's likely possible to get rid of this string copy entirely
  7589. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7590. // and passing 'add space prefix' as bool argument
  7591. //
  7592. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7593. if (&fragment == &fragment_buffer.front()) {
  7594. if (vocab.add_space_prefix) {
  7595. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7596. }
  7597. }
  7598. #ifdef PRETOKENIZERDEBUG
  7599. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7600. #endif
  7601. llm_tokenizer_spm tokenizer(vocab);
  7602. llama_escape_whitespace(raw_text);
  7603. tokenizer.tokenize(raw_text, output);
  7604. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7605. output.push_back(fragment.token);
  7606. }
  7607. }
  7608. } break;
  7609. case LLAMA_VOCAB_TYPE_BPE:
  7610. {
  7611. for (const auto & fragment : fragment_buffer) {
  7612. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7613. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7614. #ifdef PRETOKENIZERDEBUG
  7615. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7616. #endif
  7617. llm_tokenizer_bpe tokenizer(vocab);
  7618. tokenizer.tokenize(raw_text, output);
  7619. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7620. output.push_back(fragment.token);
  7621. }
  7622. }
  7623. } break;
  7624. case LLAMA_VOCAB_TYPE_WPM:
  7625. {
  7626. for (const auto & fragment : fragment_buffer) {
  7627. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7628. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7629. #ifdef PRETOKENIZERDEBUG
  7630. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7631. #endif
  7632. llm_tokenizer_wpm tokenizer(vocab);
  7633. tokenizer.tokenize(raw_text, output);
  7634. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7635. output.push_back(fragment.token);
  7636. }
  7637. }
  7638. } break;
  7639. }
  7640. return output;
  7641. }
  7642. //
  7643. // grammar - internal
  7644. //
  7645. struct llama_partial_utf8 {
  7646. uint32_t value; // bit value so far (unshifted)
  7647. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7648. };
  7649. struct llama_grammar {
  7650. const std::vector<std::vector<llama_grammar_element>> rules;
  7651. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7652. // buffer for partially generated UTF-8 sequence from accepted tokens
  7653. llama_partial_utf8 partial_utf8;
  7654. };
  7655. struct llama_grammar_candidate {
  7656. size_t index;
  7657. const uint32_t * code_points;
  7658. llama_partial_utf8 partial_utf8;
  7659. };
  7660. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7661. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7662. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7663. const std::string & src,
  7664. llama_partial_utf8 partial_start) {
  7665. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7666. const char * pos = src.c_str();
  7667. std::vector<uint32_t> code_points;
  7668. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7669. code_points.reserve(src.size() + 1);
  7670. uint32_t value = partial_start.value;
  7671. int n_remain = partial_start.n_remain;
  7672. // continue previous decode, if applicable
  7673. while (*pos != 0 && n_remain > 0) {
  7674. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7675. if ((next_byte >> 6) != 2) {
  7676. // invalid sequence, abort
  7677. code_points.push_back(0);
  7678. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7679. }
  7680. value = (value << 6) + (next_byte & 0x3F);
  7681. ++pos;
  7682. --n_remain;
  7683. }
  7684. if (partial_start.n_remain > 0 && n_remain == 0) {
  7685. code_points.push_back(value);
  7686. }
  7687. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7688. while (*pos != 0) {
  7689. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7690. uint8_t highbits = first_byte >> 4;
  7691. n_remain = lookup[highbits] - 1;
  7692. if (n_remain < 0) {
  7693. // invalid sequence, abort
  7694. code_points.clear();
  7695. code_points.push_back(0);
  7696. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7697. }
  7698. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7699. value = first_byte & mask;
  7700. ++pos;
  7701. while (*pos != 0 && n_remain > 0) {
  7702. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7703. ++pos;
  7704. --n_remain;
  7705. }
  7706. if (n_remain == 0) {
  7707. code_points.push_back(value);
  7708. }
  7709. }
  7710. code_points.push_back(0);
  7711. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7712. }
  7713. // returns true iff pos points to the end of one of the definitions of a rule
  7714. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7715. switch (pos->type) {
  7716. case LLAMA_GRETYPE_END: return true; // NOLINT
  7717. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  7718. default: return false;
  7719. }
  7720. }
  7721. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  7722. // asserts that pos is pointing to a char range element
  7723. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  7724. const llama_grammar_element * pos,
  7725. const uint32_t chr) {
  7726. bool found = false;
  7727. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7728. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  7729. do {
  7730. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7731. // inclusive range, e.g. [a-z]
  7732. found = found || (pos->value <= chr && chr <= pos[1].value);
  7733. pos += 2;
  7734. } else {
  7735. // exact char match, e.g. [a] or "a"
  7736. found = found || pos->value == chr;
  7737. pos += 1;
  7738. }
  7739. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7740. return std::make_pair(found == is_positive_char, pos);
  7741. }
  7742. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  7743. // range at pos (regular or inverse range)
  7744. // asserts that pos is pointing to a char range element
  7745. static bool llama_grammar_match_partial_char(
  7746. const llama_grammar_element * pos,
  7747. const llama_partial_utf8 partial_utf8) {
  7748. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7749. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  7750. uint32_t partial_value = partial_utf8.value;
  7751. int n_remain = partial_utf8.n_remain;
  7752. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  7753. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  7754. return false;
  7755. }
  7756. // range of possible code points this partial UTF-8 sequence could complete to
  7757. uint32_t low = partial_value << (n_remain * 6);
  7758. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  7759. if (low == 0) {
  7760. if (n_remain == 2) {
  7761. low = 1 << 11;
  7762. } else if (n_remain == 3) {
  7763. low = 1 << 16;
  7764. }
  7765. }
  7766. do {
  7767. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7768. // inclusive range, e.g. [a-z]
  7769. if (pos->value <= high && low <= pos[1].value) {
  7770. return is_positive_char;
  7771. }
  7772. pos += 2;
  7773. } else {
  7774. // exact char match, e.g. [a] or "a"
  7775. if (low <= pos->value && pos->value <= high) {
  7776. return is_positive_char;
  7777. }
  7778. pos += 1;
  7779. }
  7780. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7781. return !is_positive_char;
  7782. }
  7783. // transforms a grammar pushdown stack into N possible stacks, all ending
  7784. // at a character range (terminal element)
  7785. static void llama_grammar_advance_stack(
  7786. const std::vector<std::vector<llama_grammar_element>> & rules,
  7787. const std::vector<const llama_grammar_element *> & stack,
  7788. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  7789. if (stack.empty()) {
  7790. new_stacks.emplace_back(stack);
  7791. return;
  7792. }
  7793. const llama_grammar_element * pos = stack.back();
  7794. switch (pos->type) {
  7795. case LLAMA_GRETYPE_RULE_REF: {
  7796. const size_t rule_id = static_cast<size_t>(pos->value);
  7797. const llama_grammar_element * subpos = rules[rule_id].data();
  7798. do {
  7799. // init new stack without the top (pos)
  7800. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7801. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  7802. // if this rule ref is followed by another element, add that to stack
  7803. new_stack.push_back(pos + 1);
  7804. }
  7805. if (!llama_grammar_is_end_of_sequence(subpos)) {
  7806. // if alternate is nonempty, add to stack
  7807. new_stack.push_back(subpos);
  7808. }
  7809. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7810. while (!llama_grammar_is_end_of_sequence(subpos)) {
  7811. // scan to end of alternate def
  7812. subpos++;
  7813. }
  7814. if (subpos->type == LLAMA_GRETYPE_ALT) {
  7815. // there's another alternate def of this rule to process
  7816. subpos++;
  7817. } else {
  7818. break;
  7819. }
  7820. } while (true);
  7821. break;
  7822. }
  7823. case LLAMA_GRETYPE_CHAR:
  7824. case LLAMA_GRETYPE_CHAR_NOT:
  7825. new_stacks.emplace_back(stack);
  7826. break;
  7827. default:
  7828. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  7829. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  7830. // those
  7831. GGML_ASSERT(false);
  7832. }
  7833. }
  7834. // takes a set of possible pushdown stacks on a grammar, which are required to
  7835. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  7836. // produces the N possible stacks if the given char is accepted at those
  7837. // positions
  7838. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  7839. const std::vector<std::vector<llama_grammar_element>> & rules,
  7840. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7841. const uint32_t chr) {
  7842. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  7843. for (const auto & stack : stacks) {
  7844. if (stack.empty()) {
  7845. continue;
  7846. }
  7847. auto match = llama_grammar_match_char(stack.back(), chr);
  7848. if (match.first) {
  7849. const llama_grammar_element * pos = match.second;
  7850. // update top of stack to next element, if any
  7851. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7852. if (!llama_grammar_is_end_of_sequence(pos)) {
  7853. new_stack.push_back(pos);
  7854. }
  7855. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7856. }
  7857. }
  7858. return new_stacks;
  7859. }
  7860. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7861. const std::vector<std::vector<llama_grammar_element>> & rules,
  7862. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7863. const std::vector<llama_grammar_candidate> & candidates);
  7864. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  7865. const std::vector<std::vector<llama_grammar_element>> & rules,
  7866. const std::vector<const llama_grammar_element *> & stack,
  7867. const std::vector<llama_grammar_candidate> & candidates) {
  7868. std::vector<llama_grammar_candidate> rejects;
  7869. if (stack.empty()) {
  7870. for (const auto & tok : candidates) {
  7871. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  7872. rejects.push_back(tok);
  7873. }
  7874. }
  7875. return rejects;
  7876. }
  7877. const llama_grammar_element * stack_pos = stack.back();
  7878. std::vector<llama_grammar_candidate> next_candidates;
  7879. for (const auto & tok : candidates) {
  7880. if (*tok.code_points == 0) {
  7881. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  7882. // that cannot satisfy this position in grammar
  7883. if (tok.partial_utf8.n_remain != 0 &&
  7884. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  7885. rejects.push_back(tok);
  7886. }
  7887. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  7888. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  7889. } else {
  7890. rejects.push_back(tok);
  7891. }
  7892. }
  7893. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  7894. // update top of stack to next element, if any
  7895. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  7896. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  7897. stack_after.push_back(stack_pos_after);
  7898. }
  7899. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  7900. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  7901. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  7902. for (const auto & tok : next_rejects) {
  7903. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  7904. }
  7905. return rejects;
  7906. }
  7907. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7908. const std::vector<std::vector<llama_grammar_element>> & rules,
  7909. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7910. const std::vector<llama_grammar_candidate> & candidates) {
  7911. GGML_ASSERT(!stacks.empty()); // REVIEW
  7912. if (candidates.empty()) {
  7913. return std::vector<llama_grammar_candidate>();
  7914. }
  7915. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  7916. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  7917. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  7918. }
  7919. return rejects;
  7920. }
  7921. //
  7922. // grammar - external
  7923. //
  7924. struct llama_grammar * llama_grammar_init(
  7925. const llama_grammar_element ** rules,
  7926. size_t n_rules,
  7927. size_t start_rule_index) {
  7928. const llama_grammar_element * pos;
  7929. // copy rule definitions into vectors
  7930. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  7931. for (size_t i = 0; i < n_rules; i++) {
  7932. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  7933. vec_rules[i].push_back(*pos);
  7934. }
  7935. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  7936. }
  7937. // loop over alternates of start rule to build initial stacks
  7938. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7939. pos = rules[start_rule_index];
  7940. do {
  7941. std::vector<const llama_grammar_element *> stack;
  7942. if (!llama_grammar_is_end_of_sequence(pos)) {
  7943. // if alternate is nonempty, add to stack
  7944. stack.push_back(pos);
  7945. }
  7946. llama_grammar_advance_stack(vec_rules, stack, stacks);
  7947. while (!llama_grammar_is_end_of_sequence(pos)) {
  7948. // scan to end of alternate def
  7949. pos++;
  7950. }
  7951. if (pos->type == LLAMA_GRETYPE_ALT) {
  7952. // there's another alternate def of this rule to process
  7953. pos++;
  7954. } else {
  7955. break;
  7956. }
  7957. } while (true);
  7958. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  7959. }
  7960. void llama_grammar_free(struct llama_grammar * grammar) {
  7961. delete grammar;
  7962. }
  7963. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  7964. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  7965. // redirect elements in stacks to point to new rules
  7966. for (size_t is = 0; is < result->stacks.size(); is++) {
  7967. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  7968. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  7969. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  7970. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  7971. result->stacks[is][ie] = &result->rules[ir0][ir1];
  7972. }
  7973. }
  7974. }
  7975. }
  7976. }
  7977. return result;
  7978. }
  7979. //
  7980. // sampling
  7981. //
  7982. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  7983. if (seed == LLAMA_DEFAULT_SEED) {
  7984. seed = time(NULL);
  7985. }
  7986. ctx->rng.seed(seed);
  7987. }
  7988. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  7989. GGML_ASSERT(candidates->size > 0);
  7990. const int64_t t_start_sample_us = ggml_time_us();
  7991. // Sort the logits in descending order
  7992. if (!candidates->sorted) {
  7993. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7994. return a.logit > b.logit;
  7995. });
  7996. candidates->sorted = true;
  7997. }
  7998. float max_l = candidates->data[0].logit;
  7999. float cum_sum = 0.0f;
  8000. for (size_t i = 0; i < candidates->size; ++i) {
  8001. float p = expf(candidates->data[i].logit - max_l);
  8002. candidates->data[i].p = p;
  8003. cum_sum += p;
  8004. }
  8005. for (size_t i = 0; i < candidates->size; ++i) {
  8006. candidates->data[i].p /= cum_sum;
  8007. }
  8008. if (ctx) {
  8009. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8010. }
  8011. }
  8012. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  8013. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  8014. // if (k >= (int32_t)candidates->size) {
  8015. // return;
  8016. // }
  8017. const int64_t t_start_sample_us = ggml_time_us();
  8018. if (k <= 0) {
  8019. k = candidates->size;
  8020. }
  8021. k = std::max(k, (int) min_keep);
  8022. k = std::min(k, (int) candidates->size);
  8023. // Sort scores in descending order
  8024. if (!candidates->sorted) {
  8025. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  8026. return a.logit > b.logit;
  8027. };
  8028. if (k <= 128) {
  8029. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  8030. } else {
  8031. constexpr int nbuckets = 128;
  8032. constexpr float bucket_low = -10.0f;
  8033. constexpr float bucket_high = 10.0f;
  8034. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  8035. constexpr float bucker_inter = -bucket_low * bucket_scale;
  8036. std::vector<int> bucket_idx(candidates->size);
  8037. std::vector<int> histo(nbuckets, 0);
  8038. for (int i = 0; i < (int)candidates->size; ++i) {
  8039. const float val = candidates->data[i].logit;
  8040. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  8041. ib = std::max(0, std::min(nbuckets-1, ib));
  8042. bucket_idx[i] = ib;
  8043. ++histo[ib];
  8044. }
  8045. int nhave = 0;
  8046. int ib = nbuckets - 1;
  8047. for ( ; ib >= 0; --ib) {
  8048. nhave += histo[ib];
  8049. if (nhave >= k) break;
  8050. }
  8051. std::vector<llama_token_data> tmp_tokens(nhave);
  8052. auto ptr = tmp_tokens.data();
  8053. std::vector<llama_token_data*> bucket_ptrs;
  8054. bucket_ptrs.reserve(nbuckets - ib);
  8055. for (int j = nbuckets - 1; j >= ib; --j) {
  8056. bucket_ptrs.push_back(ptr);
  8057. ptr += histo[j];
  8058. }
  8059. for (int i = 0; i < (int)candidates->size; ++i) {
  8060. int j = bucket_idx[i];
  8061. if (j >= ib) {
  8062. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  8063. }
  8064. }
  8065. ptr = tmp_tokens.data();
  8066. int ndone = 0;
  8067. for (int j = nbuckets-1; j > ib; --j) {
  8068. std::sort(ptr, ptr + histo[j], comp);
  8069. ptr += histo[j];
  8070. ndone += histo[j];
  8071. }
  8072. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  8073. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  8074. }
  8075. candidates->sorted = true;
  8076. }
  8077. candidates->size = k;
  8078. if (ctx) {
  8079. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8080. }
  8081. }
  8082. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8083. if (p >= 1.0f) {
  8084. return;
  8085. }
  8086. llama_sample_softmax(ctx, candidates);
  8087. const int64_t t_start_sample_us = ggml_time_us();
  8088. // Compute the cumulative probabilities
  8089. float cum_sum = 0.0f;
  8090. size_t last_idx = candidates->size;
  8091. for (size_t i = 0; i < candidates->size; ++i) {
  8092. cum_sum += candidates->data[i].p;
  8093. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  8094. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  8095. if (cum_sum >= p && i + 1 >= min_keep) {
  8096. last_idx = i + 1;
  8097. break;
  8098. }
  8099. }
  8100. // Resize the output vector to keep only the top-p tokens
  8101. candidates->size = last_idx;
  8102. if (ctx) {
  8103. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8104. }
  8105. }
  8106. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8107. if (p <= 0.0f || !candidates->size) {
  8108. return;
  8109. }
  8110. const int64_t t_start_sample_us = ggml_time_us();
  8111. bool min_p_applied = false;
  8112. // if the candidates aren't sorted, try the unsorted implementation first
  8113. if (!candidates->sorted) {
  8114. std::vector<llama_token_data> filtered_tokens;
  8115. float max_logit = -FLT_MAX;
  8116. for (size_t i = 0; i < candidates->size; ++i) {
  8117. max_logit = std::max(max_logit, candidates->data[i].logit);
  8118. }
  8119. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  8120. for (size_t i = 0; i < candidates->size; ++i) {
  8121. if (candidates->data[i].logit >= min_logit) {
  8122. filtered_tokens.push_back(candidates->data[i]);
  8123. }
  8124. }
  8125. // if we have enough values the operation was a success
  8126. if (filtered_tokens.size() >= min_keep) {
  8127. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  8128. candidates->size = filtered_tokens.size();
  8129. min_p_applied = true;
  8130. }
  8131. }
  8132. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  8133. if (!min_p_applied) {
  8134. // Sort the logits in descending order
  8135. if (!candidates->sorted) {
  8136. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8137. return a.logit > b.logit;
  8138. });
  8139. candidates->sorted = true;
  8140. }
  8141. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  8142. size_t i = 1; // first token always matches
  8143. for (; i < candidates->size; ++i) {
  8144. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  8145. break; // prob too small
  8146. }
  8147. }
  8148. // Resize the output vector to keep only the matching tokens
  8149. candidates->size = i;
  8150. }
  8151. if (ctx) {
  8152. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8153. }
  8154. }
  8155. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8156. if (z >= 1.0f || candidates->size <= 2) {
  8157. return;
  8158. }
  8159. llama_sample_softmax(nullptr, candidates);
  8160. const int64_t t_start_sample_us = ggml_time_us();
  8161. // Compute the first and second derivatives
  8162. std::vector<float> first_derivatives(candidates->size - 1);
  8163. std::vector<float> second_derivatives(candidates->size - 2);
  8164. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8165. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8166. }
  8167. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8168. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8169. }
  8170. // Calculate absolute value of second derivatives
  8171. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8172. second_derivatives[i] = std::abs(second_derivatives[i]);
  8173. }
  8174. // Normalize the second derivatives
  8175. {
  8176. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8177. if (second_derivatives_sum > 1e-6f) {
  8178. for (float & value : second_derivatives) {
  8179. value /= second_derivatives_sum;
  8180. }
  8181. } else {
  8182. for (float & value : second_derivatives) {
  8183. value = 1.0f / second_derivatives.size();
  8184. }
  8185. }
  8186. }
  8187. float cum_sum = 0.0f;
  8188. size_t last_idx = candidates->size;
  8189. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8190. cum_sum += second_derivatives[i];
  8191. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8192. if (cum_sum > z && i >= min_keep) {
  8193. last_idx = i;
  8194. break;
  8195. }
  8196. }
  8197. // Resize the output vector to keep only the tokens above the tail location
  8198. candidates->size = last_idx;
  8199. if (ctx) {
  8200. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8201. }
  8202. }
  8203. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8204. // Reference implementation:
  8205. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8206. if (p >= 1.0f) {
  8207. return;
  8208. }
  8209. // Compute the softmax of logits and calculate entropy
  8210. llama_sample_softmax(nullptr, candidates);
  8211. const int64_t t_start_sample_us = ggml_time_us();
  8212. float entropy = 0.0f;
  8213. for (size_t i = 0; i < candidates->size; ++i) {
  8214. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8215. }
  8216. // Compute the absolute difference between negative log probability and entropy for each candidate
  8217. std::vector<float> shifted_scores;
  8218. for (size_t i = 0; i < candidates->size; ++i) {
  8219. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8220. shifted_scores.push_back(shifted_score);
  8221. }
  8222. // Sort tokens based on the shifted_scores and their corresponding indices
  8223. std::vector<size_t> indices(candidates->size);
  8224. std::iota(indices.begin(), indices.end(), 0);
  8225. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8226. return shifted_scores[a] < shifted_scores[b];
  8227. });
  8228. // Compute the cumulative probabilities
  8229. float cum_sum = 0.0f;
  8230. size_t last_idx = indices.size();
  8231. for (size_t i = 0; i < indices.size(); ++i) {
  8232. size_t idx = indices[i];
  8233. cum_sum += candidates->data[idx].p;
  8234. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8235. if (cum_sum > p && i >= min_keep - 1) {
  8236. last_idx = i + 1;
  8237. break;
  8238. }
  8239. }
  8240. // Resize the output vector to keep only the locally typical tokens
  8241. std::vector<llama_token_data> new_candidates;
  8242. for (size_t i = 0; i < last_idx; ++i) {
  8243. size_t idx = indices[i];
  8244. new_candidates.push_back(candidates->data[idx]);
  8245. }
  8246. // Replace the data in candidates with the new_candidates data
  8247. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8248. candidates->size = new_candidates.size();
  8249. candidates->sorted = false;
  8250. if (ctx) {
  8251. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8252. }
  8253. }
  8254. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8255. const int64_t t_start_sample_us = ggml_time_us();
  8256. // no need to do anything if there is only one (or zero) candidates
  8257. if(candidates_p->size <= 1) {
  8258. return;
  8259. }
  8260. // Calculate maximum possible entropy
  8261. float max_entropy = -logf(1.0f / candidates_p->size);
  8262. llama_sample_softmax(nullptr, candidates_p);
  8263. // Calculate entropy of the softmax probabilities
  8264. float entropy = 0.0f;
  8265. for (size_t i = 0; i < candidates_p->size; ++i) {
  8266. float prob = candidates_p->data[i].p;
  8267. if (prob > 0.0f) { // Ensure no log(0)
  8268. entropy -= prob * logf(prob);
  8269. }
  8270. }
  8271. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8272. float normalized_entropy = entropy / max_entropy;
  8273. // Map the normalized entropy to the desired temperature range using the power function
  8274. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8275. #ifdef DEBUG
  8276. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8277. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8278. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8279. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8280. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8281. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8282. #endif
  8283. // Apply the dynamically calculated temperature scaling
  8284. for (size_t i = 0; i < candidates_p->size; ++i) {
  8285. candidates_p->data[i].logit /= dyn_temp;
  8286. }
  8287. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8288. double max_l_double = candidates_p->data[0].logit;
  8289. double cum_sum_double = 0.0;
  8290. for (size_t i = 0; i < candidates_p->size; ++i) {
  8291. double p = exp(candidates_p->data[i].logit - max_l_double);
  8292. candidates_p->data[i].p = p; // Store the scaled probability
  8293. cum_sum_double += p;
  8294. }
  8295. for (size_t i = 0; i < candidates_p->size; ++i) {
  8296. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8297. }
  8298. #ifdef DEBUG
  8299. // Print the updated top 25 probabilities after temperature scaling
  8300. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8301. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8302. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8303. }
  8304. #endif
  8305. if (ctx) {
  8306. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8307. }
  8308. }
  8309. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8310. const int64_t t_start_sample_us = ggml_time_us();
  8311. for (size_t i = 0; i < candidates_p->size; ++i) {
  8312. candidates_p->data[i].logit /= temp;
  8313. }
  8314. if (ctx) {
  8315. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8316. }
  8317. }
  8318. void llama_sample_repetition_penalties(
  8319. struct llama_context * ctx,
  8320. llama_token_data_array * candidates,
  8321. const llama_token * last_tokens,
  8322. size_t penalty_last_n,
  8323. float penalty_repeat,
  8324. float penalty_freq,
  8325. float penalty_present) {
  8326. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8327. return;
  8328. }
  8329. const int64_t t_start_sample_us = ggml_time_us();
  8330. // Create a frequency map to count occurrences of each token in last_tokens
  8331. std::unordered_map<llama_token, int> token_count;
  8332. for (size_t i = 0; i < penalty_last_n; ++i) {
  8333. token_count[last_tokens[i]]++;
  8334. }
  8335. // Apply frequency and presence penalties to the candidates
  8336. for (size_t i = 0; i < candidates->size; ++i) {
  8337. const auto token_iter = token_count.find(candidates->data[i].id);
  8338. if (token_iter == token_count.end()) {
  8339. continue;
  8340. }
  8341. const int count = token_iter->second;
  8342. // 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.
  8343. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8344. if (candidates->data[i].logit <= 0) {
  8345. candidates->data[i].logit *= penalty_repeat;
  8346. } else {
  8347. candidates->data[i].logit /= penalty_repeat;
  8348. }
  8349. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8350. }
  8351. candidates->sorted = false;
  8352. if (ctx) {
  8353. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8354. }
  8355. }
  8356. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8357. GGML_ASSERT(ctx);
  8358. const int64_t t_start_sample_us = ggml_time_us();
  8359. bool allow_eos = false;
  8360. for (const auto & stack : grammar->stacks) {
  8361. if (stack.empty()) {
  8362. allow_eos = true;
  8363. break;
  8364. }
  8365. }
  8366. const llama_token eos = llama_token_eos(&ctx->model);
  8367. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8368. candidates_decoded.reserve(candidates->size);
  8369. std::vector<llama_grammar_candidate> candidates_grammar;
  8370. candidates_grammar.reserve(candidates->size);
  8371. for (size_t i = 0; i < candidates->size; ++i) {
  8372. const llama_token id = candidates->data[i].id;
  8373. const std::string piece = llama_token_to_piece(ctx, id);
  8374. if (id == eos) {
  8375. if (!allow_eos) {
  8376. candidates->data[i].logit = -INFINITY;
  8377. }
  8378. } else if (piece.empty() || piece[0] == 0) {
  8379. candidates->data[i].logit = -INFINITY;
  8380. } else {
  8381. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8382. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8383. }
  8384. }
  8385. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8386. for (const auto & reject : rejects) {
  8387. candidates->data[reject.index].logit = -INFINITY;
  8388. }
  8389. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8390. }
  8391. static void llama_log_softmax(float * array, size_t size) {
  8392. float max_l = *std::max_element(array, array + size);
  8393. float sum = 0.f;
  8394. for (size_t i = 0; i < size; ++i) {
  8395. float p = expf(array[i] - max_l);
  8396. sum += p;
  8397. array[i] = p;
  8398. }
  8399. for (size_t i = 0; i < size; ++i) {
  8400. array[i] = logf(array[i] / sum);
  8401. }
  8402. }
  8403. void llama_sample_apply_guidance(
  8404. struct llama_context * ctx,
  8405. float * logits,
  8406. float * logits_guidance,
  8407. float scale) {
  8408. GGML_ASSERT(ctx);
  8409. const auto t_start_sample_us = ggml_time_us();
  8410. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8411. llama_log_softmax(logits, n_vocab);
  8412. llama_log_softmax(logits_guidance, n_vocab);
  8413. for (int i = 0; i < n_vocab; ++i) {
  8414. auto & l = logits[i];
  8415. const auto & g = logits_guidance[i];
  8416. l = scale * (l - g) + g;
  8417. }
  8418. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8419. }
  8420. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8421. GGML_ASSERT(ctx);
  8422. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8423. int64_t t_start_sample_us;
  8424. t_start_sample_us = ggml_time_us();
  8425. llama_sample_softmax(nullptr, candidates);
  8426. // Estimate s_hat using the most probable m tokens
  8427. float s_hat = 0.0;
  8428. float sum_ti_bi = 0.0;
  8429. float sum_ti_sq = 0.0;
  8430. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8431. float t_i = logf(float(i + 2) / float(i + 1));
  8432. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8433. sum_ti_bi += t_i * b_i;
  8434. sum_ti_sq += t_i * t_i;
  8435. }
  8436. s_hat = sum_ti_bi / sum_ti_sq;
  8437. // Compute k from the estimated s_hat and target surprise value
  8438. float epsilon_hat = s_hat - 1;
  8439. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8440. // Sample the next word X using top-k sampling
  8441. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8442. if (ctx) {
  8443. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8444. }
  8445. llama_token X = llama_sample_token(ctx, candidates);
  8446. t_start_sample_us = ggml_time_us();
  8447. // Compute error as the difference between observed surprise and target surprise value
  8448. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8449. return candidate.id == X;
  8450. }));
  8451. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8452. float e = observed_surprise - tau;
  8453. // Update mu using the learning rate and error
  8454. *mu = *mu - eta * e;
  8455. if (ctx) {
  8456. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8457. }
  8458. return X;
  8459. }
  8460. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8461. int64_t t_start_sample_us;
  8462. t_start_sample_us = ggml_time_us();
  8463. llama_sample_softmax(ctx, candidates);
  8464. // Truncate the words with surprise values greater than mu
  8465. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8466. return -log2f(candidate.p) > *mu;
  8467. }));
  8468. if (candidates->size == 0) {
  8469. candidates->size = 1;
  8470. }
  8471. if (ctx) {
  8472. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8473. }
  8474. // Normalize the probabilities of the remaining words
  8475. llama_sample_softmax(ctx, candidates);
  8476. // Sample the next word X from the remaining words
  8477. llama_token X = llama_sample_token(ctx, candidates);
  8478. t_start_sample_us = ggml_time_us();
  8479. // Compute error as the difference between observed surprise and target surprise value
  8480. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8481. return candidate.id == X;
  8482. }));
  8483. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8484. float e = observed_surprise - tau;
  8485. // Update mu using the learning rate and error
  8486. *mu = *mu - eta * e;
  8487. if (ctx) {
  8488. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8489. }
  8490. return X;
  8491. }
  8492. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8493. const int64_t t_start_sample_us = ggml_time_us();
  8494. // Find max element
  8495. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8496. return a.logit < b.logit;
  8497. });
  8498. llama_token result = max_iter->id;
  8499. if (ctx) {
  8500. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8501. ctx->n_sample++;
  8502. }
  8503. return result;
  8504. }
  8505. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8506. GGML_ASSERT(ctx);
  8507. const int64_t t_start_sample_us = ggml_time_us();
  8508. llama_sample_softmax(nullptr, candidates);
  8509. std::vector<float> probs;
  8510. probs.reserve(candidates->size);
  8511. for (size_t i = 0; i < candidates->size; ++i) {
  8512. probs.push_back(candidates->data[i].p);
  8513. }
  8514. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8515. auto & rng = ctx->rng;
  8516. int idx = dist(rng);
  8517. llama_token result = candidates->data[idx].id;
  8518. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8519. ctx->n_sample++;
  8520. return result;
  8521. }
  8522. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8523. const int64_t t_start_sample_us = ggml_time_us();
  8524. if (token == llama_token_eos(&ctx->model)) {
  8525. for (const auto & stack : grammar->stacks) {
  8526. if (stack.empty()) {
  8527. return;
  8528. }
  8529. }
  8530. GGML_ASSERT(false);
  8531. }
  8532. const std::string piece = llama_token_to_piece(ctx, token);
  8533. // Note terminating 0 in decoded string
  8534. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8535. const auto & code_points = decoded.first;
  8536. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8537. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8538. }
  8539. grammar->partial_utf8 = decoded.second;
  8540. GGML_ASSERT(!grammar->stacks.empty());
  8541. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8542. }
  8543. //
  8544. // Beam search
  8545. //
  8546. struct llama_beam {
  8547. std::vector<llama_token> tokens;
  8548. float p; // Cumulative beam probability (renormalized relative to all beams)
  8549. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8550. // Sort beams by probability. In case of ties, prefer beams at eob.
  8551. bool operator<(const llama_beam & rhs) const {
  8552. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8553. }
  8554. // Shift off first n tokens and discard them.
  8555. void shift_tokens(const size_t n) {
  8556. if (n) {
  8557. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8558. tokens.resize(tokens.size() - n);
  8559. }
  8560. }
  8561. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8562. };
  8563. // A struct for calculating logit-related info.
  8564. struct llama_logit_info {
  8565. const float * const logits;
  8566. const int n_vocab;
  8567. const float max_l;
  8568. const float normalizer;
  8569. struct sum_exp {
  8570. float max_l;
  8571. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8572. };
  8573. llama_logit_info(llama_context * ctx)
  8574. : logits(llama_get_logits(ctx))
  8575. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8576. , max_l(*std::max_element(logits, logits + n_vocab))
  8577. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8578. { }
  8579. llama_token_data get_token_data(const llama_token token_id) const {
  8580. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8581. return {token_id, logits[token_id], p};
  8582. }
  8583. // Return top k token_data by logit.
  8584. std::vector<llama_token_data> top_k(size_t k) {
  8585. std::vector<llama_token_data> min_heap; // min-heap by logit
  8586. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8587. min_heap.reserve(k_min);
  8588. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8589. min_heap.push_back(get_token_data(token_id));
  8590. }
  8591. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8592. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8593. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8594. if (min_heap.front().logit < logits[token_id]) {
  8595. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8596. min_heap.back().id = token_id;
  8597. min_heap.back().logit = logits[token_id];
  8598. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8599. }
  8600. }
  8601. return min_heap;
  8602. }
  8603. float probability_from_logit(float logit) const {
  8604. return normalizer * std::exp(logit - max_l);
  8605. }
  8606. };
  8607. struct llama_beam_search_data {
  8608. llama_context * ctx;
  8609. size_t n_beams;
  8610. int n_past;
  8611. int n_predict;
  8612. std::vector<llama_beam> beams;
  8613. std::vector<llama_beam> next_beams;
  8614. // Re-calculated on each loop iteration
  8615. size_t common_prefix_length;
  8616. // Used to communicate to/from callback on beams state.
  8617. std::vector<llama_beam_view> beam_views;
  8618. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8619. : ctx(ctx)
  8620. , n_beams(n_beams)
  8621. , n_past(n_past)
  8622. , n_predict(n_predict)
  8623. , beam_views(n_beams) {
  8624. beams.reserve(n_beams);
  8625. next_beams.reserve(n_beams);
  8626. }
  8627. // Collapse beams to a single beam given by index.
  8628. void collapse_beams(const size_t beam_idx) {
  8629. if (0u < beam_idx) {
  8630. std::swap(beams[0], beams[beam_idx]);
  8631. }
  8632. beams.resize(1);
  8633. }
  8634. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8635. // The repetitive patterns below reflect the 2 stages of heaps:
  8636. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8637. // * If the heap is full and a new element is found that should be included, pop the
  8638. // least element to the back(), replace it with the new, then push it into the heap.
  8639. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8640. // Min-heaps use a greater-than comparator.
  8641. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8642. if (beam.eob) {
  8643. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8644. if (next_beams.size() < n_beams) {
  8645. next_beams.push_back(std::move(beam));
  8646. if (next_beams.size() == n_beams) {
  8647. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8648. }
  8649. } else if (next_beams.front().p < beam.p) {
  8650. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8651. next_beams.back() = std::move(beam);
  8652. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8653. }
  8654. } else {
  8655. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8656. if (!beam.tokens.empty()) {
  8657. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8658. }
  8659. llama_logit_info logit_info(ctx);
  8660. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8661. size_t i=0;
  8662. if (next_beams.size() < n_beams) {
  8663. for (; next_beams.size() < n_beams ; ++i) {
  8664. llama_beam next_beam = beam;
  8665. next_beam.tokens.push_back(next_tokens[i].id);
  8666. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8667. next_beams.push_back(std::move(next_beam));
  8668. }
  8669. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8670. } else {
  8671. for (; next_beams.front().p == 0.0f ; ++i) {
  8672. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8673. next_beams.back() = beam;
  8674. next_beams.back().tokens.push_back(next_tokens[i].id);
  8675. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8676. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8677. }
  8678. }
  8679. for (; i < n_beams ; ++i) {
  8680. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8681. if (next_beams.front().p < next_p) {
  8682. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8683. next_beams.back() = beam;
  8684. next_beams.back().tokens.push_back(next_tokens[i].id);
  8685. next_beams.back().p = next_p;
  8686. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8687. }
  8688. }
  8689. }
  8690. }
  8691. // Find common_prefix_length based on beams.
  8692. // Requires beams is not empty.
  8693. size_t find_common_prefix_length() {
  8694. size_t common_prefix_length = beams[0].tokens.size();
  8695. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8696. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8697. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8698. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8699. common_prefix_length = j;
  8700. break;
  8701. }
  8702. }
  8703. }
  8704. return common_prefix_length;
  8705. }
  8706. // Construct beams_state to send back to caller via the callback function.
  8707. // Side effect: set common_prefix_length = find_common_prefix_length();
  8708. llama_beams_state get_beams_state(const bool last_call) {
  8709. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8710. beam_views[i] = beams[i].view();
  8711. }
  8712. common_prefix_length = find_common_prefix_length();
  8713. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8714. }
  8715. // Loop:
  8716. // * while i < n_predict, AND
  8717. // * any of the beams have not yet reached end-of-beam (eob), AND
  8718. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  8719. // (since all other beam probabilities can only decrease)
  8720. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  8721. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  8722. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  8723. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  8724. !beams[top_beam_index()].eob ; ++i) {
  8725. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  8726. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  8727. if (common_prefix_length) {
  8728. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  8729. n_past += common_prefix_length;
  8730. }
  8731. // Zero-out next_beam probabilities to place them last in following min-heap.
  8732. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  8733. for (llama_beam & beam : beams) {
  8734. beam.shift_tokens(common_prefix_length);
  8735. fill_next_beams_by_top_probabilities(beam);
  8736. }
  8737. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  8738. beams.swap(next_beams);
  8739. renormalize_beam_probabilities(beams);
  8740. }
  8741. collapse_beams(top_beam_index());
  8742. callback(callback_data, get_beams_state(true));
  8743. }
  8744. // As beams grow, the cumulative probabilities decrease.
  8745. // Renormalize them to avoid floating point underflow.
  8746. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  8747. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  8748. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  8749. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  8750. }
  8751. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  8752. size_t top_beam_index() {
  8753. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  8754. }
  8755. // Copy (p,eob) for each beam which may have been changed by the callback.
  8756. void update_beams_from_beam_views() {
  8757. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8758. beams[i].p = beam_views[i].p;
  8759. beams[i].eob = beam_views[i].eob;
  8760. }
  8761. }
  8762. };
  8763. void llama_beam_search(llama_context * ctx,
  8764. llama_beam_search_callback_fn_t callback, void * callback_data,
  8765. size_t n_beams, int n_past, int n_predict) {
  8766. assert(ctx);
  8767. const int64_t t_start_sample_us = ggml_time_us();
  8768. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  8769. beam_search_data.loop(callback, callback_data);
  8770. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8771. ctx->n_sample++;
  8772. }
  8773. //
  8774. // quantization
  8775. //
  8776. struct quantize_state_internal {
  8777. const llama_model & model;
  8778. const llama_model_quantize_params * params;
  8779. int n_attention_wv = 0;
  8780. int n_ffn_down = 0;
  8781. int n_ffn_gate = 0;
  8782. int n_ffn_up = 0;
  8783. int i_attention_wv = 0;
  8784. int i_ffn_down = 0;
  8785. int i_ffn_gate = 0;
  8786. int i_ffn_up = 0;
  8787. int n_k_quantized = 0;
  8788. int n_fallback = 0;
  8789. bool has_imatrix = false;
  8790. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  8791. : model(model)
  8792. , params(params)
  8793. {}
  8794. };
  8795. static void llama_convert_tensor_internal(
  8796. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  8797. const size_t nelements, const int nthread
  8798. ) {
  8799. if (output.size() < nelements) {
  8800. output.resize(nelements);
  8801. }
  8802. float * f32_output = (float *) output.data();
  8803. ggml_type_traits_t qtype;
  8804. if (ggml_is_quantized(tensor->type)) {
  8805. qtype = ggml_internal_get_type_traits(tensor->type);
  8806. if (qtype.to_float == NULL) {
  8807. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  8808. }
  8809. } else if (tensor->type != GGML_TYPE_F16) {
  8810. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  8811. }
  8812. if (nthread < 2) {
  8813. if (tensor->type == GGML_TYPE_F16) {
  8814. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  8815. } else if (ggml_is_quantized(tensor->type)) {
  8816. qtype.to_float(tensor->data, f32_output, nelements);
  8817. } else {
  8818. GGML_ASSERT(false); // unreachable
  8819. }
  8820. return;
  8821. }
  8822. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  8823. size_t block_size_bytes = ggml_type_size(tensor->type);
  8824. GGML_ASSERT(nelements % block_size == 0);
  8825. size_t nblocks = nelements / block_size;
  8826. size_t blocks_per_thread = nblocks / nthread;
  8827. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  8828. size_t in_buff_offs = 0;
  8829. size_t out_buff_offs = 0;
  8830. for (int tnum = 0; tnum < nthread; tnum++) {
  8831. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  8832. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  8833. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  8834. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  8835. if (typ == GGML_TYPE_F16) {
  8836. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  8837. } else {
  8838. qtype.to_float(inbuf, outbuf, nels);
  8839. }
  8840. };
  8841. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  8842. in_buff_offs += thr_block_bytes;
  8843. out_buff_offs += thr_elems;
  8844. }
  8845. for (auto & w : workers) { w.join(); }
  8846. workers.clear();
  8847. }
  8848. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  8849. const std::string name = ggml_get_name(tensor);
  8850. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8851. const llm_arch arch = qs.model.arch;
  8852. const auto tn = LLM_TN(arch);
  8853. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  8854. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  8855. };
  8856. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  8857. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  8858. if (n_expert > 1) {
  8859. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  8860. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  8861. // for getting the current layer as I initially thought, and we need to resort to parsing the
  8862. // tensor name.
  8863. n_layer /= n_expert;
  8864. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  8865. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  8866. }
  8867. if (i_layer < 0 || i_layer >= n_layer) {
  8868. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  8869. }
  8870. }
  8871. return std::make_pair(i_layer, n_layer);
  8872. };
  8873. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  8874. // with the quantization of the output tensor
  8875. if (name == tn(LLM_TENSOR_OUTPUT, "weight") ||
  8876. (LLM_TENSOR_NAMES.at(arch).find(LLM_TENSOR_OUTPUT) == LLM_TENSOR_NAMES.at(arch).end() && name == "token_embd.weight")) {
  8877. int nx = tensor->ne[0];
  8878. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  8879. new_type = GGML_TYPE_Q8_0;
  8880. }
  8881. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  8882. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  8883. new_type = GGML_TYPE_Q5_K;
  8884. }
  8885. else if (new_type != GGML_TYPE_Q8_0) {
  8886. new_type = GGML_TYPE_Q6_K;
  8887. }
  8888. } else if (name == "token_embd.weight") {
  8889. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  8890. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8891. new_type = GGML_TYPE_Q2_K;
  8892. }
  8893. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  8894. new_type = GGML_TYPE_IQ3_S;
  8895. }
  8896. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8897. new_type = GGML_TYPE_IQ3_S;
  8898. }
  8899. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  8900. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  8901. if (name.find("attn_v.weight") != std::string::npos) {
  8902. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  8903. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  8904. ++qs.i_attention_wv;
  8905. }
  8906. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  8907. new_type = GGML_TYPE_Q4_K;
  8908. }
  8909. else if (name.find("ffn_down") != std::string::npos) {
  8910. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  8911. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  8912. }
  8913. ++qs.i_ffn_down;
  8914. }
  8915. else if (name.find("attn_output.weight") != std::string::npos) {
  8916. if (qs.model.hparams.n_expert == 8) {
  8917. new_type = GGML_TYPE_Q5_K;
  8918. } else {
  8919. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  8920. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  8921. }
  8922. }
  8923. } else if (name.find("attn_v.weight") != std::string::npos) {
  8924. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  8925. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8926. }
  8927. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  8928. new_type = GGML_TYPE_Q4_K;
  8929. }
  8930. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8931. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  8932. }
  8933. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  8934. new_type = GGML_TYPE_Q4_K;
  8935. }
  8936. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  8937. new_type = GGML_TYPE_Q4_K;
  8938. }
  8939. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  8940. new_type = GGML_TYPE_Q4_K;
  8941. }
  8942. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  8943. new_type = GGML_TYPE_Q4_K;
  8944. }
  8945. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8946. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8947. }
  8948. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8949. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  8950. new_type = GGML_TYPE_Q5_K;
  8951. }
  8952. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  8953. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  8954. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  8955. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  8956. (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;
  8957. if (qs.model.type == MODEL_70B) {
  8958. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  8959. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  8960. // nearly negligible increase in model size by quantizing this tensor with more bits:
  8961. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  8962. }
  8963. if (qs.model.hparams.n_expert == 8) {
  8964. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8965. // TODO: explore better strategies
  8966. new_type = GGML_TYPE_Q8_0;
  8967. }
  8968. ++qs.i_attention_wv;
  8969. } else if (name.find("attn_k.weight") != std::string::npos) {
  8970. if (qs.model.hparams.n_expert == 8) {
  8971. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8972. // TODO: explore better strategies
  8973. new_type = GGML_TYPE_Q8_0;
  8974. }
  8975. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  8976. new_type = GGML_TYPE_IQ3_XXS;
  8977. }
  8978. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8979. new_type = GGML_TYPE_IQ2_S;
  8980. }
  8981. } else if (name.find("attn_q.weight") != std::string::npos) {
  8982. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  8983. new_type = GGML_TYPE_IQ3_XXS;
  8984. }
  8985. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8986. new_type = GGML_TYPE_IQ2_S;
  8987. }
  8988. } else if (name.find("ffn_down") != std::string::npos) {
  8989. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  8990. int i_layer = info.first, n_layer = info.second;
  8991. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8992. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  8993. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  8994. }
  8995. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  8996. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8997. }
  8998. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8999. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  9000. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  9001. : GGML_TYPE_Q3_K;
  9002. }
  9003. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  9004. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  9005. new_type = GGML_TYPE_Q4_K;
  9006. }
  9007. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  9008. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  9009. }
  9010. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  9011. if (arch == LLM_ARCH_FALCON) {
  9012. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  9013. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9014. } else {
  9015. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9016. }
  9017. }
  9018. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  9019. new_type = GGML_TYPE_Q5_K;
  9020. }
  9021. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9022. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  9023. new_type = GGML_TYPE_Q5_K;
  9024. }
  9025. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  9026. && qs.has_imatrix && i_layer < n_layer/8) {
  9027. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  9028. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  9029. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  9030. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  9031. }
  9032. ++qs.i_ffn_down;
  9033. } else if (name.find("attn_output.weight") != std::string::npos) {
  9034. if (arch != LLM_ARCH_FALCON) {
  9035. if (qs.model.hparams.n_expert == 8) {
  9036. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9037. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  9038. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  9039. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  9040. new_type = GGML_TYPE_Q5_K;
  9041. }
  9042. } else {
  9043. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  9044. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  9045. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  9046. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  9047. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  9048. }
  9049. } else {
  9050. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  9051. }
  9052. }
  9053. else if (name.find("attn_qkv.weight") != std::string::npos) {
  9054. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9055. new_type = GGML_TYPE_Q4_K;
  9056. }
  9057. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  9058. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  9059. }
  9060. else if (name.find("ffn_gate") != std::string::npos) {
  9061. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  9062. int i_layer = info.first, n_layer = info.second;
  9063. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9064. new_type = GGML_TYPE_IQ3_XXS;
  9065. }
  9066. ++qs.i_ffn_gate;
  9067. }
  9068. else if (name.find("ffn_up") != std::string::npos) {
  9069. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  9070. int i_layer = info.first, n_layer = info.second;
  9071. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9072. new_type = GGML_TYPE_IQ3_XXS;
  9073. }
  9074. ++qs.i_ffn_up;
  9075. }
  9076. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9077. //}
  9078. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  9079. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  9080. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9081. //}
  9082. // This can be used to reduce the size of the Q5_K_S model.
  9083. // The associated PPL increase is fully in line with the size reduction
  9084. //else {
  9085. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  9086. //}
  9087. bool convert_incompatible_tensor = false;
  9088. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  9089. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  9090. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  9091. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  9092. int nx = tensor->ne[0];
  9093. int ny = tensor->ne[1];
  9094. if (nx % QK_K != 0) {
  9095. 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));
  9096. convert_incompatible_tensor = true;
  9097. } else {
  9098. ++qs.n_k_quantized;
  9099. }
  9100. }
  9101. if (convert_incompatible_tensor) {
  9102. switch (new_type) {
  9103. case GGML_TYPE_IQ2_XXS:
  9104. case GGML_TYPE_IQ2_XS:
  9105. case GGML_TYPE_IQ2_S:
  9106. case GGML_TYPE_IQ3_XXS:
  9107. case GGML_TYPE_IQ3_S:
  9108. case GGML_TYPE_IQ1_S:
  9109. case GGML_TYPE_Q2_K:
  9110. case GGML_TYPE_Q3_K:
  9111. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  9112. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  9113. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  9114. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  9115. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  9116. }
  9117. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  9118. ++qs.n_fallback;
  9119. }
  9120. return new_type;
  9121. }
  9122. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  9123. ggml_type quantized_type;
  9124. llama_ftype ftype = params->ftype;
  9125. switch (params->ftype) {
  9126. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  9127. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  9128. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  9129. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  9130. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  9131. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  9132. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  9133. // K-quants
  9134. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  9135. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  9136. case LLAMA_FTYPE_MOSTLY_IQ3_XS: quantized_type = GGML_TYPE_IQ3_S; break;
  9137. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  9138. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  9139. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  9140. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  9141. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  9142. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  9143. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  9144. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  9145. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  9146. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  9147. case LLAMA_FTYPE_MOSTLY_IQ2_S: quantized_type = GGML_TYPE_IQ2_XS; break;
  9148. case LLAMA_FTYPE_MOSTLY_IQ2_M: quantized_type = GGML_TYPE_IQ2_S; break;
  9149. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  9150. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  9151. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  9152. case LLAMA_FTYPE_MOSTLY_IQ4_XS: quantized_type = GGML_TYPE_IQ4_XS; break;
  9153. case LLAMA_FTYPE_MOSTLY_IQ3_S: quantized_type = GGML_TYPE_IQ3_S; break;
  9154. case LLAMA_FTYPE_MOSTLY_IQ3_M: quantized_type = GGML_TYPE_IQ3_S; break;
  9155. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  9156. }
  9157. int nthread = params->nthread;
  9158. if (nthread <= 0) {
  9159. nthread = std::thread::hardware_concurrency();
  9160. }
  9161. // mmap consistently increases speed Linux, and also increases speed on Windows with
  9162. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  9163. #if defined(__linux__) || defined(_WIN32)
  9164. constexpr bool use_mmap = true;
  9165. #else
  9166. constexpr bool use_mmap = false;
  9167. #endif
  9168. llama_model_loader ml(fname_inp, use_mmap, NULL);
  9169. ml.init_mapping(false); // no prefetching?
  9170. llama_model model;
  9171. llm_load_arch(ml, model);
  9172. llm_load_hparams(ml, model);
  9173. struct quantize_state_internal qs(model, params);
  9174. if (params->only_copy) {
  9175. ftype = model.ftype;
  9176. }
  9177. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  9178. if (params->imatrix) {
  9179. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  9180. if (imatrix_data) {
  9181. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  9182. qs.has_imatrix = true;
  9183. }
  9184. }
  9185. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  9186. struct gguf_context * ctx_out = gguf_init_empty();
  9187. // copy the KV pairs from the input file
  9188. gguf_set_kv (ctx_out, ml.ctx_gguf);
  9189. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  9190. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  9191. for (int i = 0; i < ml.n_tensors; ++i) {
  9192. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9193. const std::string name = ggml_get_name(meta);
  9194. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9195. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9196. ++qs.n_attention_wv;
  9197. }
  9198. else if (name.find("ffn_down") != std::string::npos) {
  9199. ++qs.n_ffn_down;
  9200. }
  9201. else if (name.find("ffn_gate") != std::string::npos) {
  9202. ++qs.n_ffn_gate;
  9203. }
  9204. else if (name.find("ffn_up") != std::string::npos) {
  9205. ++qs.n_ffn_up;
  9206. }
  9207. }
  9208. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9209. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9210. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9211. }
  9212. size_t total_size_org = 0;
  9213. size_t total_size_new = 0;
  9214. std::vector<int64_t> hist_all(1 << 4, 0);
  9215. std::vector<std::thread> workers;
  9216. workers.reserve(nthread);
  9217. std::mutex mutex;
  9218. int idx = 0;
  9219. std::vector<no_init<uint8_t>> read_data;
  9220. std::vector<no_init<uint8_t>> work;
  9221. std::vector<no_init<float>> f32_conv_buf;
  9222. // populate the original tensors so we get an initial meta data
  9223. for (int i = 0; i < ml.n_tensors; ++i) {
  9224. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9225. gguf_add_tensor(ctx_out, meta);
  9226. }
  9227. std::ofstream fout(fname_out, std::ios::binary);
  9228. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9229. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9230. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9231. // placeholder for the meta data
  9232. ::zeros(fout, meta_size);
  9233. for (int i = 0; i < ml.n_tensors; ++i) {
  9234. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9235. const std::string name = ggml_get_name(tensor);
  9236. if (!ml.use_mmap) {
  9237. if (read_data.size() < ggml_nbytes(tensor)) {
  9238. read_data.resize(ggml_nbytes(tensor));
  9239. }
  9240. tensor->data = read_data.data();
  9241. }
  9242. ml.load_data_for(tensor);
  9243. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9244. ++idx, ml.n_tensors,
  9245. ggml_get_name(tensor),
  9246. llama_format_tensor_shape(tensor).c_str(),
  9247. ggml_type_name(tensor->type));
  9248. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9249. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9250. // quantize only 2D tensors
  9251. quantize &= (ggml_n_dims(tensor) == 2);
  9252. quantize &= params->quantize_output_tensor || name != "output.weight";
  9253. quantize &= !params->only_copy;
  9254. // do not quantize expert gating tensors
  9255. // NOTE: can't use LLM_TN here because the layer number is not known
  9256. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  9257. // do not quantize positional embeddings and token types (BERT)
  9258. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9259. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9260. enum ggml_type new_type;
  9261. void * new_data;
  9262. size_t new_size;
  9263. if (quantize) {
  9264. new_type = quantized_type;
  9265. if (!params->pure) {
  9266. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9267. }
  9268. // If we've decided to quantize to the same type the tensor is already
  9269. // in then there's nothing to do.
  9270. quantize = tensor->type != new_type;
  9271. }
  9272. if (!quantize) {
  9273. new_type = tensor->type;
  9274. new_data = tensor->data;
  9275. new_size = ggml_nbytes(tensor);
  9276. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9277. } else {
  9278. const size_t nelements = ggml_nelements(tensor);
  9279. const float * imatrix = nullptr;
  9280. if (imatrix_data) {
  9281. auto it = imatrix_data->find(tensor->name);
  9282. if (it == imatrix_data->end()) {
  9283. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9284. } else {
  9285. if (it->second.size() == (size_t)tensor->ne[0]) {
  9286. imatrix = it->second.data();
  9287. } else {
  9288. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9289. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9290. }
  9291. }
  9292. }
  9293. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9294. new_type == GGML_TYPE_IQ2_XS ||
  9295. new_type == GGML_TYPE_IQ2_S ||
  9296. new_type == GGML_TYPE_IQ1_S ||
  9297. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9298. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9299. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9300. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9301. LLAMA_LOG_ERROR("============================================================\n\n");
  9302. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9303. }
  9304. float * f32_data;
  9305. if (tensor->type == GGML_TYPE_F32) {
  9306. f32_data = (float *) tensor->data;
  9307. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9308. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9309. } else {
  9310. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9311. f32_data = (float *) f32_conv_buf.data();
  9312. }
  9313. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9314. fflush(stdout);
  9315. if (work.size() < nelements * 4) {
  9316. work.resize(nelements * 4); // upper bound on size
  9317. }
  9318. new_data = work.data();
  9319. std::array<int64_t, 1 << 4> hist_cur = {};
  9320. const int n_per_row = tensor->ne[0];
  9321. const int nrows = nelements / n_per_row;
  9322. static const int min_chunk_size = 32 * 512;
  9323. 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);
  9324. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9325. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9326. if (nthread_use < 2) {
  9327. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  9328. } else {
  9329. int counter = 0;
  9330. new_size = 0;
  9331. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9332. nrows, n_per_row, imatrix]() {
  9333. std::array<int64_t, 1 << 4> local_hist = {};
  9334. const int nrows_per_chunk = chunk_size / n_per_row;
  9335. size_t local_size = 0;
  9336. while (true) {
  9337. std::unique_lock<std::mutex> lock(mutex);
  9338. int first_row = counter; counter += nrows_per_chunk;
  9339. if (first_row >= nrows) {
  9340. if (local_size > 0) {
  9341. for (int j=0; j<int(local_hist.size()); ++j) {
  9342. hist_cur[j] += local_hist[j];
  9343. }
  9344. new_size += local_size;
  9345. }
  9346. break;
  9347. }
  9348. lock.unlock();
  9349. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9350. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9351. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9352. }
  9353. };
  9354. for (int it = 0; it < nthread_use - 1; ++it) {
  9355. workers.emplace_back(compute);
  9356. }
  9357. compute();
  9358. for (auto & w : workers) { w.join(); }
  9359. workers.clear();
  9360. }
  9361. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9362. int64_t tot_count = 0;
  9363. for (size_t i = 0; i < hist_cur.size(); i++) {
  9364. hist_all[i] += hist_cur[i];
  9365. tot_count += hist_cur[i];
  9366. }
  9367. if (tot_count > 0) {
  9368. LLAMA_LOG_INFO(" | hist: ");
  9369. for (size_t i = 0; i < hist_cur.size(); i++) {
  9370. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9371. }
  9372. }
  9373. LLAMA_LOG_INFO("\n");
  9374. }
  9375. total_size_org += ggml_nbytes(tensor);
  9376. total_size_new += new_size;
  9377. // update the gguf meta data as we go
  9378. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9379. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9380. // write tensor data + padding
  9381. fout.write((const char *) new_data, new_size);
  9382. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9383. }
  9384. // go back to beginning of file and write the updated meta data
  9385. {
  9386. fout.seekp(0);
  9387. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9388. gguf_get_meta_data(ctx_out, data.data());
  9389. fout.write((const char *) data.data(), data.size());
  9390. }
  9391. fout.close();
  9392. gguf_free(ctx_out);
  9393. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9394. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9395. // print histogram for all tensors
  9396. {
  9397. int64_t sum_all = 0;
  9398. for (size_t i = 0; i < hist_all.size(); i++) {
  9399. sum_all += hist_all[i];
  9400. }
  9401. if (sum_all > 0) {
  9402. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9403. for (size_t i = 0; i < hist_all.size(); i++) {
  9404. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9405. }
  9406. LLAMA_LOG_INFO("\n");
  9407. }
  9408. }
  9409. if (qs.n_fallback > 0) {
  9410. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9411. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9412. }
  9413. }
  9414. static int llama_apply_lora_from_file_internal(
  9415. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9416. ) {
  9417. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9418. const int64_t t_start_lora_us = ggml_time_us();
  9419. llama_file fin(path_lora, "rb");
  9420. // verify magic and version
  9421. {
  9422. uint32_t magic = fin.read_u32();
  9423. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9424. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9425. return 1;
  9426. }
  9427. uint32_t format_version = fin.read_u32();
  9428. if (format_version != 1) {
  9429. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9430. return 1;
  9431. }
  9432. }
  9433. int32_t lora_r = fin.read_u32();
  9434. int32_t lora_alpha = fin.read_u32();
  9435. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9436. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9437. // load base model
  9438. std::unique_ptr<llama_model_loader> ml;
  9439. if (path_base_model) {
  9440. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9441. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9442. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9443. }
  9444. struct tensor_meta {
  9445. std::string name;
  9446. ggml_type type;
  9447. int32_t ne[2];
  9448. size_t offset;
  9449. };
  9450. std::map<std::string, tensor_meta> tensor_meta_map;
  9451. // load all tensor meta
  9452. while (true) {
  9453. if (fin.tell() == fin.size) {
  9454. // eof
  9455. break;
  9456. }
  9457. int32_t n_dims;
  9458. int32_t name_len;
  9459. int32_t ftype;
  9460. fin.read_raw(&n_dims, sizeof(n_dims));
  9461. fin.read_raw(&name_len, sizeof(name_len));
  9462. fin.read_raw(&ftype, sizeof(ftype));
  9463. if (n_dims != 1 && n_dims != 2) {
  9464. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9465. return 1;
  9466. }
  9467. int32_t ne[2] = { 1, 1 };
  9468. for (int i = 0; i < n_dims; ++i) {
  9469. fin.read_raw(&ne[i], sizeof(ne[i]));
  9470. }
  9471. std::string name;
  9472. {
  9473. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9474. char buf[GGML_MAX_NAME];
  9475. fin.read_raw(buf, name_len);
  9476. name = std::string(buf, name_len);
  9477. }
  9478. // check for lora suffix
  9479. std::string lora_suffix;
  9480. if (name.length() > 6) {
  9481. lora_suffix = name.substr(name.length() - 6);
  9482. }
  9483. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9484. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9485. return 1;
  9486. }
  9487. // tensor type
  9488. ggml_type wtype;
  9489. switch (ftype) {
  9490. case 0: wtype = GGML_TYPE_F32; break;
  9491. case 1: wtype = GGML_TYPE_F16; break;
  9492. default:
  9493. {
  9494. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9495. __func__, ftype);
  9496. return 1;
  9497. }
  9498. }
  9499. // data offset
  9500. size_t offset = fin.tell();
  9501. offset = (offset + 31) & -32;
  9502. // skip tensor data
  9503. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9504. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9505. }
  9506. bool warned = false;
  9507. int n_tensors = 0;
  9508. // apply
  9509. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9510. if (backend_cpu == nullptr) {
  9511. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9512. return 1;
  9513. }
  9514. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9515. std::vector<no_init<uint8_t>> read_buf;
  9516. for (const auto & it : model.tensors_by_name) {
  9517. const std::string & base_name = it.first;
  9518. ggml_tensor * model_t = it.second;
  9519. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9520. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9521. continue;
  9522. }
  9523. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9524. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9525. ggml_init_params lora_init_params = {
  9526. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9527. /* .mem_buffer */ nullptr,
  9528. /* .no_alloc */ true,
  9529. };
  9530. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9531. if (lora_ctx == nullptr) {
  9532. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9533. ggml_backend_free(backend_cpu);
  9534. return 1;
  9535. }
  9536. // create tensors
  9537. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9538. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9539. ggml_set_name(loraA, metaA.name.c_str());
  9540. ggml_set_name(loraB, metaB.name.c_str());
  9541. ggml_tensor * base_t;
  9542. if (ml) {
  9543. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9544. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9545. return 1;
  9546. }
  9547. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9548. } else {
  9549. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9550. }
  9551. ggml_set_name(base_t, base_name.c_str());
  9552. // allocate in backend buffer
  9553. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9554. if (lora_buf == nullptr) {
  9555. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9556. return 1;
  9557. }
  9558. // load tensor data
  9559. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9560. read_buf.resize(ggml_nbytes(tensor));
  9561. fin.seek(tensor_meta.offset, SEEK_SET);
  9562. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9563. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9564. };
  9565. load_tensor(metaA, loraA);
  9566. load_tensor(metaB, loraB);
  9567. // load base model tensor data
  9568. if (ml) {
  9569. ml->load_data_for(base_t);
  9570. } else {
  9571. ggml_backend_tensor_copy(model_t, base_t);
  9572. }
  9573. if (ggml_is_quantized(base_t->type) && !warned) {
  9574. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9575. "use a f16 or f32 base model with --lora-base\n", __func__);
  9576. warned = true;
  9577. }
  9578. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9579. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9580. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9581. ggml_free(lora_ctx);
  9582. ggml_backend_buffer_free(lora_buf);
  9583. ggml_backend_free(backend_cpu);
  9584. return 1;
  9585. }
  9586. auto build_lora_graph = [&]() {
  9587. // w = w + BA*s
  9588. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9589. ggml_set_name(BA, "BA");
  9590. if (scaling != 1.0f) {
  9591. BA = ggml_scale(lora_ctx, BA, scaling);
  9592. ggml_set_name(BA, "BA_scaled");
  9593. }
  9594. ggml_tensor * r;
  9595. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9596. ggml_set_name(r, "r_add");
  9597. if (base_t->type != model_t->type) {
  9598. // convert the result to the model type
  9599. r = ggml_cast(lora_ctx, r, model_t->type);
  9600. ggml_set_name(r, "r_cast");
  9601. }
  9602. return r;
  9603. };
  9604. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9605. ggml_tensor * r = build_lora_graph();
  9606. ggml_build_forward_expand(gf, r);
  9607. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9608. if (graph_buf == nullptr) {
  9609. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9610. ggml_free(lora_ctx);
  9611. ggml_backend_buffer_free(lora_buf);
  9612. ggml_backend_free(backend_cpu);
  9613. return 1;
  9614. }
  9615. ggml_backend_graph_compute(backend_cpu, gf);
  9616. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9617. #if 0
  9618. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9619. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9620. // sched compute
  9621. ggml_build_forward_expand(gf, build_graph());
  9622. ggml_backend_sched_init_measure(sched, gf);
  9623. // create the graph again, since the previous one was destroyed by the measure
  9624. ggml_graph_clear(gf);
  9625. ggml_build_forward_expand(gf, build_graph());
  9626. ggml_backend_sched_graph_compute(sched, gf);
  9627. ggml_backend_sched_free(sched);
  9628. #endif
  9629. ggml_backend_buffer_free(lora_buf);
  9630. ggml_backend_buffer_free(graph_buf);
  9631. ggml_free(lora_ctx);
  9632. n_tensors++;
  9633. if (n_tensors % 4 == 0) {
  9634. LLAMA_LOG_INFO(".");
  9635. }
  9636. }
  9637. ggml_backend_free(backend_cpu);
  9638. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9639. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9640. return 0;
  9641. }
  9642. //
  9643. // interface implementation
  9644. //
  9645. struct llama_model_params llama_model_default_params() {
  9646. struct llama_model_params result = {
  9647. /*.n_gpu_layers =*/ 0,
  9648. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  9649. /*.main_gpu =*/ 0,
  9650. /*.tensor_split =*/ nullptr,
  9651. /*.progress_callback =*/ nullptr,
  9652. /*.progress_callback_user_data =*/ nullptr,
  9653. /*.kv_overrides =*/ nullptr,
  9654. /*.vocab_only =*/ false,
  9655. /*.use_mmap =*/ true,
  9656. /*.use_mlock =*/ false,
  9657. };
  9658. #ifdef GGML_USE_METAL
  9659. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9660. result.n_gpu_layers = 999;
  9661. #endif
  9662. return result;
  9663. }
  9664. struct llama_context_params llama_context_default_params() {
  9665. struct llama_context_params result = {
  9666. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9667. /*.n_ctx =*/ 512,
  9668. /*.n_batch =*/ 512,
  9669. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9670. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9671. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  9672. /*.rope_freq_base =*/ 0.0f,
  9673. /*.rope_freq_scale =*/ 0.0f,
  9674. /*.yarn_ext_factor =*/ -1.0f,
  9675. /*.yarn_attn_factor =*/ 1.0f,
  9676. /*.yarn_beta_fast =*/ 32.0f,
  9677. /*.yarn_beta_slow =*/ 1.0f,
  9678. /*.yarn_orig_ctx =*/ 0,
  9679. /*.defrag_thold =*/ -1.0f,
  9680. /*.cb_eval =*/ nullptr,
  9681. /*.cb_eval_user_data =*/ nullptr,
  9682. /*.type_k =*/ GGML_TYPE_F16,
  9683. /*.type_v =*/ GGML_TYPE_F16,
  9684. /*.mul_mat_q =*/ true,
  9685. /*.logits_all =*/ false,
  9686. /*.embedding =*/ false,
  9687. /*.offload_kqv =*/ true,
  9688. /*.do_pooling =*/ true,
  9689. };
  9690. return result;
  9691. }
  9692. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9693. struct llama_model_quantize_params result = {
  9694. /*.nthread =*/ 0,
  9695. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9696. /*.allow_requantize =*/ false,
  9697. /*.quantize_output_tensor =*/ true,
  9698. /*.only_copy =*/ false,
  9699. /*.pure =*/ false,
  9700. /*.imatrix =*/ nullptr,
  9701. };
  9702. return result;
  9703. }
  9704. size_t llama_max_devices(void) {
  9705. #if defined(GGML_USE_METAL)
  9706. return 1;
  9707. #elif defined(GGML_USE_CUBLAS)
  9708. return GGML_CUDA_MAX_DEVICES;
  9709. #elif defined(GGML_USE_SYCL)
  9710. return GGML_SYCL_MAX_DEVICES;
  9711. #elif defined(GGML_USE_VULKAN)
  9712. return GGML_VK_MAX_DEVICES;
  9713. #else
  9714. return 1;
  9715. #endif
  9716. }
  9717. bool llama_supports_mmap(void) {
  9718. return llama_mmap::SUPPORTED;
  9719. }
  9720. bool llama_supports_mlock(void) {
  9721. return llama_mlock::SUPPORTED;
  9722. }
  9723. bool llama_supports_gpu_offload(void) {
  9724. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  9725. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  9726. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  9727. return true;
  9728. #else
  9729. return false;
  9730. #endif
  9731. }
  9732. void llama_backend_init(void) {
  9733. ggml_time_init();
  9734. // needed to initialize f16 tables
  9735. {
  9736. struct ggml_init_params params = { 0, NULL, false };
  9737. struct ggml_context * ctx = ggml_init(params);
  9738. ggml_free(ctx);
  9739. }
  9740. #ifdef GGML_USE_MPI
  9741. ggml_mpi_backend_init();
  9742. #endif
  9743. }
  9744. void llama_numa_init(enum ggml_numa_strategy numa) {
  9745. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  9746. ggml_numa_init(numa);
  9747. }
  9748. }
  9749. void llama_backend_free(void) {
  9750. #ifdef GGML_USE_MPI
  9751. ggml_mpi_backend_free();
  9752. #endif
  9753. ggml_quantize_free();
  9754. }
  9755. int64_t llama_time_us(void) {
  9756. return ggml_time_us();
  9757. }
  9758. struct llama_model * llama_load_model_from_file(
  9759. const char * path_model,
  9760. struct llama_model_params params) {
  9761. ggml_time_init();
  9762. llama_model * model = new llama_model;
  9763. unsigned cur_percentage = 0;
  9764. if (params.progress_callback == NULL) {
  9765. params.progress_callback_user_data = &cur_percentage;
  9766. params.progress_callback = [](float progress, void * ctx) {
  9767. unsigned * cur_percentage_p = (unsigned *) ctx;
  9768. unsigned percentage = (unsigned) (100 * progress);
  9769. while (percentage > *cur_percentage_p) {
  9770. *cur_percentage_p = percentage;
  9771. LLAMA_LOG_INFO(".");
  9772. if (percentage >= 100) {
  9773. LLAMA_LOG_INFO("\n");
  9774. }
  9775. }
  9776. return true;
  9777. };
  9778. }
  9779. int status = llama_model_load(path_model, *model, params);
  9780. GGML_ASSERT(status <= 0);
  9781. if (status < 0) {
  9782. if (status == -1) {
  9783. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  9784. } else if (status == -2) {
  9785. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  9786. }
  9787. delete model;
  9788. return nullptr;
  9789. }
  9790. return model;
  9791. }
  9792. void llama_free_model(struct llama_model * model) {
  9793. delete model;
  9794. }
  9795. struct llama_context * llama_new_context_with_model(
  9796. struct llama_model * model,
  9797. struct llama_context_params params) {
  9798. if (!model) {
  9799. return nullptr;
  9800. }
  9801. llama_context * ctx = new llama_context(*model);
  9802. const auto & hparams = model->hparams;
  9803. auto & cparams = ctx->cparams;
  9804. cparams.n_batch = params.n_batch;
  9805. cparams.n_threads = params.n_threads;
  9806. cparams.n_threads_batch = params.n_threads_batch;
  9807. cparams.yarn_ext_factor = params.yarn_ext_factor;
  9808. cparams.yarn_attn_factor = params.yarn_attn_factor;
  9809. cparams.yarn_beta_fast = params.yarn_beta_fast;
  9810. cparams.yarn_beta_slow = params.yarn_beta_slow;
  9811. cparams.defrag_thold = params.defrag_thold;
  9812. cparams.mul_mat_q = params.mul_mat_q;
  9813. cparams.offload_kqv = params.offload_kqv;
  9814. cparams.do_pooling = params.do_pooling;
  9815. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  9816. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  9817. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  9818. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  9819. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  9820. hparams.n_ctx_train;
  9821. cparams.cb_eval = params.cb_eval;
  9822. cparams.cb_eval_user_data = params.cb_eval_user_data;
  9823. auto rope_scaling_type = params.rope_scaling_type;
  9824. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  9825. rope_scaling_type = hparams.rope_scaling_type_train;
  9826. }
  9827. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  9828. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  9829. }
  9830. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  9831. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  9832. }
  9833. if (params.seed == LLAMA_DEFAULT_SEED) {
  9834. params.seed = time(NULL);
  9835. }
  9836. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  9837. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  9838. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  9839. ctx->rng = std::mt19937(params.seed);
  9840. ctx->logits_all = params.logits_all;
  9841. const ggml_type type_k = params.type_k;
  9842. const ggml_type type_v = params.type_v;
  9843. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  9844. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  9845. if (!hparams.vocab_only) {
  9846. // initialize backends
  9847. #ifdef GGML_USE_METAL
  9848. if (model->n_gpu_layers > 0) {
  9849. ctx->backend_metal = ggml_backend_metal_init();
  9850. if (ctx->backend_metal == nullptr) {
  9851. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  9852. llama_free(ctx);
  9853. return nullptr;
  9854. }
  9855. ctx->backends.push_back(ctx->backend_metal);
  9856. }
  9857. #elif defined(GGML_USE_CUBLAS)
  9858. if (model->n_gpu_layers > 0) {
  9859. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  9860. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  9861. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  9862. if (backend == nullptr) {
  9863. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  9864. llama_free(ctx);
  9865. return nullptr;
  9866. }
  9867. ctx->backends.push_back(backend);
  9868. } else {
  9869. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  9870. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  9871. ggml_backend_t backend = ggml_backend_cuda_init(device);
  9872. if (backend == nullptr) {
  9873. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  9874. llama_free(ctx);
  9875. return nullptr;
  9876. }
  9877. ctx->backends.push_back(backend);
  9878. }
  9879. }
  9880. }
  9881. #elif defined(GGML_USE_VULKAN)
  9882. if (model->n_gpu_layers > 0) {
  9883. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  9884. ggml_backend_t backend = ggml_backend_vk_init(device);
  9885. if (backend == nullptr) {
  9886. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  9887. llama_free(ctx);
  9888. return nullptr;
  9889. }
  9890. ctx->backends.push_back(backend);
  9891. }
  9892. }
  9893. #elif defined(GGML_USE_SYCL)
  9894. if (model->n_gpu_layers > 0) {
  9895. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  9896. if (backend == nullptr) {
  9897. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  9898. llama_free(ctx);
  9899. return nullptr;
  9900. }
  9901. ctx->backends.push_back(backend);
  9902. }
  9903. #elif defined(GGML_USE_KOMPUTE)
  9904. if (model->n_gpu_layers > 0) {
  9905. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  9906. if (backend == nullptr) {
  9907. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  9908. llama_free(ctx);
  9909. return nullptr;
  9910. }
  9911. ctx->backends.push_back(backend);
  9912. }
  9913. #endif
  9914. ctx->backend_cpu = ggml_backend_cpu_init();
  9915. if (ctx->backend_cpu == nullptr) {
  9916. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  9917. llama_free(ctx);
  9918. return nullptr;
  9919. }
  9920. ctx->backends.push_back(ctx->backend_cpu);
  9921. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, cparams.n_ctx, cparams.offload_kqv)) {
  9922. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  9923. llama_free(ctx);
  9924. return nullptr;
  9925. }
  9926. {
  9927. size_t memory_size_k = 0;
  9928. size_t memory_size_v = 0;
  9929. for (auto & k : ctx->kv_self.k_l) {
  9930. memory_size_k += ggml_nbytes(k);
  9931. }
  9932. for (auto & v : ctx->kv_self.v_l) {
  9933. memory_size_v += ggml_nbytes(v);
  9934. }
  9935. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  9936. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  9937. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  9938. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  9939. }
  9940. // resized during inference, reserve maximum
  9941. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  9942. if (params.embedding) {
  9943. ctx->embedding.resize(hparams.n_embd);
  9944. }
  9945. // graph inputs
  9946. {
  9947. ggml_init_params init_params = {
  9948. /* .mem_size */ ggml_tensor_overhead()*8,
  9949. /* .mem_buffer */ nullptr,
  9950. /* .no_alloc */ true,
  9951. };
  9952. ctx->ctx_input = ggml_init(init_params);
  9953. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9954. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  9955. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9956. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  9957. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  9958. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  9959. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  9960. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9961. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  9962. ggml_set_name(ctx->inp_embd, "inp_embd");
  9963. ggml_set_name(ctx->inp_pos, "inp_pos");
  9964. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  9965. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  9966. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  9967. ggml_set_name(ctx->inp_mean, "inp_mean");
  9968. ggml_set_name(ctx->inp_cls, "inp_cls");
  9969. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  9970. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  9971. ggml_backend_buffer_name(ctx->buf_input),
  9972. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  9973. }
  9974. // scheduler and compute buffers
  9975. {
  9976. // buffer types used for the compute buffer of each backend
  9977. std::vector<ggml_backend_buffer_type_t> backend_buft;
  9978. for (auto * backend : ctx->backends) {
  9979. if (ggml_backend_is_cpu(backend)) {
  9980. // use host buffers for the CPU backend compute buffer
  9981. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  9982. } else {
  9983. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  9984. }
  9985. }
  9986. // buffer used to store the computation graph and the tensor meta data
  9987. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  9988. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  9989. // build worst-case graph
  9990. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  9991. int n_past = cparams.n_ctx - n_tokens;
  9992. 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
  9993. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  9994. // initialize scheduler with the worst-case graph
  9995. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  9996. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  9997. llama_free(ctx);
  9998. return nullptr;
  9999. }
  10000. for (size_t i = 0; i < ctx->backends.size(); i++) {
  10001. ggml_backend_t backend = ctx->backends[i];
  10002. ggml_backend_buffer_type_t buft = backend_buft[i];
  10003. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  10004. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  10005. ggml_backend_buft_name(buft),
  10006. size / 1024.0 / 1024.0);
  10007. }
  10008. // note: the number of splits during measure is higher than during inference due to the kv shift
  10009. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  10010. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  10011. }
  10012. }
  10013. #ifdef GGML_USE_MPI
  10014. ctx->ctx_mpi = ggml_mpi_init();
  10015. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  10016. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  10017. // TODO: needs fix after #3228
  10018. GGML_ASSERT(false && "not implemented");
  10019. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  10020. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  10021. llama_backend_free();
  10022. exit(1);
  10023. }
  10024. #endif
  10025. return ctx;
  10026. }
  10027. void llama_free(struct llama_context * ctx) {
  10028. delete ctx;
  10029. }
  10030. const llama_model * llama_get_model(const struct llama_context * ctx) {
  10031. return &ctx->model;
  10032. }
  10033. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  10034. return ctx->cparams.n_ctx;
  10035. }
  10036. uint32_t llama_n_batch(const struct llama_context * ctx) {
  10037. return ctx->cparams.n_batch;
  10038. }
  10039. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  10040. return model->vocab.type;
  10041. }
  10042. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  10043. switch (model->arch) {
  10044. // these models do not use RoPE
  10045. case LLM_ARCH_GPT2:
  10046. case LLM_ARCH_GPTJ:
  10047. case LLM_ARCH_GPTNEOX:
  10048. case LLM_ARCH_MPT:
  10049. case LLM_ARCH_REFACT:
  10050. case LLM_ARCH_BLOOM:
  10051. return LLAMA_ROPE_TYPE_NONE;
  10052. // use what we call a normal RoPE, operating on pairs of consecutive head values
  10053. case LLM_ARCH_LLAMA:
  10054. case LLM_ARCH_BAICHUAN:
  10055. case LLM_ARCH_STARCODER:
  10056. case LLM_ARCH_PLAMO:
  10057. case LLM_ARCH_CODESHELL:
  10058. case LLM_ARCH_ORION:
  10059. case LLM_ARCH_INTERNLM2:
  10060. case LLM_ARCH_MINICPM:
  10061. return LLAMA_ROPE_TYPE_NORM;
  10062. // the pairs of head values are offset by n_rot/2
  10063. case LLM_ARCH_FALCON:
  10064. case LLM_ARCH_PERSIMMON:
  10065. case LLM_ARCH_BERT:
  10066. case LLM_ARCH_NOMIC_BERT:
  10067. case LLM_ARCH_STABLELM:
  10068. case LLM_ARCH_QWEN:
  10069. case LLM_ARCH_QWEN2:
  10070. case LLM_ARCH_PHI2:
  10071. case LLM_ARCH_GEMMA:
  10072. return LLAMA_ROPE_TYPE_NEOX;
  10073. // all model arches should be listed explicitly here
  10074. case LLM_ARCH_UNKNOWN:
  10075. GGML_ASSERT(false && "unknown architecture");
  10076. break;
  10077. }
  10078. return LLAMA_ROPE_TYPE_NONE;
  10079. }
  10080. int32_t llama_n_vocab(const struct llama_model * model) {
  10081. return model->vocab.id_to_token.size();
  10082. }
  10083. int32_t llama_n_ctx_train(const struct llama_model * model) {
  10084. return model->hparams.n_ctx_train;
  10085. }
  10086. int32_t llama_n_embd(const struct llama_model * model) {
  10087. return model->hparams.n_embd;
  10088. }
  10089. float llama_rope_freq_scale_train(const struct llama_model * model) {
  10090. return model->hparams.rope_freq_scale_train;
  10091. }
  10092. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  10093. const auto & it = model->gguf_kv.find(key);
  10094. if (it == model->gguf_kv.end()) {
  10095. if (buf_size > 0) {
  10096. buf[0] = '\0';
  10097. }
  10098. return -1;
  10099. }
  10100. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10101. }
  10102. int32_t llama_model_meta_count(const struct llama_model * model) {
  10103. return (int)model->gguf_kv.size();
  10104. }
  10105. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  10106. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10107. if (buf_size > 0) {
  10108. buf[0] = '\0';
  10109. }
  10110. return -1;
  10111. }
  10112. auto it = model->gguf_kv.begin();
  10113. std::advance(it, i);
  10114. return snprintf(buf, buf_size, "%s", it->first.c_str());
  10115. }
  10116. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  10117. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10118. if (buf_size > 0) {
  10119. buf[0] = '\0';
  10120. }
  10121. return -1;
  10122. }
  10123. auto it = model->gguf_kv.begin();
  10124. std::advance(it, i);
  10125. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10126. }
  10127. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  10128. return snprintf(buf, buf_size, "%s %s %s",
  10129. llama_model_arch_name(model->arch),
  10130. llama_model_type_name(model->type),
  10131. llama_model_ftype_name(model->ftype).c_str());
  10132. }
  10133. uint64_t llama_model_size(const struct llama_model * model) {
  10134. uint64_t size = 0;
  10135. for (const auto & it : model->tensors_by_name) {
  10136. size += ggml_nbytes(it.second);
  10137. }
  10138. return size;
  10139. }
  10140. uint64_t llama_model_n_params(const struct llama_model * model) {
  10141. uint64_t nparams = 0;
  10142. for (const auto & it : model->tensors_by_name) {
  10143. nparams += ggml_nelements(it.second);
  10144. }
  10145. return nparams;
  10146. }
  10147. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  10148. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  10149. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  10150. return it.first == name;
  10151. });
  10152. if (it == model->tensors_by_name.end()) {
  10153. return nullptr;
  10154. }
  10155. return it->second;
  10156. }
  10157. uint32_t llama_model_quantize(
  10158. const char * fname_inp,
  10159. const char * fname_out,
  10160. const llama_model_quantize_params * params) {
  10161. try {
  10162. llama_model_quantize_internal(fname_inp, fname_out, params);
  10163. return 0;
  10164. } catch (const std::exception & err) {
  10165. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  10166. return 1;
  10167. }
  10168. }
  10169. 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) {
  10170. try {
  10171. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  10172. } catch (const std::exception & err) {
  10173. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  10174. return 1;
  10175. }
  10176. }
  10177. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  10178. struct llama_kv_cache_view result = {
  10179. /*.n_cells = */ 0,
  10180. /*.n_max_seq = */ n_max_seq,
  10181. /*.token_count = */ 0,
  10182. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  10183. /*.max_contiguous = */ 0,
  10184. /*.max_contiguous_idx = */ -1,
  10185. /*.cells = */ nullptr,
  10186. /*.cells_sequences = */ nullptr,
  10187. };
  10188. return result;
  10189. }
  10190. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  10191. if (view->cells != nullptr) {
  10192. free(view->cells);
  10193. view->cells = nullptr;
  10194. }
  10195. if (view->cells_sequences != nullptr) {
  10196. free(view->cells_sequences);
  10197. view->cells_sequences = nullptr;
  10198. }
  10199. }
  10200. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  10201. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  10202. view->n_cells = int32_t(ctx->kv_self.size);
  10203. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  10204. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  10205. view->cells = (struct llama_kv_cache_view_cell *)p;
  10206. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  10207. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  10208. view->cells_sequences = (llama_seq_id *)p;
  10209. }
  10210. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  10211. llama_kv_cache_view_cell * c_curr = view->cells;
  10212. llama_seq_id * cs_curr = view->cells_sequences;
  10213. int32_t used_cells = 0;
  10214. int32_t token_count = 0;
  10215. int32_t curr_contig_idx = -1;
  10216. uint32_t max_contig = 0;
  10217. int32_t max_contig_idx = -1;
  10218. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10219. const size_t curr_size = kv_cells[i].seq_id.size();
  10220. token_count += curr_size;
  10221. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10222. if (curr_size > 0) {
  10223. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10224. max_contig = i - curr_contig_idx;
  10225. max_contig_idx = curr_contig_idx;
  10226. }
  10227. curr_contig_idx = -1;
  10228. } else if (curr_contig_idx < 0) {
  10229. curr_contig_idx = i;
  10230. }
  10231. int seq_idx = 0;
  10232. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10233. if (seq_idx >= view->n_max_seq) {
  10234. break;
  10235. }
  10236. cs_curr[seq_idx] = it;
  10237. seq_idx++;
  10238. }
  10239. if (seq_idx != 0) {
  10240. used_cells++;
  10241. }
  10242. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10243. cs_curr[seq_idx] = -1;
  10244. }
  10245. }
  10246. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10247. max_contig_idx = curr_contig_idx;
  10248. max_contig = kv_cells.size() - curr_contig_idx;
  10249. }
  10250. view->max_contiguous = max_contig;
  10251. view->max_contiguous_idx = max_contig_idx;
  10252. view->token_count = token_count;
  10253. view->used_cells = used_cells;
  10254. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10255. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10256. __func__, ctx->kv_self.used, used_cells);
  10257. }
  10258. }
  10259. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10260. int result = 0;
  10261. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10262. result += ctx->kv_self.cells[i].seq_id.size();
  10263. }
  10264. return result;
  10265. }
  10266. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10267. return ctx->kv_self.used;
  10268. }
  10269. void llama_kv_cache_clear(struct llama_context * ctx) {
  10270. llama_kv_cache_clear(ctx->kv_self);
  10271. }
  10272. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10273. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10274. }
  10275. 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) {
  10276. if (seq_id_src == seq_id_dst) {
  10277. return;
  10278. }
  10279. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10280. }
  10281. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10282. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10283. }
  10284. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10285. if (delta == 0) {
  10286. return;
  10287. }
  10288. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  10289. }
  10290. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10291. if (d == 1) {
  10292. return;
  10293. }
  10294. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10295. }
  10296. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  10297. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  10298. }
  10299. void llama_kv_cache_defrag(struct llama_context * ctx) {
  10300. llama_kv_cache_defrag(ctx->kv_self);
  10301. }
  10302. void llama_kv_cache_update(struct llama_context * ctx) {
  10303. llama_kv_cache_update_internal(*ctx);
  10304. }
  10305. // Returns the *maximum* size of the state
  10306. size_t llama_get_state_size(const struct llama_context * ctx) {
  10307. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10308. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10309. const size_t s_rng_size = sizeof(size_t);
  10310. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10311. const size_t s_logits_size = sizeof(size_t);
  10312. // assume worst case for logits although only currently set ones are serialized
  10313. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10314. const size_t s_embedding_size = sizeof(size_t);
  10315. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  10316. const size_t s_kv_size = sizeof(size_t);
  10317. const size_t s_kv_ntok = sizeof(int);
  10318. const size_t s_kv = ctx->kv_self.total_size();
  10319. const size_t s_total = (
  10320. + s_rng_size
  10321. + s_rng
  10322. + s_logits_size
  10323. + s_logits
  10324. + s_embedding_size
  10325. + s_embedding
  10326. + s_kv_size
  10327. + s_kv_ntok
  10328. + s_kv
  10329. );
  10330. return s_total;
  10331. }
  10332. // llama_context_data
  10333. struct llama_data_context {
  10334. virtual void write(const void * src, size_t size) = 0;
  10335. virtual size_t get_size_written() = 0;
  10336. virtual ~llama_data_context() = default;
  10337. };
  10338. struct llama_data_buffer_context : llama_data_context {
  10339. uint8_t * ptr;
  10340. size_t size_written = 0;
  10341. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10342. void write(const void * src, size_t size) override {
  10343. memcpy(ptr, src, size);
  10344. ptr += size;
  10345. size_written += size;
  10346. }
  10347. size_t get_size_written() override {
  10348. return size_written;
  10349. }
  10350. };
  10351. struct llama_data_file_context : llama_data_context {
  10352. llama_file * file;
  10353. size_t size_written = 0;
  10354. llama_data_file_context(llama_file * f) : file(f) {}
  10355. void write(const void * src, size_t size) override {
  10356. file->write_raw(src, size);
  10357. size_written += size;
  10358. }
  10359. size_t get_size_written() override {
  10360. return size_written;
  10361. }
  10362. };
  10363. /** copy state data into either a buffer or file depending on the passed in context
  10364. *
  10365. * file context:
  10366. * llama_file file("/path", "wb");
  10367. * llama_data_file_context data_ctx(&file);
  10368. * llama_copy_state_data(ctx, &data_ctx);
  10369. *
  10370. * buffer context:
  10371. * std::vector<uint8_t> buf(max_size, 0);
  10372. * llama_data_buffer_context data_ctx(&buf.data());
  10373. * llama_copy_state_data(ctx, &data_ctx);
  10374. *
  10375. */
  10376. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10377. // copy rng
  10378. {
  10379. std::ostringstream rng_ss;
  10380. rng_ss << ctx->rng;
  10381. const std::string & rng_str = rng_ss.str();
  10382. const size_t rng_size = rng_str.size();
  10383. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10384. data_ctx->write(&rng_size, sizeof(rng_size));
  10385. data_ctx->write(rng_str.data(), rng_size);
  10386. }
  10387. // copy logits
  10388. {
  10389. const size_t logits_size = ctx->logits.size();
  10390. data_ctx->write(&logits_size, sizeof(logits_size));
  10391. if (logits_size) {
  10392. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10393. }
  10394. }
  10395. // copy embeddings
  10396. {
  10397. const size_t embedding_size = ctx->embedding.size();
  10398. data_ctx->write(&embedding_size, sizeof(embedding_size));
  10399. if (embedding_size) {
  10400. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  10401. }
  10402. }
  10403. // copy kv cache
  10404. {
  10405. const auto & kv_self = ctx->kv_self;
  10406. const auto & hparams = ctx->model.hparams;
  10407. const auto & cparams = ctx->cparams;
  10408. const uint32_t n_layer = hparams.n_layer;
  10409. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10410. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10411. const uint32_t n_ctx = cparams.n_ctx;
  10412. const size_t kv_buf_size = kv_self.total_size();
  10413. const uint32_t kv_head = kv_self.head;
  10414. const uint32_t kv_size = kv_self.size;
  10415. const uint32_t kv_used = kv_self.used;
  10416. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10417. data_ctx->write(&kv_head, sizeof(kv_head));
  10418. data_ctx->write(&kv_size, sizeof(kv_size));
  10419. data_ctx->write(&kv_used, sizeof(kv_used));
  10420. if (kv_buf_size) {
  10421. std::vector<uint8_t> tmp_buf;
  10422. for (int il = 0; il < (int) n_layer; ++il) {
  10423. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10424. tmp_buf.resize(k_size);
  10425. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10426. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10427. // v is not contiguous, copy row by row
  10428. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10429. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10430. tmp_buf.resize(v_row_size);
  10431. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10432. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10433. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10434. }
  10435. }
  10436. }
  10437. for (uint32_t i = 0; i < kv_size; ++i) {
  10438. const auto & cell = kv_self.cells[i];
  10439. const llama_pos pos = cell.pos;
  10440. const size_t seq_id_size = cell.seq_id.size();
  10441. data_ctx->write(&pos, sizeof(pos));
  10442. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10443. for (auto seq_id : cell.seq_id) {
  10444. data_ctx->write(&seq_id, sizeof(seq_id));
  10445. }
  10446. }
  10447. }
  10448. }
  10449. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10450. llama_data_buffer_context data_ctx(dst);
  10451. llama_copy_state_data_internal(ctx, &data_ctx);
  10452. return data_ctx.get_size_written();
  10453. }
  10454. // Sets the state reading from the specified source address
  10455. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  10456. uint8_t * inp = src;
  10457. // set rng
  10458. {
  10459. size_t rng_size;
  10460. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10461. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10462. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  10463. std::istringstream rng_ss(rng_str);
  10464. rng_ss >> ctx->rng;
  10465. GGML_ASSERT(!rng_ss.fail());
  10466. }
  10467. // set logits
  10468. {
  10469. size_t logits_size;
  10470. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10471. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10472. if (logits_size) {
  10473. ctx->logits.resize(logits_size);
  10474. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10475. inp += logits_size * sizeof(float);
  10476. }
  10477. }
  10478. // set embeddings
  10479. {
  10480. size_t embedding_size;
  10481. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  10482. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  10483. if (embedding_size) {
  10484. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  10485. inp += embedding_size * sizeof(float);
  10486. }
  10487. }
  10488. // set kv cache
  10489. {
  10490. const auto & kv_self = ctx->kv_self;
  10491. const auto & hparams = ctx->model.hparams;
  10492. const auto & cparams = ctx->cparams;
  10493. const uint32_t n_layer = hparams.n_layer;
  10494. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10495. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10496. const uint32_t n_ctx = cparams.n_ctx;
  10497. size_t kv_buf_size;
  10498. uint32_t kv_head;
  10499. uint32_t kv_size;
  10500. uint32_t kv_used;
  10501. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10502. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10503. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10504. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10505. if (kv_buf_size) {
  10506. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10507. for (int il = 0; il < (int) n_layer; ++il) {
  10508. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10509. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10510. inp += k_size;
  10511. // v is not contiguous, copy row by row
  10512. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10513. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10514. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10515. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10516. inp += v_row_size;
  10517. }
  10518. }
  10519. }
  10520. ctx->kv_self.head = kv_head;
  10521. ctx->kv_self.size = kv_size;
  10522. ctx->kv_self.used = kv_used;
  10523. ctx->kv_self.cells.resize(kv_size);
  10524. for (uint32_t i = 0; i < kv_size; ++i) {
  10525. llama_pos pos;
  10526. size_t seq_id_size;
  10527. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10528. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10529. ctx->kv_self.cells[i].pos = pos;
  10530. llama_seq_id seq_id;
  10531. for (size_t j = 0; j < seq_id_size; ++j) {
  10532. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10533. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10534. }
  10535. }
  10536. }
  10537. const size_t nread = inp - src;
  10538. const size_t max_size = llama_get_state_size(ctx);
  10539. GGML_ASSERT(nread <= max_size);
  10540. return nread;
  10541. }
  10542. 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) {
  10543. llama_file file(path_session, "rb");
  10544. // sanity checks
  10545. {
  10546. const uint32_t magic = file.read_u32();
  10547. const uint32_t version = file.read_u32();
  10548. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10549. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10550. return false;
  10551. }
  10552. llama_hparams session_hparams;
  10553. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10554. if (session_hparams != ctx->model.hparams) {
  10555. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10556. return false;
  10557. }
  10558. }
  10559. // load the prompt
  10560. {
  10561. const uint32_t n_token_count = file.read_u32();
  10562. if (n_token_count > n_token_capacity) {
  10563. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10564. return false;
  10565. }
  10566. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10567. *n_token_count_out = n_token_count;
  10568. }
  10569. // restore the context state
  10570. {
  10571. const size_t n_state_size_cur = file.size - file.tell();
  10572. const size_t n_state_size_max = llama_get_state_size(ctx);
  10573. if (n_state_size_cur > n_state_size_max) {
  10574. 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);
  10575. return false;
  10576. }
  10577. std::vector<uint8_t> state_data(n_state_size_max);
  10578. file.read_raw(state_data.data(), n_state_size_cur);
  10579. llama_set_state_data(ctx, state_data.data());
  10580. }
  10581. return true;
  10582. }
  10583. 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) {
  10584. try {
  10585. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10586. } catch (const std::exception & err) {
  10587. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10588. return false;
  10589. }
  10590. }
  10591. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10592. llama_file file(path_session, "wb");
  10593. file.write_u32(LLAMA_SESSION_MAGIC);
  10594. file.write_u32(LLAMA_SESSION_VERSION);
  10595. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10596. // save the prompt
  10597. file.write_u32((uint32_t) n_token_count);
  10598. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10599. // save the context state using stream saving
  10600. llama_data_file_context data_ctx(&file);
  10601. llama_copy_state_data_internal(ctx, &data_ctx);
  10602. return true;
  10603. }
  10604. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10605. ctx->cparams.n_threads = n_threads;
  10606. ctx->cparams.n_threads_batch = n_threads_batch;
  10607. }
  10608. struct llama_batch llama_batch_get_one(
  10609. llama_token * tokens,
  10610. int32_t n_tokens,
  10611. llama_pos pos_0,
  10612. llama_seq_id seq_id) {
  10613. return {
  10614. /*n_tokens =*/ n_tokens,
  10615. /*tokens =*/ tokens,
  10616. /*embd =*/ nullptr,
  10617. /*pos =*/ nullptr,
  10618. /*n_seq_id =*/ nullptr,
  10619. /*seq_id =*/ nullptr,
  10620. /*logits =*/ nullptr,
  10621. /*all_pos_0 =*/ pos_0,
  10622. /*all_pos_1 =*/ 1,
  10623. /*all_seq_id =*/ seq_id,
  10624. };
  10625. }
  10626. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10627. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10628. if (embd) {
  10629. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10630. } else {
  10631. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10632. }
  10633. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10634. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10635. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10636. for (int i = 0; i < n_tokens_alloc; ++i) {
  10637. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10638. }
  10639. batch.seq_id[n_tokens_alloc] = nullptr;
  10640. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10641. return batch;
  10642. }
  10643. void llama_batch_free(struct llama_batch batch) {
  10644. if (batch.token) free(batch.token);
  10645. if (batch.embd) free(batch.embd);
  10646. if (batch.pos) free(batch.pos);
  10647. if (batch.n_seq_id) free(batch.n_seq_id);
  10648. if (batch.seq_id) {
  10649. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10650. free(batch.seq_id[i]);
  10651. }
  10652. free(batch.seq_id);
  10653. }
  10654. if (batch.logits) free(batch.logits);
  10655. }
  10656. int32_t llama_decode(
  10657. struct llama_context * ctx,
  10658. struct llama_batch batch) {
  10659. const int ret = llama_decode_internal(*ctx, batch);
  10660. if (ret < 0) {
  10661. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10662. }
  10663. return ret;
  10664. }
  10665. float * llama_get_logits(struct llama_context * ctx) {
  10666. return ctx->logits.data();
  10667. }
  10668. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10669. assert(ctx->logits_valid.at(i));
  10670. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  10671. }
  10672. float * llama_get_embeddings(struct llama_context * ctx) {
  10673. return ctx->embedding.data();
  10674. }
  10675. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  10676. return ctx->embedding.data() + i*ctx->model.hparams.n_embd;
  10677. }
  10678. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  10679. return model->vocab.id_to_token[token].text.c_str();
  10680. }
  10681. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  10682. return model->vocab.id_to_token[token].score;
  10683. }
  10684. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  10685. return model->vocab.id_to_token[token].type;
  10686. }
  10687. llama_token llama_token_bos(const struct llama_model * model) {
  10688. return model->vocab.special_bos_id;
  10689. }
  10690. llama_token llama_token_eos(const struct llama_model * model) {
  10691. return model->vocab.special_eos_id;
  10692. }
  10693. llama_token llama_token_nl(const struct llama_model * model) {
  10694. return model->vocab.linefeed_id;
  10695. }
  10696. int32_t llama_add_bos_token(const struct llama_model * model) {
  10697. return model->vocab.special_add_bos;
  10698. }
  10699. int32_t llama_add_eos_token(const struct llama_model * model) {
  10700. return model->vocab.special_add_eos;
  10701. }
  10702. llama_token llama_token_prefix(const struct llama_model * model) {
  10703. return model->vocab.special_prefix_id;
  10704. }
  10705. llama_token llama_token_middle(const struct llama_model * model) {
  10706. return model->vocab.special_middle_id;
  10707. }
  10708. llama_token llama_token_suffix(const struct llama_model * model) {
  10709. return model->vocab.special_suffix_id;
  10710. }
  10711. llama_token llama_token_eot(const struct llama_model * model) {
  10712. return model->vocab.special_eot_id;
  10713. }
  10714. int32_t llama_tokenize(
  10715. const struct llama_model * model,
  10716. const char * text,
  10717. int32_t text_len,
  10718. llama_token * tokens,
  10719. int32_t n_max_tokens,
  10720. bool add_bos,
  10721. bool special) {
  10722. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  10723. if (n_max_tokens < (int) res.size()) {
  10724. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  10725. return -((int) res.size());
  10726. }
  10727. for (size_t i = 0; i < res.size(); i++) {
  10728. tokens[i] = res[i];
  10729. }
  10730. return res.size();
  10731. }
  10732. static std::string llama_decode_text(const std::string & text) {
  10733. std::string decoded_text;
  10734. auto unicode_sequences = codepoints_from_utf8(text);
  10735. for (auto& unicode_sequence : unicode_sequences) {
  10736. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  10737. }
  10738. return decoded_text;
  10739. }
  10740. // does not write null-terminator to buf
  10741. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  10742. if (0 <= token && token < llama_n_vocab(model)) {
  10743. switch (llama_vocab_get_type(model->vocab)) {
  10744. case LLAMA_VOCAB_TYPE_WPM:
  10745. case LLAMA_VOCAB_TYPE_SPM: {
  10746. // NOTE: we accept all unsupported token types,
  10747. // suppressing them like CONTROL tokens.
  10748. if (llama_is_normal_token(model->vocab, token)) {
  10749. std::string result = model->vocab.id_to_token[token].text;
  10750. llama_unescape_whitespace(result);
  10751. if (length < (int) result.length()) {
  10752. return -(int) result.length();
  10753. }
  10754. memcpy(buf, result.c_str(), result.length());
  10755. return result.length();
  10756. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10757. std::string result = model->vocab.id_to_token[token].text;
  10758. if (length < (int) result.length()) {
  10759. return -result.length();
  10760. }
  10761. memcpy(buf, result.c_str(), result.length());
  10762. return result.length();
  10763. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  10764. if (length < 3) {
  10765. return -3;
  10766. }
  10767. memcpy(buf, "\xe2\x96\x85", 3);
  10768. return 3;
  10769. } else if (llama_is_control_token(model->vocab, token)) {
  10770. ;
  10771. } else if (llama_is_byte_token(model->vocab, token)) {
  10772. if (length < 1) {
  10773. return -1;
  10774. }
  10775. buf[0] = llama_token_to_byte(model->vocab, token);
  10776. return 1;
  10777. }
  10778. break;
  10779. }
  10780. case LLAMA_VOCAB_TYPE_BPE: {
  10781. // NOTE: we accept all unsupported token types,
  10782. // suppressing them like CONTROL tokens.
  10783. if (llama_is_normal_token(model->vocab, token)) {
  10784. std::string result = model->vocab.id_to_token[token].text;
  10785. result = llama_decode_text(result);
  10786. if (length < (int) result.length()) {
  10787. return -(int) result.length();
  10788. }
  10789. memcpy(buf, result.c_str(), result.length());
  10790. return result.length();
  10791. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10792. std::string result = model->vocab.id_to_token[token].text;
  10793. if (length < (int) result.length()) {
  10794. return -result.length();
  10795. }
  10796. memcpy(buf, result.c_str(), result.length());
  10797. return result.length();
  10798. } else if (llama_is_control_token(model->vocab, token)) {
  10799. ;
  10800. }
  10801. break;
  10802. }
  10803. default:
  10804. GGML_ASSERT(false);
  10805. }
  10806. }
  10807. return 0;
  10808. }
  10809. // trim whitespace from the beginning and end of a string
  10810. static std::string trim(const std::string & str) {
  10811. size_t start = 0;
  10812. size_t end = str.size();
  10813. while (start < end && isspace(str[start])) {
  10814. start += 1;
  10815. }
  10816. while (end > start && isspace(str[end - 1])) {
  10817. end -= 1;
  10818. }
  10819. return str.substr(start, end - start);
  10820. }
  10821. // Simple version of "llama_apply_chat_template" that only works with strings
  10822. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  10823. static int32_t llama_chat_apply_template_internal(
  10824. const std::string & tmpl,
  10825. const std::vector<const llama_chat_message *> & chat,
  10826. std::string & dest, bool add_ass) {
  10827. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  10828. std::stringstream ss;
  10829. if (tmpl.find("<|im_start|>") != std::string::npos) {
  10830. // chatml template
  10831. for (auto message : chat) {
  10832. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  10833. }
  10834. if (add_ass) {
  10835. ss << "<|im_start|>assistant\n";
  10836. }
  10837. } else if (tmpl.find("[INST]") != std::string::npos) {
  10838. // llama2 template and its variants
  10839. // [variant] support system message
  10840. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  10841. // [variant] space before + after response
  10842. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  10843. // [variant] add BOS inside history
  10844. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  10845. // [variant] trim spaces from the input message
  10846. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  10847. // construct the prompt
  10848. bool is_inside_turn = true; // skip BOS at the beginning
  10849. ss << "[INST] ";
  10850. for (auto message : chat) {
  10851. std::string content = strip_message ? trim(message->content) : message->content;
  10852. std::string role(message->role);
  10853. if (!is_inside_turn) {
  10854. is_inside_turn = true;
  10855. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  10856. }
  10857. if (role == "system") {
  10858. if (support_system_message) {
  10859. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  10860. } else {
  10861. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  10862. ss << content << "\n";
  10863. }
  10864. } else if (role == "user") {
  10865. ss << content << " [/INST]";
  10866. } else {
  10867. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  10868. is_inside_turn = false;
  10869. }
  10870. }
  10871. // llama2 templates seem to not care about "add_generation_prompt"
  10872. } else if (tmpl.find("<|user|>") != std::string::npos) {
  10873. // zephyr template
  10874. for (auto message : chat) {
  10875. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  10876. }
  10877. if (add_ass) {
  10878. ss << "<|assistant|>\n";
  10879. }
  10880. } else if (tmpl.find("bos_token + message['role']") != std::string::npos) {
  10881. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  10882. for (auto message : chat) {
  10883. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  10884. ss << bos << message->role << "\n" << message->content << "</s>\n";
  10885. }
  10886. if (add_ass) {
  10887. ss << "<s>assistant\n";
  10888. }
  10889. } else if (tmpl.find("<start_of_turn>") != std::string::npos) {
  10890. // google/gemma-7b-it
  10891. std::string system_prompt = "";
  10892. for (auto message : chat) {
  10893. std::string role(message->role);
  10894. if (role == "system") {
  10895. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  10896. system_prompt = trim(message->content);
  10897. continue;
  10898. }
  10899. // in gemma, "assistant" is "model"
  10900. role = role == "assistant" ? "model" : message->role;
  10901. ss << "<start_of_turn>" << role << "\n";
  10902. if (!system_prompt.empty() && role != "model") {
  10903. ss << system_prompt << "\n\n";
  10904. system_prompt = "";
  10905. }
  10906. ss << trim(message->content) << "<end_of_turn>\n";
  10907. }
  10908. if (add_ass) {
  10909. ss << "<start_of_turn>model\n";
  10910. }
  10911. } else {
  10912. // template not supported
  10913. return -1;
  10914. }
  10915. dest = ss.str();
  10916. return dest.size();
  10917. }
  10918. LLAMA_API int32_t llama_chat_apply_template(
  10919. const struct llama_model * model,
  10920. const char * tmpl,
  10921. const struct llama_chat_message * chat,
  10922. size_t n_msg,
  10923. bool add_ass,
  10924. char * buf,
  10925. int32_t length) {
  10926. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  10927. if (tmpl == nullptr) {
  10928. GGML_ASSERT(model != nullptr);
  10929. // load template from model
  10930. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  10931. std::string template_key = "tokenizer.chat_template";
  10932. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  10933. if (res < 0) {
  10934. // worst case: there is no information about template, we will use chatml by default
  10935. curr_tmpl = "<|im_start|>"; // see llama_chat_apply_template_internal
  10936. } else {
  10937. curr_tmpl = std::string(model_template.data(), model_template.size());
  10938. }
  10939. }
  10940. // format the chat to string
  10941. std::vector<const llama_chat_message *> chat_vec;
  10942. chat_vec.resize(n_msg);
  10943. for (size_t i = 0; i < n_msg; i++) {
  10944. chat_vec[i] = &chat[i];
  10945. }
  10946. std::string formatted_chat;
  10947. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  10948. if (res < 0) {
  10949. return res;
  10950. }
  10951. strncpy(buf, formatted_chat.c_str(), length);
  10952. return res;
  10953. }
  10954. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  10955. struct llama_timings result = {
  10956. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  10957. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  10958. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  10959. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  10960. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  10961. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  10962. /*.n_sample =*/ std::max(1, ctx->n_sample),
  10963. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  10964. /*.n_eval =*/ std::max(1, ctx->n_eval),
  10965. };
  10966. return result;
  10967. }
  10968. void llama_print_timings(struct llama_context * ctx) {
  10969. const llama_timings timings = llama_get_timings(ctx);
  10970. LLAMA_LOG_INFO("\n");
  10971. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  10972. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10973. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  10974. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  10975. __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);
  10976. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10977. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  10978. 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));
  10979. }
  10980. void llama_reset_timings(struct llama_context * ctx) {
  10981. ctx->t_start_us = ggml_time_us();
  10982. ctx->t_sample_us = ctx->n_sample = 0;
  10983. ctx->t_eval_us = ctx->n_eval = 0;
  10984. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  10985. }
  10986. const char * llama_print_system_info(void) {
  10987. static std::string s;
  10988. s = "";
  10989. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  10990. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  10991. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  10992. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  10993. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  10994. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  10995. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  10996. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  10997. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  10998. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  10999. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  11000. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  11001. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  11002. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  11003. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  11004. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  11005. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  11006. return s.c_str();
  11007. }
  11008. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  11009. fprintf(stream, "\n");
  11010. fprintf(stream, "###########\n");
  11011. fprintf(stream, "# Timings #\n");
  11012. fprintf(stream, "###########\n");
  11013. fprintf(stream, "\n");
  11014. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  11015. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  11016. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  11017. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  11018. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  11019. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  11020. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  11021. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  11022. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  11023. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  11024. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  11025. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  11026. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  11027. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  11028. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  11029. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  11030. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  11031. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  11032. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  11033. }
  11034. // For internal test use
  11035. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  11036. struct llama_context * ctx
  11037. ) {
  11038. return ctx->model.tensors_by_name;
  11039. }
  11040. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  11041. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  11042. g_state.log_callback_user_data = user_data;
  11043. #ifdef GGML_USE_METAL
  11044. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  11045. #endif
  11046. }
  11047. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  11048. va_list args_copy;
  11049. va_copy(args_copy, args);
  11050. char buffer[128];
  11051. int len = vsnprintf(buffer, 128, format, args);
  11052. if (len < 128) {
  11053. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  11054. } else {
  11055. char* buffer2 = new char[len+1];
  11056. vsnprintf(buffer2, len+1, format, args_copy);
  11057. buffer2[len] = 0;
  11058. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  11059. delete[] buffer2;
  11060. }
  11061. va_end(args_copy);
  11062. }
  11063. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  11064. va_list args;
  11065. va_start(args, format);
  11066. llama_log_internal_v(level, format, args);
  11067. va_end(args);
  11068. }
  11069. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  11070. (void) level;
  11071. (void) user_data;
  11072. fputs(text, stderr);
  11073. fflush(stderr);
  11074. }