llama.cpp 421 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034
  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. #endif
  12. #ifdef GGML_USE_METAL
  13. # include "ggml-metal.h"
  14. #endif
  15. #ifdef GGML_USE_MPI
  16. # include "ggml-mpi.h"
  17. #endif
  18. #ifndef QK_K
  19. # ifdef GGML_QKK_64
  20. # define QK_K 64
  21. # else
  22. # define QK_K 256
  23. # endif
  24. #endif
  25. #ifdef __has_include
  26. #if __has_include(<unistd.h>)
  27. #include <unistd.h>
  28. #if defined(_POSIX_MAPPED_FILES)
  29. #include <sys/mman.h>
  30. #include <fcntl.h>
  31. #endif
  32. #if defined(_POSIX_MEMLOCK_RANGE)
  33. #include <sys/resource.h>
  34. #endif
  35. #endif
  36. #endif
  37. #if defined(_WIN32)
  38. #define WIN32_LEAN_AND_MEAN
  39. #ifndef NOMINMAX
  40. #define NOMINMAX
  41. #endif
  42. #include <windows.h>
  43. #include <io.h>
  44. #endif
  45. #include <algorithm>
  46. #include <array>
  47. #include <cassert>
  48. #include <cinttypes>
  49. #include <climits>
  50. #include <cmath>
  51. #include <cstdarg>
  52. #include <cstddef>
  53. #include <cstdint>
  54. #include <cstdio>
  55. #include <cstring>
  56. #include <ctime>
  57. #include <forward_list>
  58. #include <fstream>
  59. #include <functional>
  60. #include <initializer_list>
  61. #include <map>
  62. #include <memory>
  63. #include <mutex>
  64. #include <numeric>
  65. #include <queue>
  66. #include <random>
  67. #include <regex>
  68. #include <set>
  69. #include <sstream>
  70. #include <thread>
  71. #include <type_traits>
  72. #include <unordered_map>
  73. #if defined(_MSC_VER)
  74. #pragma warning(disable: 4244 4267) // possible loss of data
  75. #endif
  76. #ifdef __GNUC__
  77. #ifdef __MINGW32__
  78. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  79. #else
  80. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  81. #endif
  82. #else
  83. #define LLAMA_ATTRIBUTE_FORMAT(...)
  84. #endif
  85. #define LLAMA_MAX_NODES 8192
  86. #define LLAMA_MAX_EXPERTS 8
  87. //
  88. // logging
  89. //
  90. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  91. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  92. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  93. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  94. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  95. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  96. //
  97. // helpers
  98. //
  99. static size_t utf8_len(char src) {
  100. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  101. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  102. return lookup[highbits];
  103. }
  104. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  105. std::string result;
  106. for (size_t pos = 0; ; pos += search.length()) {
  107. auto new_pos = s.find(search, pos);
  108. if (new_pos == std::string::npos) {
  109. result += s.substr(pos, s.size() - pos);
  110. break;
  111. }
  112. result += s.substr(pos, new_pos - pos) + replace;
  113. pos = new_pos;
  114. }
  115. s = std::move(result);
  116. }
  117. static bool is_float_close(float a, float b, float abs_tol) {
  118. // Check for non-negative tolerance
  119. if (abs_tol < 0.0) {
  120. throw std::invalid_argument("Tolerance must be non-negative");
  121. }
  122. // Exact equality check
  123. if (a == b) {
  124. return true;
  125. }
  126. // Check for infinities
  127. if (std::isinf(a) || std::isinf(b)) {
  128. return false;
  129. }
  130. // Regular comparison using the provided absolute tolerance
  131. return std::fabs(b - a) <= abs_tol;
  132. }
  133. static void zeros(std::ofstream & file, size_t n) {
  134. char zero = 0;
  135. for (size_t i = 0; i < n; ++i) {
  136. file.write(&zero, 1);
  137. }
  138. }
  139. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  140. static std::string format(const char * fmt, ...) {
  141. va_list ap;
  142. va_list ap2;
  143. va_start(ap, fmt);
  144. va_copy(ap2, ap);
  145. int size = vsnprintf(NULL, 0, fmt, ap);
  146. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  147. std::vector<char> buf(size + 1);
  148. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  149. GGML_ASSERT(size2 == size);
  150. va_end(ap2);
  151. va_end(ap);
  152. return std::string(buf.data(), size);
  153. }
  154. //
  155. // gguf constants (sync with gguf.py)
  156. //
  157. enum llm_arch {
  158. LLM_ARCH_LLAMA,
  159. LLM_ARCH_FALCON,
  160. LLM_ARCH_BAICHUAN,
  161. LLM_ARCH_GPT2,
  162. LLM_ARCH_GPTJ,
  163. LLM_ARCH_GPTNEOX,
  164. LLM_ARCH_MPT,
  165. LLM_ARCH_STARCODER,
  166. LLM_ARCH_PERSIMMON,
  167. LLM_ARCH_REFACT,
  168. LLM_ARCH_BLOOM,
  169. LLM_ARCH_STABLELM,
  170. LLM_ARCH_QWEN,
  171. LLM_ARCH_QWEN2,
  172. LLM_ARCH_PHI2,
  173. LLM_ARCH_PLAMO,
  174. LLM_ARCH_CODESHELL,
  175. LLM_ARCH_UNKNOWN,
  176. };
  177. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  178. { LLM_ARCH_LLAMA, "llama" },
  179. { LLM_ARCH_FALCON, "falcon" },
  180. { LLM_ARCH_GPT2, "gpt2" },
  181. { LLM_ARCH_GPTJ, "gptj" },
  182. { LLM_ARCH_GPTNEOX, "gptneox" },
  183. { LLM_ARCH_MPT, "mpt" },
  184. { LLM_ARCH_BAICHUAN, "baichuan" },
  185. { LLM_ARCH_STARCODER, "starcoder" },
  186. { LLM_ARCH_PERSIMMON, "persimmon" },
  187. { LLM_ARCH_REFACT, "refact" },
  188. { LLM_ARCH_BLOOM, "bloom" },
  189. { LLM_ARCH_STABLELM, "stablelm" },
  190. { LLM_ARCH_QWEN, "qwen" },
  191. { LLM_ARCH_QWEN2, "qwen2" },
  192. { LLM_ARCH_PHI2, "phi2" },
  193. { LLM_ARCH_PLAMO, "plamo" },
  194. { LLM_ARCH_CODESHELL, "codeshell" },
  195. };
  196. enum llm_kv {
  197. LLM_KV_GENERAL_ARCHITECTURE,
  198. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  199. LLM_KV_GENERAL_ALIGNMENT,
  200. LLM_KV_GENERAL_NAME,
  201. LLM_KV_GENERAL_AUTHOR,
  202. LLM_KV_GENERAL_URL,
  203. LLM_KV_GENERAL_DESCRIPTION,
  204. LLM_KV_GENERAL_LICENSE,
  205. LLM_KV_GENERAL_SOURCE_URL,
  206. LLM_KV_GENERAL_SOURCE_HF_REPO,
  207. LLM_KV_CONTEXT_LENGTH,
  208. LLM_KV_EMBEDDING_LENGTH,
  209. LLM_KV_BLOCK_COUNT,
  210. LLM_KV_FEED_FORWARD_LENGTH,
  211. LLM_KV_USE_PARALLEL_RESIDUAL,
  212. LLM_KV_TENSOR_DATA_LAYOUT,
  213. LLM_KV_EXPERT_COUNT,
  214. LLM_KV_EXPERT_USED_COUNT,
  215. LLM_KV_ATTENTION_HEAD_COUNT,
  216. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  217. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  218. LLM_KV_ATTENTION_CLAMP_KQV,
  219. LLM_KV_ATTENTION_KEY_LENGTH,
  220. LLM_KV_ATTENTION_VALUE_LENGTH,
  221. LLM_KV_ATTENTION_LAYERNORM_EPS,
  222. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  223. LLM_KV_ROPE_DIMENSION_COUNT,
  224. LLM_KV_ROPE_FREQ_BASE,
  225. LLM_KV_ROPE_SCALE_LINEAR,
  226. LLM_KV_ROPE_SCALING_TYPE,
  227. LLM_KV_ROPE_SCALING_FACTOR,
  228. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  229. LLM_KV_ROPE_SCALING_FINETUNED,
  230. LLM_KV_TOKENIZER_MODEL,
  231. LLM_KV_TOKENIZER_LIST,
  232. LLM_KV_TOKENIZER_TOKEN_TYPE,
  233. LLM_KV_TOKENIZER_SCORES,
  234. LLM_KV_TOKENIZER_MERGES,
  235. LLM_KV_TOKENIZER_BOS_ID,
  236. LLM_KV_TOKENIZER_EOS_ID,
  237. LLM_KV_TOKENIZER_UNK_ID,
  238. LLM_KV_TOKENIZER_SEP_ID,
  239. LLM_KV_TOKENIZER_PAD_ID,
  240. LLM_KV_TOKENIZER_ADD_BOS,
  241. LLM_KV_TOKENIZER_ADD_EOS,
  242. LLM_KV_TOKENIZER_HF_JSON,
  243. LLM_KV_TOKENIZER_RWKV,
  244. };
  245. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  246. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  247. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  248. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  249. { LLM_KV_GENERAL_NAME, "general.name" },
  250. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  251. { LLM_KV_GENERAL_URL, "general.url" },
  252. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  253. { LLM_KV_GENERAL_LICENSE, "general.license" },
  254. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  255. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  256. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  257. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  258. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  259. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  260. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  261. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  262. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  263. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  264. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  265. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  266. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  267. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  268. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  269. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  270. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  271. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  272. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  273. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  274. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  275. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  276. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  277. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  278. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  279. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  280. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  281. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  282. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  283. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  284. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  285. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  286. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  287. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  288. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  289. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  290. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  291. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  292. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  293. };
  294. struct LLM_KV {
  295. LLM_KV(llm_arch arch) : arch(arch) {}
  296. llm_arch arch;
  297. std::string operator()(llm_kv kv) const {
  298. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  299. }
  300. };
  301. enum llm_tensor {
  302. LLM_TENSOR_TOKEN_EMBD,
  303. LLM_TENSOR_TOKEN_EMBD_NORM,
  304. LLM_TENSOR_POS_EMBD,
  305. LLM_TENSOR_OUTPUT,
  306. LLM_TENSOR_OUTPUT_NORM,
  307. LLM_TENSOR_ROPE_FREQS,
  308. LLM_TENSOR_ATTN_Q,
  309. LLM_TENSOR_ATTN_K,
  310. LLM_TENSOR_ATTN_V,
  311. LLM_TENSOR_ATTN_QKV,
  312. LLM_TENSOR_ATTN_OUT,
  313. LLM_TENSOR_ATTN_NORM,
  314. LLM_TENSOR_ATTN_NORM_2,
  315. LLM_TENSOR_ATTN_ROT_EMBD,
  316. LLM_TENSOR_FFN_GATE_INP,
  317. LLM_TENSOR_FFN_NORM,
  318. LLM_TENSOR_FFN_GATE,
  319. LLM_TENSOR_FFN_DOWN,
  320. LLM_TENSOR_FFN_UP,
  321. LLM_TENSOR_FFN_ACT,
  322. LLM_TENSOR_FFN_DOWN_EXP,
  323. LLM_TENSOR_FFN_GATE_EXP,
  324. LLM_TENSOR_FFN_UP_EXP,
  325. LLM_TENSOR_ATTN_Q_NORM,
  326. LLM_TENSOR_ATTN_K_NORM,
  327. };
  328. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  329. {
  330. LLM_ARCH_LLAMA,
  331. {
  332. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  333. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  334. { LLM_TENSOR_OUTPUT, "output" },
  335. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  336. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  337. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  338. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  339. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  340. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  341. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  342. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  343. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  344. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  345. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  346. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  347. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  348. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  349. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  350. },
  351. },
  352. {
  353. LLM_ARCH_BAICHUAN,
  354. {
  355. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  356. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  357. { LLM_TENSOR_OUTPUT, "output" },
  358. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  359. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  360. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  361. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  362. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  363. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  364. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  365. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  366. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  367. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  368. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  369. },
  370. },
  371. {
  372. LLM_ARCH_FALCON,
  373. {
  374. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  375. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  376. { LLM_TENSOR_OUTPUT, "output" },
  377. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  378. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  379. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  380. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  381. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  382. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  383. },
  384. },
  385. {
  386. LLM_ARCH_GPT2,
  387. {
  388. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  389. { LLM_TENSOR_POS_EMBD, "position_embd" },
  390. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  391. { LLM_TENSOR_OUTPUT, "output" },
  392. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  393. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  394. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  395. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  396. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  397. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  398. },
  399. },
  400. {
  401. LLM_ARCH_GPTJ,
  402. {
  403. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  404. },
  405. },
  406. {
  407. LLM_ARCH_GPTNEOX,
  408. {
  409. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  410. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  411. { LLM_TENSOR_OUTPUT, "output" },
  412. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  413. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  414. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  415. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  416. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  417. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  418. },
  419. },
  420. {
  421. LLM_ARCH_PERSIMMON,
  422. {
  423. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  424. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  425. { LLM_TENSOR_OUTPUT, "output"},
  426. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  427. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  428. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  429. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  430. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  431. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  432. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  433. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  434. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  435. },
  436. },
  437. {
  438. LLM_ARCH_MPT,
  439. {
  440. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  441. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  442. { LLM_TENSOR_OUTPUT, "output" },
  443. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  444. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  445. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  446. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  447. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  448. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  449. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  450. },
  451. },
  452. {
  453. LLM_ARCH_STARCODER,
  454. {
  455. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  456. { LLM_TENSOR_POS_EMBD, "position_embd" },
  457. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  458. { LLM_TENSOR_OUTPUT, "output" },
  459. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  460. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  461. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  462. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  463. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  465. },
  466. },
  467. {
  468. LLM_ARCH_REFACT,
  469. {
  470. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  471. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  472. { LLM_TENSOR_OUTPUT, "output" },
  473. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  474. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  475. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  476. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  477. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  478. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  479. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  480. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  481. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  482. },
  483. },
  484. {
  485. LLM_ARCH_BLOOM,
  486. {
  487. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  488. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  489. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  490. { LLM_TENSOR_OUTPUT, "output" },
  491. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  492. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  493. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  494. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  495. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  496. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  497. },
  498. },
  499. {
  500. LLM_ARCH_STABLELM,
  501. {
  502. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  503. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  504. { LLM_TENSOR_OUTPUT, "output" },
  505. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  506. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  507. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  508. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  509. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  510. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  511. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  512. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  513. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  514. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  515. },
  516. },
  517. {
  518. LLM_ARCH_QWEN,
  519. {
  520. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  521. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  522. { LLM_TENSOR_OUTPUT, "output" },
  523. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  524. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  525. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  526. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  527. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  528. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  529. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  530. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  531. },
  532. },
  533. {
  534. LLM_ARCH_QWEN2,
  535. {
  536. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  537. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  538. { LLM_TENSOR_OUTPUT, "output" },
  539. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  540. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  541. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  542. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  543. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  544. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  545. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  546. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  547. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  548. },
  549. },
  550. {
  551. LLM_ARCH_PHI2,
  552. {
  553. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  554. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  555. { LLM_TENSOR_OUTPUT, "output" },
  556. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  557. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  558. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  559. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  560. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  561. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  562. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  563. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  564. },
  565. },
  566. {
  567. LLM_ARCH_PLAMO,
  568. {
  569. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  570. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  571. { LLM_TENSOR_OUTPUT, "output" },
  572. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  573. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  574. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  575. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  576. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  577. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  578. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  579. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  580. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  581. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  582. },
  583. },
  584. {
  585. LLM_ARCH_CODESHELL,
  586. {
  587. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  588. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  589. { LLM_TENSOR_OUTPUT, "output" },
  590. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  591. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  592. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  593. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  594. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  595. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  596. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  597. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  598. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  599. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  600. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  601. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  602. },
  603. },
  604. {
  605. LLM_ARCH_UNKNOWN,
  606. {
  607. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  608. },
  609. },
  610. };
  611. static llm_arch llm_arch_from_string(const std::string & name) {
  612. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  613. if (kv.second == name) {
  614. return kv.first;
  615. }
  616. }
  617. return LLM_ARCH_UNKNOWN;
  618. }
  619. // helper to handle gguf constants
  620. // usage:
  621. //
  622. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  623. //
  624. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  625. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  626. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  627. //
  628. struct LLM_TN {
  629. LLM_TN(llm_arch arch) : arch(arch) {}
  630. llm_arch arch;
  631. std::string operator()(llm_tensor tensor) const {
  632. return LLM_TENSOR_NAMES[arch].at(tensor);
  633. }
  634. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  635. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  636. }
  637. std::string operator()(llm_tensor tensor, int bid) const {
  638. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  639. }
  640. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  641. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  642. }
  643. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  644. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  645. }
  646. };
  647. //
  648. // gguf helpers
  649. //
  650. static std::map<int8_t, std::string> LLAMA_ROPE_SCALING_TYPES = {
  651. { LLAMA_ROPE_SCALING_NONE, "none" },
  652. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  653. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  654. };
  655. static int8_t llama_rope_scaling_type_from_string(const std::string & name) {
  656. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  657. if (kv.second == name) {
  658. return kv.first;
  659. }
  660. }
  661. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  662. }
  663. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  664. switch (type) {
  665. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  666. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  667. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  668. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  669. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  670. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  671. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  672. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  673. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  674. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  675. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  676. default: return format("unknown type %d", type);
  677. }
  678. }
  679. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  680. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  681. switch (type) {
  682. case GGUF_TYPE_STRING:
  683. return gguf_get_val_str(ctx_gguf, i);
  684. case GGUF_TYPE_ARRAY:
  685. {
  686. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  687. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  688. const void * data = gguf_get_arr_data(ctx_gguf, i);
  689. std::stringstream ss;
  690. ss << "[";
  691. for (int j = 0; j < arr_n; j++) {
  692. if (arr_type == GGUF_TYPE_STRING) {
  693. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  694. // escape quotes
  695. replace_all(val, "\\", "\\\\");
  696. replace_all(val, "\"", "\\\"");
  697. ss << '"' << val << '"';
  698. } else if (arr_type == GGUF_TYPE_ARRAY) {
  699. ss << "???";
  700. } else {
  701. ss << gguf_data_to_str(arr_type, data, j);
  702. }
  703. if (j < arr_n - 1) {
  704. ss << ", ";
  705. }
  706. }
  707. ss << "]";
  708. return ss.str();
  709. }
  710. default:
  711. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  712. }
  713. }
  714. //
  715. // ggml helpers
  716. //
  717. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  718. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  719. if (plan.work_size > 0) {
  720. buf.resize(plan.work_size);
  721. plan.work_data = buf.data();
  722. }
  723. ggml_graph_compute(graph, &plan);
  724. }
  725. //
  726. // llama helpers
  727. //
  728. #if defined(_WIN32)
  729. static std::string llama_format_win_err(DWORD err) {
  730. LPSTR buf;
  731. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  732. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  733. if (!size) {
  734. return "FormatMessageA failed";
  735. }
  736. std::string ret(buf, size);
  737. LocalFree(buf);
  738. return ret;
  739. }
  740. #endif
  741. template <typename T>
  742. struct no_init {
  743. T value;
  744. no_init() { /* do nothing */ }
  745. };
  746. struct llama_file {
  747. // use FILE * so we don't have to re-open the file to mmap
  748. FILE * fp;
  749. size_t size;
  750. llama_file(const char * fname, const char * mode) {
  751. fp = std::fopen(fname, mode);
  752. if (fp == NULL) {
  753. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  754. }
  755. seek(0, SEEK_END);
  756. size = tell();
  757. seek(0, SEEK_SET);
  758. }
  759. size_t tell() const {
  760. #ifdef _WIN32
  761. __int64 ret = _ftelli64(fp);
  762. #else
  763. long ret = std::ftell(fp);
  764. #endif
  765. GGML_ASSERT(ret != -1); // this really shouldn't fail
  766. return (size_t) ret;
  767. }
  768. void seek(size_t offset, int whence) const {
  769. #ifdef _WIN32
  770. int ret = _fseeki64(fp, (__int64) offset, whence);
  771. #else
  772. int ret = std::fseek(fp, (long) offset, whence);
  773. #endif
  774. GGML_ASSERT(ret == 0); // same
  775. }
  776. void read_raw(void * ptr, size_t len) const {
  777. if (len == 0) {
  778. return;
  779. }
  780. errno = 0;
  781. std::size_t ret = std::fread(ptr, len, 1, fp);
  782. if (ferror(fp)) {
  783. throw std::runtime_error(format("read error: %s", strerror(errno)));
  784. }
  785. if (ret != 1) {
  786. throw std::runtime_error("unexpectedly reached end of file");
  787. }
  788. }
  789. uint32_t read_u32() const {
  790. uint32_t ret;
  791. read_raw(&ret, sizeof(ret));
  792. return ret;
  793. }
  794. void write_raw(const void * ptr, size_t len) const {
  795. if (len == 0) {
  796. return;
  797. }
  798. errno = 0;
  799. size_t ret = std::fwrite(ptr, len, 1, fp);
  800. if (ret != 1) {
  801. throw std::runtime_error(format("write error: %s", strerror(errno)));
  802. }
  803. }
  804. void write_u32(std::uint32_t val) const {
  805. write_raw(&val, sizeof(val));
  806. }
  807. ~llama_file() {
  808. if (fp) {
  809. std::fclose(fp);
  810. }
  811. }
  812. };
  813. struct llama_mmap {
  814. void * addr;
  815. size_t size;
  816. llama_mmap(const llama_mmap &) = delete;
  817. #ifdef _POSIX_MAPPED_FILES
  818. static constexpr bool SUPPORTED = true;
  819. // list of mapped fragments (first_offset, last_offset)
  820. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  821. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  822. size = file->size;
  823. int fd = fileno(file->fp);
  824. int flags = MAP_SHARED;
  825. // prefetch/readahead impairs performance on NUMA systems
  826. if (numa) { prefetch = 0; }
  827. #ifdef __linux__
  828. // advise the kernel to read the file sequentially (increases readahead)
  829. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  830. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  831. strerror(errno));
  832. }
  833. if (prefetch) { flags |= MAP_POPULATE; }
  834. #endif
  835. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  836. if (addr == MAP_FAILED) { // NOLINT
  837. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  838. }
  839. if (prefetch > 0) {
  840. // advise the kernel to preload the mapped memory
  841. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  842. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  843. strerror(errno));
  844. }
  845. }
  846. if (numa) {
  847. // advise the kernel not to use readahead
  848. // (because the next page might not belong on the same node)
  849. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  850. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  851. strerror(errno));
  852. }
  853. }
  854. // initialize list of mapped_fragments
  855. mapped_fragments.emplace_back(0, file->size);
  856. }
  857. static void align_range(size_t * first, size_t * last, size_t page_size) {
  858. // align first to the next page
  859. size_t offset_in_page = *first & (page_size - 1);
  860. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  861. *first += offset_to_page;
  862. // align last to the previous page
  863. *last = *last & ~(page_size - 1);
  864. if (*last <= *first) {
  865. *last = *first;
  866. }
  867. }
  868. // partially unmap the file in the range [first, last)
  869. void unmap_fragment(size_t first, size_t last) {
  870. // note: this function must not be called multiple times with overlapping ranges
  871. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  872. int page_size = sysconf(_SC_PAGESIZE);
  873. align_range(&first, &last, page_size);
  874. size_t len = last - first;
  875. if (len == 0) {
  876. return;
  877. }
  878. GGML_ASSERT(first % page_size == 0);
  879. GGML_ASSERT(last % page_size == 0);
  880. GGML_ASSERT(last > first);
  881. void * next_page_start = (uint8_t *) addr + first;
  882. // unmap the range
  883. if (munmap(next_page_start, len)) {
  884. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  885. }
  886. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  887. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  888. for (const auto & frag : mapped_fragments) {
  889. if (frag.first < first && frag.second > last) {
  890. // the range is in the middle of the fragment, split it
  891. new_mapped_fragments.emplace_back(frag.first, first);
  892. new_mapped_fragments.emplace_back(last, frag.second);
  893. } else if (frag.first < first && frag.second > first) {
  894. // the range starts in the middle of the fragment
  895. new_mapped_fragments.emplace_back(frag.first, first);
  896. } else if (frag.first < last && frag.second > last) {
  897. // the range ends in the middle of the fragment
  898. new_mapped_fragments.emplace_back(last, frag.second);
  899. } else if (frag.first >= first && frag.second <= last) {
  900. // the range covers the entire fragment
  901. } else {
  902. // the range is outside the fragment
  903. new_mapped_fragments.push_back(frag);
  904. }
  905. }
  906. mapped_fragments = std::move(new_mapped_fragments);
  907. }
  908. ~llama_mmap() {
  909. for (const auto & frag : mapped_fragments) {
  910. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  911. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  912. }
  913. }
  914. }
  915. #elif defined(_WIN32)
  916. static constexpr bool SUPPORTED = true;
  917. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  918. GGML_UNUSED(numa);
  919. size = file->size;
  920. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  921. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  922. if (hMapping == NULL) {
  923. DWORD error = GetLastError();
  924. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  925. }
  926. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  927. DWORD error = GetLastError();
  928. CloseHandle(hMapping);
  929. if (addr == NULL) {
  930. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  931. }
  932. if (prefetch > 0) {
  933. #if _WIN32_WINNT >= 0x602
  934. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  935. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  936. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  937. // may fail on pre-Windows 8 systems
  938. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  939. if (pPrefetchVirtualMemory) {
  940. // advise the kernel to preload the mapped memory
  941. WIN32_MEMORY_RANGE_ENTRY range;
  942. range.VirtualAddress = addr;
  943. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  944. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  945. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  946. llama_format_win_err(GetLastError()).c_str());
  947. }
  948. }
  949. #else
  950. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  951. #endif
  952. }
  953. }
  954. void unmap_fragment(size_t first, size_t last) {
  955. // not supported
  956. GGML_UNUSED(first);
  957. GGML_UNUSED(last);
  958. }
  959. ~llama_mmap() {
  960. if (!UnmapViewOfFile(addr)) {
  961. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  962. llama_format_win_err(GetLastError()).c_str());
  963. }
  964. }
  965. #else
  966. static constexpr bool SUPPORTED = false;
  967. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  968. GGML_UNUSED(file);
  969. GGML_UNUSED(prefetch);
  970. GGML_UNUSED(numa);
  971. throw std::runtime_error("mmap not supported");
  972. }
  973. void unmap_fragment(size_t first, size_t last) {
  974. GGML_UNUSED(first);
  975. GGML_UNUSED(last);
  976. throw std::runtime_error("mmap not supported");
  977. }
  978. #endif
  979. };
  980. // Represents some region of memory being locked using mlock or VirtualLock;
  981. // will automatically unlock on destruction.
  982. struct llama_mlock {
  983. void * addr = NULL;
  984. size_t size = 0;
  985. bool failed_already = false;
  986. llama_mlock() {}
  987. llama_mlock(const llama_mlock &) = delete;
  988. ~llama_mlock() {
  989. if (size) {
  990. raw_unlock(addr, size);
  991. }
  992. }
  993. void init(void * ptr) {
  994. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  995. addr = ptr;
  996. }
  997. void grow_to(size_t target_size) {
  998. GGML_ASSERT(addr);
  999. if (failed_already) {
  1000. return;
  1001. }
  1002. size_t granularity = lock_granularity();
  1003. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1004. if (target_size > size) {
  1005. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1006. size = target_size;
  1007. } else {
  1008. failed_already = true;
  1009. }
  1010. }
  1011. }
  1012. #ifdef _POSIX_MEMLOCK_RANGE
  1013. static constexpr bool SUPPORTED = true;
  1014. static size_t lock_granularity() {
  1015. return (size_t) sysconf(_SC_PAGESIZE);
  1016. }
  1017. #ifdef __APPLE__
  1018. #define MLOCK_SUGGESTION \
  1019. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1020. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  1021. #else
  1022. #define MLOCK_SUGGESTION \
  1023. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  1024. #endif
  1025. bool raw_lock(const void * addr, size_t size) const {
  1026. if (!mlock(addr, size)) {
  1027. return true;
  1028. }
  1029. char* errmsg = std::strerror(errno);
  1030. bool suggest = (errno == ENOMEM);
  1031. // Check if the resource limit is fine after all
  1032. struct rlimit lock_limit;
  1033. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1034. suggest = false;
  1035. }
  1036. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1037. suggest = false;
  1038. }
  1039. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1040. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1041. return false;
  1042. }
  1043. #undef MLOCK_SUGGESTION
  1044. static void raw_unlock(void * addr, size_t size) {
  1045. if (munlock(addr, size)) {
  1046. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1047. }
  1048. }
  1049. #elif defined(_WIN32)
  1050. static constexpr bool SUPPORTED = true;
  1051. static size_t lock_granularity() {
  1052. SYSTEM_INFO si;
  1053. GetSystemInfo(&si);
  1054. return (size_t) si.dwPageSize;
  1055. }
  1056. bool raw_lock(void * ptr, size_t len) const {
  1057. for (int tries = 1; ; tries++) {
  1058. if (VirtualLock(ptr, len)) {
  1059. return true;
  1060. }
  1061. if (tries == 2) {
  1062. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1063. len, size, llama_format_win_err(GetLastError()).c_str());
  1064. return false;
  1065. }
  1066. // It failed but this was only the first try; increase the working
  1067. // set size and try again.
  1068. SIZE_T min_ws_size, max_ws_size;
  1069. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1070. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1071. llama_format_win_err(GetLastError()).c_str());
  1072. return false;
  1073. }
  1074. // Per MSDN: "The maximum number of pages that a process can lock
  1075. // is equal to the number of pages in its minimum working set minus
  1076. // a small overhead."
  1077. // Hopefully a megabyte is enough overhead:
  1078. size_t increment = len + 1048576;
  1079. // The minimum must be <= the maximum, so we need to increase both:
  1080. min_ws_size += increment;
  1081. max_ws_size += increment;
  1082. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1083. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1084. llama_format_win_err(GetLastError()).c_str());
  1085. return false;
  1086. }
  1087. }
  1088. }
  1089. static void raw_unlock(void * ptr, size_t len) {
  1090. if (!VirtualUnlock(ptr, len)) {
  1091. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1092. llama_format_win_err(GetLastError()).c_str());
  1093. }
  1094. }
  1095. #else
  1096. static constexpr bool SUPPORTED = false;
  1097. static size_t lock_granularity() {
  1098. return (size_t) 65536;
  1099. }
  1100. bool raw_lock(const void * addr, size_t len) const {
  1101. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1102. return false;
  1103. }
  1104. static void raw_unlock(const void * addr, size_t len) {}
  1105. #endif
  1106. };
  1107. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1108. std::vector<char> result(8, 0);
  1109. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1110. if (n_tokens < 0) {
  1111. result.resize(-n_tokens);
  1112. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1113. GGML_ASSERT(check == -n_tokens);
  1114. }
  1115. else {
  1116. result.resize(n_tokens);
  1117. }
  1118. return std::string(result.data(), result.size());
  1119. }
  1120. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1121. ggml_backend_buffer_type_t buft = nullptr;
  1122. #if defined(GGML_USE_CUBLAS)
  1123. // host buffers should only be used when data is expected to be copied to/from the GPU
  1124. if (host_buffer) {
  1125. buft = ggml_backend_cuda_host_buffer_type();
  1126. }
  1127. #elif defined(GGML_USE_CPU_HBM)
  1128. buft = ggml_backend_cpu_hbm_buffer_type();
  1129. #endif
  1130. if (buft == nullptr) {
  1131. buft = ggml_backend_cpu_buffer_type();
  1132. }
  1133. return buft;
  1134. GGML_UNUSED(host_buffer);
  1135. }
  1136. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1137. ggml_backend_buffer_type_t buft = nullptr;
  1138. #ifdef GGML_USE_METAL
  1139. buft = ggml_backend_metal_buffer_type();
  1140. #elif defined(GGML_USE_CUBLAS)
  1141. buft = ggml_backend_cuda_buffer_type(gpu);
  1142. #elif defined(GGML_USE_CLBLAST)
  1143. buft = ggml_backend_opencl_buffer_type();
  1144. #endif
  1145. if (buft == nullptr) {
  1146. buft = llama_default_buffer_type_cpu(true);
  1147. }
  1148. return buft;
  1149. GGML_UNUSED(gpu);
  1150. }
  1151. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1152. ggml_backend_buffer_type_t buft = nullptr;
  1153. #ifdef GGML_USE_CUBLAS
  1154. if (ggml_backend_cuda_get_device_count() > 1) {
  1155. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1156. }
  1157. #endif
  1158. if (buft == nullptr) {
  1159. buft = llama_default_buffer_type_offload(fallback_gpu);
  1160. }
  1161. return buft;
  1162. GGML_UNUSED(tensor_split);
  1163. }
  1164. //
  1165. // globals
  1166. //
  1167. struct llama_state {
  1168. llama_state() {
  1169. #ifdef GGML_USE_METAL
  1170. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1171. #endif
  1172. }
  1173. // We save the log callback globally
  1174. ggml_log_callback log_callback = llama_log_callback_default;
  1175. void * log_callback_user_data = nullptr;
  1176. };
  1177. static llama_state g_state;
  1178. // available llama models
  1179. enum e_model {
  1180. MODEL_UNKNOWN,
  1181. MODEL_1B,
  1182. MODEL_3B,
  1183. MODEL_7B,
  1184. MODEL_8B,
  1185. MODEL_13B,
  1186. MODEL_15B,
  1187. MODEL_30B,
  1188. MODEL_34B,
  1189. MODEL_40B,
  1190. MODEL_65B,
  1191. MODEL_70B,
  1192. MODEL_SMALL,
  1193. MODEL_MEDIUM,
  1194. MODEL_LARGE,
  1195. MODEL_XL,
  1196. };
  1197. static const size_t kiB = 1024;
  1198. static const size_t MiB = 1024*kiB;
  1199. static const size_t GiB = 1024*MiB;
  1200. struct llama_hparams {
  1201. bool vocab_only;
  1202. uint32_t n_vocab;
  1203. uint32_t n_ctx_train; // context size the model was trained on
  1204. uint32_t n_embd;
  1205. uint32_t n_head;
  1206. uint32_t n_head_kv;
  1207. uint32_t n_layer;
  1208. uint32_t n_rot;
  1209. 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
  1210. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1211. uint32_t n_ff;
  1212. uint32_t n_expert = 0;
  1213. uint32_t n_expert_used = 0;
  1214. float f_norm_eps;
  1215. float f_norm_rms_eps;
  1216. float rope_freq_base_train;
  1217. float rope_freq_scale_train;
  1218. uint32_t n_yarn_orig_ctx;
  1219. int8_t rope_scaling_type_train : 3;
  1220. bool rope_finetuned : 1;
  1221. float f_clamp_kqv;
  1222. float f_max_alibi_bias;
  1223. bool operator!=(const llama_hparams & other) const {
  1224. if (this->vocab_only != other.vocab_only) return true;
  1225. if (this->n_vocab != other.n_vocab) return true;
  1226. if (this->n_ctx_train != other.n_ctx_train) return true;
  1227. if (this->n_embd != other.n_embd) return true;
  1228. if (this->n_head != other.n_head) return true;
  1229. if (this->n_head_kv != other.n_head_kv) return true;
  1230. if (this->n_layer != other.n_layer) return true;
  1231. if (this->n_rot != other.n_rot) return true;
  1232. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1233. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1234. if (this->n_ff != other.n_ff) return true;
  1235. if (this->n_expert != other.n_expert) return true;
  1236. if (this->n_expert_used != other.n_expert_used) return true;
  1237. if (this->rope_finetuned != other.rope_finetuned) return true;
  1238. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1239. const float EPSILON = 1e-9f;
  1240. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1241. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1242. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1243. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1244. return false;
  1245. }
  1246. uint32_t n_gqa() const {
  1247. return n_head/n_head_kv;
  1248. }
  1249. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1250. return n_embd_head_k * n_head_kv;
  1251. }
  1252. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1253. return n_embd_head_v * n_head_kv;
  1254. }
  1255. };
  1256. struct llama_cparams {
  1257. uint32_t n_ctx; // context size used during inference
  1258. uint32_t n_batch;
  1259. uint32_t n_threads; // number of threads to use for generation
  1260. uint32_t n_threads_batch; // number of threads to use for batch processing
  1261. float rope_freq_base;
  1262. float rope_freq_scale;
  1263. uint32_t n_yarn_orig_ctx;
  1264. // These hyperparameters are not exposed in GGUF, because all
  1265. // existing YaRN models use the same values for them.
  1266. float yarn_ext_factor;
  1267. float yarn_attn_factor;
  1268. float yarn_beta_fast;
  1269. float yarn_beta_slow;
  1270. bool mul_mat_q;
  1271. bool offload_kqv;
  1272. ggml_backend_sched_eval_callback cb_eval;
  1273. void * cb_eval_user_data;
  1274. };
  1275. struct llama_layer {
  1276. // normalization
  1277. struct ggml_tensor * attn_norm;
  1278. struct ggml_tensor * attn_norm_b;
  1279. struct ggml_tensor * attn_norm_2;
  1280. struct ggml_tensor * attn_norm_2_b;
  1281. struct ggml_tensor * attn_q_norm;
  1282. struct ggml_tensor * attn_q_norm_b;
  1283. struct ggml_tensor * attn_k_norm;
  1284. struct ggml_tensor * attn_k_norm_b;
  1285. // attention
  1286. struct ggml_tensor * wq;
  1287. struct ggml_tensor * wk;
  1288. struct ggml_tensor * wv;
  1289. struct ggml_tensor * wo;
  1290. struct ggml_tensor * wqkv;
  1291. // attention bias
  1292. struct ggml_tensor * bq;
  1293. struct ggml_tensor * bk;
  1294. struct ggml_tensor * bv;
  1295. struct ggml_tensor * bo;
  1296. struct ggml_tensor * bqkv;
  1297. // normalization
  1298. struct ggml_tensor * ffn_norm;
  1299. struct ggml_tensor * ffn_norm_b;
  1300. // ff
  1301. struct ggml_tensor * ffn_gate; // w1
  1302. struct ggml_tensor * ffn_down; // w2
  1303. struct ggml_tensor * ffn_up; // w3
  1304. // ff MoE
  1305. struct ggml_tensor * ffn_gate_inp;
  1306. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1307. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1308. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1309. // ff bias
  1310. struct ggml_tensor * ffn_down_b; // b2
  1311. struct ggml_tensor * ffn_up_b; // b3
  1312. struct ggml_tensor * ffn_act;
  1313. };
  1314. struct llama_kv_cell {
  1315. llama_pos pos = -1;
  1316. llama_pos delta = 0;
  1317. std::set<llama_seq_id> seq_id;
  1318. bool has_seq_id(const llama_seq_id & id) const {
  1319. return seq_id.find(id) != seq_id.end();
  1320. }
  1321. };
  1322. // ring-buffer of cached KV data
  1323. struct llama_kv_cache {
  1324. bool has_shift = false;
  1325. // Note: The value of head isn't only used to optimize searching
  1326. // for a free KV slot. llama_decode_internal also uses it, so it
  1327. // cannot be freely changed after a slot has been allocated.
  1328. uint32_t head = 0;
  1329. uint32_t size = 0;
  1330. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1331. // computed before each graph build
  1332. uint32_t n = 0;
  1333. std::vector<llama_kv_cell> cells;
  1334. std::vector<struct ggml_tensor *> k_l; // per layer
  1335. std::vector<struct ggml_tensor *> v_l;
  1336. std::vector<struct ggml_context *> ctxs;
  1337. std::vector<ggml_backend_buffer_t> bufs;
  1338. size_t total_size() const {
  1339. size_t size = 0;
  1340. for (ggml_backend_buffer_t buf : bufs) {
  1341. size += ggml_backend_buffer_get_size(buf);
  1342. }
  1343. return size;
  1344. }
  1345. ~llama_kv_cache() {
  1346. for (struct ggml_context * ctx : ctxs) {
  1347. ggml_free(ctx);
  1348. }
  1349. for (ggml_backend_buffer_t buf : bufs) {
  1350. ggml_backend_buffer_free(buf);
  1351. }
  1352. }
  1353. };
  1354. struct llama_vocab {
  1355. using id = int32_t;
  1356. using token = std::string;
  1357. using ttype = llama_token_type;
  1358. struct token_data {
  1359. token text;
  1360. float score;
  1361. ttype type;
  1362. };
  1363. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1364. std::unordered_map<token, id> token_to_id;
  1365. std::vector<token_data> id_to_token;
  1366. std::unordered_map<token, id> special_tokens_cache;
  1367. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1368. // default LLaMA special tokens
  1369. id special_bos_id = 1;
  1370. id special_eos_id = 2;
  1371. id special_unk_id = 0;
  1372. id special_sep_id = -1;
  1373. id special_pad_id = -1;
  1374. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1375. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1376. id linefeed_id = 13;
  1377. id special_prefix_id = 32007;
  1378. id special_middle_id = 32009;
  1379. id special_suffix_id = 32008;
  1380. id special_eot_id = 32010;
  1381. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1382. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1383. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1384. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1385. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1386. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1387. if (it == bpe_ranks.end()) {
  1388. return -1;
  1389. }
  1390. return it->second;
  1391. }
  1392. };
  1393. struct llama_model {
  1394. e_model type = MODEL_UNKNOWN;
  1395. llm_arch arch = LLM_ARCH_UNKNOWN;
  1396. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1397. std::string name = "n/a";
  1398. llama_hparams hparams = {};
  1399. llama_vocab vocab;
  1400. struct ggml_tensor * tok_embd;
  1401. struct ggml_tensor * pos_embd;
  1402. struct ggml_tensor * tok_norm;
  1403. struct ggml_tensor * tok_norm_b;
  1404. struct ggml_tensor * output_norm;
  1405. struct ggml_tensor * output_norm_b;
  1406. struct ggml_tensor * output;
  1407. struct ggml_tensor * output_b;
  1408. std::vector<llama_layer> layers;
  1409. llama_split_mode split_mode;
  1410. int main_gpu;
  1411. int n_gpu_layers;
  1412. // gguf metadata
  1413. std::unordered_map<std::string, std::string> gguf_kv;
  1414. // layer -> buffer type mapping
  1415. struct layer_buft {
  1416. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1417. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1418. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1419. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1420. ggml_backend_buffer_type_t buft; // everything else
  1421. };
  1422. layer_buft buft_input;
  1423. layer_buft buft_output;
  1424. std::vector<layer_buft> buft_layer;
  1425. // contexts where the model tensors metadata is stored
  1426. std::vector<struct ggml_context *> ctxs;
  1427. // the model memory buffers for the tensor data
  1428. std::vector<ggml_backend_buffer_t> bufs;
  1429. // model memory mapped file
  1430. std::unique_ptr<llama_mmap> mapping;
  1431. // objects representing data potentially being locked in memory
  1432. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1433. llama_mlock mlock_mmap;
  1434. // for quantize-stats only
  1435. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1436. int64_t t_load_us = 0;
  1437. int64_t t_start_us = 0;
  1438. ~llama_model() {
  1439. for (struct ggml_context * ctx : ctxs) {
  1440. ggml_free(ctx);
  1441. }
  1442. for (ggml_backend_buffer_t buf : bufs) {
  1443. ggml_backend_buffer_free(buf);
  1444. }
  1445. }
  1446. };
  1447. struct llama_context {
  1448. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1449. ~llama_context() {
  1450. ggml_backend_sched_free(sched);
  1451. for (ggml_backend_t backend : backends) {
  1452. ggml_backend_free(backend);
  1453. }
  1454. }
  1455. llama_cparams cparams;
  1456. std::vector<ggml_backend_t> backends;
  1457. #ifdef GGML_USE_METAL
  1458. ggml_backend_t backend_metal = nullptr;
  1459. #endif
  1460. ggml_backend_t backend_cpu = nullptr;
  1461. const llama_model & model;
  1462. // key + value cache for the self attention
  1463. struct llama_kv_cache kv_self;
  1464. std::mt19937 rng;
  1465. bool has_evaluated_once = false;
  1466. int64_t t_start_us;
  1467. int64_t t_load_us;
  1468. int64_t t_sample_us = 0;
  1469. int64_t t_p_eval_us = 0;
  1470. int64_t t_eval_us = 0;
  1471. int32_t n_sample = 0; // number of tokens sampled
  1472. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1473. int32_t n_eval = 0; // number of eval calls
  1474. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1475. std::vector<float> logits;
  1476. #ifndef NDEBUG
  1477. // guard against access to unset logits
  1478. std::vector<bool> logits_valid;
  1479. #endif
  1480. bool logits_all = false;
  1481. // input embedding (1-dimensional array: [n_embd])
  1482. std::vector<float> embedding;
  1483. // memory buffers used to evaluate the model
  1484. std::vector<uint8_t> buf_compute_meta;
  1485. ggml_backend_sched_t sched = nullptr;
  1486. // allocator for the input tensors
  1487. ggml_tallocr * alloc = nullptr;
  1488. // temporary buffer for copying data to/from the backend
  1489. std::vector<no_init<uint8_t>> buf_copy;
  1490. #ifdef GGML_USE_MPI
  1491. ggml_mpi_context * ctx_mpi = NULL;
  1492. #endif
  1493. };
  1494. //
  1495. // kv cache helpers
  1496. //
  1497. static bool llama_kv_cache_init(
  1498. struct llama_kv_cache & cache,
  1499. const llama_model & model,
  1500. ggml_type ktype,
  1501. ggml_type vtype,
  1502. uint32_t n_ctx,
  1503. bool offload) {
  1504. const struct llama_hparams & hparams = model.hparams;
  1505. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1506. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1507. const int64_t n_layer = hparams.n_layer;
  1508. cache.has_shift = false;
  1509. cache.head = 0;
  1510. cache.size = n_ctx;
  1511. cache.used = 0;
  1512. cache.cells.clear();
  1513. cache.cells.resize(n_ctx);
  1514. #ifdef GGML_USE_CLBLAST
  1515. offload = false;
  1516. #endif
  1517. // count used buffer types
  1518. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1519. if (offload) {
  1520. for (int64_t i = 0; i < n_layer; ++i) {
  1521. buft_layer_count[model.buft_layer[i].buft]++;
  1522. }
  1523. } else {
  1524. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1525. }
  1526. // create a context for each buffer type
  1527. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1528. for (auto & it : buft_layer_count) {
  1529. int n_layers = it.second;
  1530. struct ggml_init_params params = {
  1531. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1532. /*.mem_buffer =*/ NULL,
  1533. /*.no_alloc =*/ true,
  1534. };
  1535. ggml_context * ctx = ggml_init(params);
  1536. if (!ctx) {
  1537. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1538. return false;
  1539. }
  1540. ctx_map[it.first] = ctx;
  1541. cache.ctxs.push_back(ctx);
  1542. }
  1543. cache.k_l.reserve(n_layer);
  1544. cache.v_l.reserve(n_layer);
  1545. for (int i = 0; i < (int) n_layer; i++) {
  1546. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1547. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1548. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1549. ggml_format_name(k, "cache_k_l%d", i);
  1550. ggml_format_name(v, "cache_v_l%d", i);
  1551. cache.k_l.push_back(k);
  1552. cache.v_l.push_back(v);
  1553. }
  1554. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1555. for (auto it : ctx_map) {
  1556. ggml_backend_buffer_type_t buft = it.first;
  1557. ggml_context * ctx = it.second;
  1558. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1559. if (!buf) {
  1560. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1561. return false;
  1562. }
  1563. ggml_backend_buffer_clear(buf, 0);
  1564. 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);
  1565. cache.bufs.push_back(buf);
  1566. }
  1567. return true;
  1568. }
  1569. // find an empty slot of size "n_tokens" in the cache
  1570. // updates the cache head
  1571. // Note: On success, it's important that cache.head points
  1572. // to the first cell of the slot.
  1573. static bool llama_kv_cache_find_slot(
  1574. struct llama_kv_cache & cache,
  1575. const struct llama_batch & batch) {
  1576. const uint32_t n_ctx = cache.size;
  1577. const uint32_t n_tokens = batch.n_tokens;
  1578. if (n_tokens > n_ctx) {
  1579. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1580. return false;
  1581. }
  1582. uint32_t n_tested = 0;
  1583. while (true) {
  1584. if (cache.head + n_tokens > n_ctx) {
  1585. n_tested += n_ctx - cache.head;
  1586. cache.head = 0;
  1587. continue;
  1588. }
  1589. bool found = true;
  1590. for (uint32_t i = 0; i < n_tokens; i++) {
  1591. if (cache.cells[cache.head + i].pos >= 0) {
  1592. found = false;
  1593. cache.head += i + 1;
  1594. n_tested += i + 1;
  1595. break;
  1596. }
  1597. }
  1598. if (found) {
  1599. break;
  1600. }
  1601. if (n_tested >= n_ctx) {
  1602. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1603. return false;
  1604. }
  1605. }
  1606. for (uint32_t i = 0; i < n_tokens; i++) {
  1607. cache.cells[cache.head + i].pos = batch.pos[i];
  1608. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1609. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1610. }
  1611. }
  1612. cache.used += n_tokens;
  1613. return true;
  1614. }
  1615. // find how many cells are currently in use
  1616. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1617. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1618. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1619. return i + 1;
  1620. }
  1621. }
  1622. return 0;
  1623. }
  1624. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1625. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1626. cache.cells[i].pos = -1;
  1627. cache.cells[i].seq_id.clear();
  1628. }
  1629. cache.head = 0;
  1630. cache.used = 0;
  1631. }
  1632. static void llama_kv_cache_seq_rm(
  1633. struct llama_kv_cache & cache,
  1634. llama_seq_id seq_id,
  1635. llama_pos p0,
  1636. llama_pos p1) {
  1637. uint32_t new_head = cache.size;
  1638. if (p0 < 0) p0 = 0;
  1639. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1640. for (uint32_t i = 0; i < cache.size; ++i) {
  1641. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1642. if (seq_id < 0) {
  1643. cache.cells[i].seq_id.clear();
  1644. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1645. cache.cells[i].seq_id.erase(seq_id);
  1646. } else {
  1647. continue;
  1648. }
  1649. if (cache.cells[i].seq_id.empty()) {
  1650. // keep count of the number of used cells
  1651. if (cache.cells[i].pos >= 0) cache.used--;
  1652. cache.cells[i].pos = -1;
  1653. if (new_head == cache.size) new_head = i;
  1654. }
  1655. }
  1656. }
  1657. // If we freed up a slot, set head to it so searching can start there.
  1658. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1659. }
  1660. static void llama_kv_cache_seq_cp(
  1661. struct llama_kv_cache & cache,
  1662. llama_seq_id seq_id_src,
  1663. llama_seq_id seq_id_dst,
  1664. llama_pos p0,
  1665. llama_pos p1) {
  1666. if (p0 < 0) p0 = 0;
  1667. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1668. cache.head = 0;
  1669. for (uint32_t i = 0; i < cache.size; ++i) {
  1670. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1671. cache.cells[i].seq_id.insert(seq_id_dst);
  1672. }
  1673. }
  1674. }
  1675. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1676. uint32_t new_head = cache.size;
  1677. for (uint32_t i = 0; i < cache.size; ++i) {
  1678. if (!cache.cells[i].has_seq_id(seq_id)) {
  1679. if (cache.cells[i].pos >= 0) cache.used--;
  1680. cache.cells[i].pos = -1;
  1681. cache.cells[i].seq_id.clear();
  1682. if (new_head == cache.size) new_head = i;
  1683. } else {
  1684. cache.cells[i].seq_id.clear();
  1685. cache.cells[i].seq_id.insert(seq_id);
  1686. }
  1687. }
  1688. // If we freed up a slot, set head to it so searching can start there.
  1689. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1690. }
  1691. static void llama_kv_cache_seq_shift(
  1692. struct llama_kv_cache & cache,
  1693. llama_seq_id seq_id,
  1694. llama_pos p0,
  1695. llama_pos p1,
  1696. llama_pos delta) {
  1697. uint32_t new_head = cache.size;
  1698. if (p0 < 0) p0 = 0;
  1699. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1700. for (uint32_t i = 0; i < cache.size; ++i) {
  1701. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1702. cache.has_shift = true;
  1703. cache.cells[i].pos += delta;
  1704. cache.cells[i].delta += delta;
  1705. if (cache.cells[i].pos < 0) {
  1706. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1707. cache.cells[i].pos = -1;
  1708. cache.cells[i].seq_id.clear();
  1709. if (new_head == cache.size) new_head = i;
  1710. }
  1711. }
  1712. }
  1713. // If we freed up a slot, set head to it so searching can start there.
  1714. // Otherwise we just start the next search from the beginning.
  1715. cache.head = new_head != cache.size ? new_head : 0;
  1716. }
  1717. static void llama_kv_cache_seq_div(
  1718. struct llama_kv_cache & cache,
  1719. llama_seq_id seq_id,
  1720. llama_pos p0,
  1721. llama_pos p1,
  1722. int d) {
  1723. if (p0 < 0) p0 = 0;
  1724. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1725. for (uint32_t i = 0; i < cache.size; ++i) {
  1726. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1727. cache.has_shift = true;
  1728. {
  1729. llama_pos p_old = cache.cells[i].pos;
  1730. cache.cells[i].pos /= d;
  1731. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1732. }
  1733. }
  1734. }
  1735. }
  1736. //
  1737. // model loading and saving
  1738. //
  1739. enum llama_fver {
  1740. GGUF_FILE_VERSION_V1 = 1,
  1741. GGUF_FILE_VERSION_V2 = 2,
  1742. GGUF_FILE_VERSION_V3 = 3,
  1743. };
  1744. static const char * llama_file_version_name(llama_fver version) {
  1745. switch (version) {
  1746. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1747. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1748. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1749. }
  1750. return "unknown";
  1751. }
  1752. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1753. char buf[256];
  1754. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1755. for (size_t i = 1; i < ne.size(); i++) {
  1756. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1757. }
  1758. return buf;
  1759. }
  1760. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1761. char buf[256];
  1762. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1763. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1764. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1765. }
  1766. return buf;
  1767. }
  1768. namespace GGUFMeta {
  1769. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1770. struct GKV_Base_Type {
  1771. static constexpr gguf_type gt = gt_;
  1772. static T getter(const gguf_context * ctx, const int kid) {
  1773. return gfun(ctx, kid);
  1774. }
  1775. };
  1776. template<typename T> struct GKV_Base;
  1777. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1778. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1779. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1780. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1781. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1782. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1783. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1784. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1785. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1786. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1787. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1788. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1789. template<> struct GKV_Base<std::string> {
  1790. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1791. static std::string getter(const gguf_context * ctx, const int kid) {
  1792. return gguf_get_val_str(ctx, kid);
  1793. }
  1794. };
  1795. struct ArrayInfo{
  1796. const gguf_type gt;
  1797. const size_t length;
  1798. const void * data;
  1799. };
  1800. template<> struct GKV_Base<ArrayInfo> {
  1801. public:
  1802. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1803. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1804. return ArrayInfo {
  1805. gguf_get_arr_type(ctx, k),
  1806. size_t(gguf_get_arr_n(ctx, k)),
  1807. gguf_get_arr_data(ctx, k),
  1808. };
  1809. }
  1810. };
  1811. template<typename T>
  1812. class GKV: public GKV_Base<T> {
  1813. GKV() = delete;
  1814. public:
  1815. static T get_kv(const gguf_context * ctx, const int k) {
  1816. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1817. if (kt != GKV::gt) {
  1818. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1819. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1820. }
  1821. return GKV::getter(ctx, k);
  1822. }
  1823. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1824. switch (ty) {
  1825. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1826. case LLAMA_KV_OVERRIDE_INT: return "int";
  1827. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1828. }
  1829. return "unknown";
  1830. }
  1831. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1832. if (!override) { return false; }
  1833. if (override->tag == expected_type) {
  1834. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1835. __func__, override_type_to_str(override->tag), override->key);
  1836. switch (override->tag) {
  1837. case LLAMA_KV_OVERRIDE_BOOL: {
  1838. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  1839. } break;
  1840. case LLAMA_KV_OVERRIDE_INT: {
  1841. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  1842. } break;
  1843. case LLAMA_KV_OVERRIDE_FLOAT: {
  1844. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  1845. } break;
  1846. default:
  1847. // Shouldn't be possible to end up here, but just in case...
  1848. throw std::runtime_error(
  1849. format("Unsupported attempt to override %s type for metadata key %s\n",
  1850. override_type_to_str(override->tag), override->key));
  1851. }
  1852. return true;
  1853. }
  1854. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1855. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1856. return false;
  1857. }
  1858. template<typename OT>
  1859. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1860. try_override(OT & target, const struct llama_model_kv_override *override) {
  1861. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1862. target = override->bool_value;
  1863. return true;
  1864. }
  1865. return false;
  1866. }
  1867. template<typename OT>
  1868. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1869. try_override(OT & target, const struct llama_model_kv_override *override) {
  1870. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1871. target = override->int_value;
  1872. return true;
  1873. }
  1874. return false;
  1875. }
  1876. template<typename OT>
  1877. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1878. try_override(T & target, const struct llama_model_kv_override *override) {
  1879. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1880. target = override->float_value;
  1881. return true;
  1882. }
  1883. return false;
  1884. }
  1885. template<typename OT>
  1886. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1887. try_override(T & target, const struct llama_model_kv_override *override) {
  1888. (void)target;
  1889. (void)override;
  1890. if (!override) { return false; }
  1891. // Currently, we should never end up here so it would be a bug if we do.
  1892. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1893. override ? override->key : "NULL"));
  1894. }
  1895. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1896. if (try_override<T>(target, override)) {
  1897. return true;
  1898. }
  1899. if (k < 0) { return false; }
  1900. target = get_kv(ctx, k);
  1901. return true;
  1902. }
  1903. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1904. return set(ctx, gguf_find_key(ctx, key), target, override);
  1905. }
  1906. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1907. return set(ctx, key.c_str(), target, override);
  1908. }
  1909. };
  1910. }
  1911. struct llama_model_loader {
  1912. int n_kv = 0;
  1913. int n_tensors = 0;
  1914. int n_created = 0;
  1915. int64_t n_elements = 0;
  1916. size_t n_bytes = 0;
  1917. bool use_mmap = false;
  1918. llama_file file;
  1919. llama_ftype ftype;
  1920. llama_fver fver;
  1921. std::unique_ptr<llama_mmap> mapping;
  1922. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1923. struct gguf_context * ctx_gguf = NULL;
  1924. struct ggml_context * ctx_meta = NULL;
  1925. std::string arch_name;
  1926. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1927. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1928. int trace = 0;
  1929. if (getenv("LLAMA_TRACE")) {
  1930. trace = atoi(getenv("LLAMA_TRACE"));
  1931. }
  1932. struct gguf_init_params params = {
  1933. /*.no_alloc = */ true,
  1934. /*.ctx = */ &ctx_meta,
  1935. };
  1936. if (param_overrides_p != nullptr) {
  1937. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1938. kv_overrides.insert({std::string(p->key), *p});
  1939. }
  1940. }
  1941. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1942. if (!ctx_gguf) {
  1943. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1944. }
  1945. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  1946. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  1947. n_kv = gguf_get_n_kv(ctx_gguf);
  1948. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1949. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1950. for (int i = 0; i < n_tensors; i++) {
  1951. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1952. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1953. n_elements += ggml_nelements(t);
  1954. n_bytes += ggml_nbytes(t);
  1955. }
  1956. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1957. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1958. // determine file type based on the number of tensors for each quantization and print meta data
  1959. // TODO: make optional
  1960. {
  1961. std::map<enum ggml_type, uint32_t> n_type;
  1962. uint32_t n_type_max = 0;
  1963. enum ggml_type type_max = GGML_TYPE_F32;
  1964. for (int i = 0; i < n_tensors; i++) {
  1965. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  1966. n_type[type]++;
  1967. if (n_type_max < n_type[type]) {
  1968. n_type_max = n_type[type];
  1969. type_max = type;
  1970. }
  1971. if (trace > 0) {
  1972. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  1973. 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());
  1974. }
  1975. }
  1976. switch (type_max) {
  1977. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1978. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1979. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1980. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1981. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1982. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1983. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1984. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1985. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1986. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1987. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1988. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1989. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  1990. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  1991. default:
  1992. {
  1993. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1994. ftype = LLAMA_FTYPE_ALL_F32;
  1995. } break;
  1996. }
  1997. // this is a way to mark that we have "guessed" the file type
  1998. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1999. {
  2000. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2001. if (kid >= 0) {
  2002. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2003. }
  2004. }
  2005. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2006. for (int i = 0; i < n_kv; i++) {
  2007. const char * name = gguf_get_key(ctx_gguf, i);
  2008. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2009. const std::string type_name =
  2010. type == GGUF_TYPE_ARRAY
  2011. ? 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))
  2012. : gguf_type_name(type);
  2013. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2014. const size_t MAX_VALUE_LEN = 40;
  2015. if (value.size() > MAX_VALUE_LEN) {
  2016. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2017. }
  2018. replace_all(value, "\n", "\\n");
  2019. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2020. }
  2021. // print type counts
  2022. for (auto & kv : n_type) {
  2023. if (kv.second == 0) {
  2024. continue;
  2025. }
  2026. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2027. }
  2028. }
  2029. if (!llama_mmap::SUPPORTED) {
  2030. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2031. use_mmap = false;
  2032. }
  2033. this->use_mmap = use_mmap;
  2034. }
  2035. ~llama_model_loader() {
  2036. if (ctx_gguf) {
  2037. gguf_free(ctx_gguf);
  2038. }
  2039. if (ctx_meta) {
  2040. ggml_free(ctx_meta);
  2041. }
  2042. }
  2043. template<typename T>
  2044. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2045. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2046. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2047. if (kid < 0) {
  2048. if (required) {
  2049. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2050. }
  2051. return false;
  2052. }
  2053. struct GGUFMeta::ArrayInfo arr_info =
  2054. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2055. result = arr_info.length;
  2056. return true;
  2057. }
  2058. template<typename T>
  2059. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2060. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2061. return get_arr_n(llm_kv(kid), result, required);
  2062. }
  2063. template<typename T>
  2064. bool get_key(const std::string & key, T & result, const bool required = true) {
  2065. auto it = kv_overrides.find(key);
  2066. const struct llama_model_kv_override * override =
  2067. it != kv_overrides.end() ? &it->second : nullptr;
  2068. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2069. if (required && !found) {
  2070. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2071. }
  2072. return found;
  2073. }
  2074. template<typename T>
  2075. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2076. return get_key(llm_kv(kid), result, required);
  2077. }
  2078. std::string get_arch_name() const {
  2079. return arch_name;
  2080. }
  2081. enum llm_arch get_arch() const {
  2082. return llm_kv.arch;
  2083. }
  2084. const char * get_tensor_name(int i) const {
  2085. return gguf_get_tensor_name(ctx_gguf, i);
  2086. }
  2087. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2088. return ggml_get_tensor(ctx_meta, name);
  2089. }
  2090. struct ggml_tensor * get_tensor_meta(int i) const {
  2091. return get_tensor_meta(get_tensor_name(i));
  2092. }
  2093. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2094. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2095. ggml_set_name(tensor, ggml_get_name(meta));
  2096. n_created++;
  2097. return tensor;
  2098. }
  2099. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2100. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2101. if (cur == NULL) {
  2102. if (!required) {
  2103. return NULL;
  2104. }
  2105. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2106. }
  2107. {
  2108. bool is_ok = true;
  2109. for (size_t i = 0; i < ne.size(); ++i) {
  2110. if (ne[i] != cur->ne[i]) {
  2111. is_ok = false;
  2112. break;
  2113. }
  2114. }
  2115. if (!is_ok) {
  2116. throw std::runtime_error(
  2117. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2118. __func__, name.c_str(),
  2119. llama_format_tensor_shape(ne).c_str(),
  2120. llama_format_tensor_shape(cur).c_str()));
  2121. }
  2122. }
  2123. return create_tensor_for(ctx, cur);
  2124. }
  2125. void done_getting_tensors() const {
  2126. if (n_created != n_tensors) {
  2127. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2128. }
  2129. }
  2130. size_t file_offset(const char * name) const {
  2131. const int idx = gguf_find_tensor(ctx_gguf, name);
  2132. if (idx < 0) {
  2133. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2134. }
  2135. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2136. }
  2137. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2138. // prefetch the whole file - all the data is needed anyway
  2139. if (use_mmap) {
  2140. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2141. }
  2142. // compute the total size of all tensors for progress reporting
  2143. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2144. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2145. size_data += ggml_nbytes(cur);
  2146. }
  2147. if (use_mmap && mapping) {
  2148. if (lmlock) {
  2149. lmlock->init(mapping->addr);
  2150. }
  2151. mmap_used_first = mapping->size;
  2152. }
  2153. }
  2154. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2155. GGML_ASSERT(mapping);
  2156. *first = mapping->size;
  2157. *last = 0;
  2158. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2159. const size_t offs = file_offset(ggml_get_name(tensor));
  2160. *first = std::min(*first, offs);
  2161. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2162. }
  2163. }
  2164. // for backwards compatibility, does not support ggml-backend
  2165. void load_data_for(struct ggml_tensor * cur) const {
  2166. const size_t offs = file_offset(ggml_get_name(cur));
  2167. if (use_mmap && mapping) {
  2168. if (cur->data == nullptr) {
  2169. cur->data = (uint8_t *)mapping->addr + offs;
  2170. } else {
  2171. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2172. }
  2173. } else {
  2174. GGML_ASSERT(cur->data != nullptr);
  2175. file.seek(offs, SEEK_SET);
  2176. file.read_raw(cur->data, ggml_nbytes(cur));
  2177. }
  2178. }
  2179. size_t size_done = 0;
  2180. size_t size_data = 0;
  2181. size_t mmap_used_first = -1;
  2182. size_t mmap_used_last = 0;
  2183. // Returns false if cancelled by progress_callback
  2184. 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) {
  2185. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2186. std::vector<no_init<uint8_t>> read_buf;
  2187. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2188. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2189. if (!cur) {
  2190. // some tensors may be allocated in a different context
  2191. continue;
  2192. }
  2193. if (progress_callback) {
  2194. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2195. return false;
  2196. }
  2197. }
  2198. const size_t offs = file_offset(ggml_get_name(cur));
  2199. if (use_mmap && mapping) {
  2200. if (buf_mmap && cur->data == nullptr) {
  2201. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2202. if (lmlock) {
  2203. lmlock->grow_to(offs + ggml_nbytes(cur));
  2204. }
  2205. mmap_used_first = std::min(mmap_used_first, offs);
  2206. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2207. } else {
  2208. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2209. }
  2210. } else {
  2211. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2212. file.seek(offs, SEEK_SET);
  2213. file.read_raw(cur->data, ggml_nbytes(cur));
  2214. } else {
  2215. read_buf.resize(ggml_nbytes(cur));
  2216. file.seek(offs, SEEK_SET);
  2217. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2218. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2219. }
  2220. }
  2221. size_done += ggml_nbytes(cur);
  2222. }
  2223. // check if this is the last call and do final cleanup
  2224. if (size_done >= size_data) {
  2225. // unmap offloaded tensors and metadata
  2226. if (use_mmap && mapping) {
  2227. mapping->unmap_fragment(0, mmap_used_first);
  2228. if (mmap_used_last != 0) {
  2229. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2230. }
  2231. }
  2232. if (progress_callback) {
  2233. // Even though the model is done loading, we still honor
  2234. // cancellation since we need to free allocations.
  2235. return progress_callback(1.0f, progress_callback_user_data);
  2236. }
  2237. }
  2238. return true;
  2239. }
  2240. };
  2241. //
  2242. // load LLaMA models
  2243. //
  2244. static std::string llama_model_arch_name(llm_arch arch) {
  2245. auto it = LLM_ARCH_NAMES.find(arch);
  2246. if (it == LLM_ARCH_NAMES.end()) {
  2247. return "unknown";
  2248. }
  2249. return it->second;
  2250. }
  2251. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2252. if (ftype & LLAMA_FTYPE_GUESSED) {
  2253. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2254. }
  2255. switch (ftype) {
  2256. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2257. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2258. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2259. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2260. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2261. return "Q4_1, some F16";
  2262. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2263. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2264. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2265. // K-quants
  2266. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2267. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2268. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2269. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2270. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2271. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2272. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2273. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2274. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2275. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2276. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XSS - 2.0625 bpw";
  2277. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2278. default: return "unknown, may not work";
  2279. }
  2280. }
  2281. static const char * llama_model_type_name(e_model type) {
  2282. switch (type) {
  2283. case MODEL_1B: return "1B";
  2284. case MODEL_3B: return "3B";
  2285. case MODEL_7B: return "7B";
  2286. case MODEL_8B: return "8B";
  2287. case MODEL_13B: return "13B";
  2288. case MODEL_15B: return "15B";
  2289. case MODEL_30B: return "30B";
  2290. case MODEL_34B: return "34B";
  2291. case MODEL_40B: return "40B";
  2292. case MODEL_65B: return "65B";
  2293. case MODEL_70B: return "70B";
  2294. case MODEL_SMALL: return "0.1B";
  2295. case MODEL_MEDIUM: return "0.4B";
  2296. case MODEL_LARGE: return "0.8B";
  2297. case MODEL_XL: return "1.5B";
  2298. default: return "?B";
  2299. }
  2300. }
  2301. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2302. model.arch = ml.get_arch();
  2303. if (model.arch == LLM_ARCH_UNKNOWN) {
  2304. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2305. }
  2306. }
  2307. static void llm_load_hparams(
  2308. llama_model_loader & ml,
  2309. llama_model & model) {
  2310. auto & hparams = model.hparams;
  2311. const gguf_context * ctx = ml.ctx_gguf;
  2312. // get metadata as string
  2313. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2314. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2315. if (type == GGUF_TYPE_ARRAY) {
  2316. continue;
  2317. }
  2318. const char * name = gguf_get_key(ctx, i);
  2319. const std::string value = gguf_kv_to_str(ctx, i);
  2320. model.gguf_kv.emplace(name, value);
  2321. }
  2322. // get general kv
  2323. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2324. // get hparams kv
  2325. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2326. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2327. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2328. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2329. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2330. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2331. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2332. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2333. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2334. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2335. if (hparams.n_expert > 0) {
  2336. GGML_ASSERT(hparams.n_expert_used > 0);
  2337. } else {
  2338. GGML_ASSERT(hparams.n_expert_used == 0);
  2339. }
  2340. // n_head_kv is optional, default to n_head
  2341. hparams.n_head_kv = hparams.n_head;
  2342. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2343. bool rope_finetuned = false;
  2344. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2345. hparams.rope_finetuned = rope_finetuned;
  2346. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2347. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2348. // rope_freq_base (optional)
  2349. hparams.rope_freq_base_train = 10000.0f;
  2350. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2351. std::string rope_scaling("linear");
  2352. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2353. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2354. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2355. // rope_freq_scale (inverse of the kv) is optional
  2356. float ropescale = 0.0f;
  2357. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2358. // try the old key name
  2359. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2360. }
  2361. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2362. // sanity check for n_rot (optional)
  2363. {
  2364. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2365. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2366. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2367. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2368. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2369. }
  2370. }
  2371. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2372. // gpt-j n_rot = rotary_dim
  2373. }
  2374. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2375. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2376. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2377. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2378. // arch-specific KVs
  2379. switch (model.arch) {
  2380. case LLM_ARCH_LLAMA:
  2381. {
  2382. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2383. switch (hparams.n_layer) {
  2384. case 22: model.type = e_model::MODEL_1B; break;
  2385. case 26: model.type = e_model::MODEL_3B; break;
  2386. case 32: model.type = e_model::MODEL_7B; break;
  2387. case 40: model.type = e_model::MODEL_13B; break;
  2388. case 48: model.type = e_model::MODEL_34B; break;
  2389. case 60: model.type = e_model::MODEL_30B; break;
  2390. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2391. default: model.type = e_model::MODEL_UNKNOWN;
  2392. }
  2393. } break;
  2394. case LLM_ARCH_FALCON:
  2395. {
  2396. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2397. switch (hparams.n_layer) {
  2398. case 32: model.type = e_model::MODEL_7B; break;
  2399. case 60: model.type = e_model::MODEL_40B; break;
  2400. default: model.type = e_model::MODEL_UNKNOWN;
  2401. }
  2402. } break;
  2403. case LLM_ARCH_BAICHUAN:
  2404. {
  2405. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2406. switch (hparams.n_layer) {
  2407. case 32: model.type = e_model::MODEL_7B; break;
  2408. case 40: model.type = e_model::MODEL_13B; break;
  2409. default: model.type = e_model::MODEL_UNKNOWN;
  2410. }
  2411. } break;
  2412. case LLM_ARCH_STARCODER:
  2413. {
  2414. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2415. switch (hparams.n_layer) {
  2416. case 24: model.type = e_model::MODEL_1B; break;
  2417. case 36: model.type = e_model::MODEL_3B; break;
  2418. case 42: model.type = e_model::MODEL_7B; break;
  2419. case 40: model.type = e_model::MODEL_15B; break;
  2420. default: model.type = e_model::MODEL_UNKNOWN;
  2421. }
  2422. } break;
  2423. case LLM_ARCH_PERSIMMON:
  2424. {
  2425. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2426. switch (hparams.n_layer) {
  2427. case 36: model.type = e_model::MODEL_8B; break;
  2428. default: model.type = e_model::MODEL_UNKNOWN;
  2429. }
  2430. } break;
  2431. case LLM_ARCH_REFACT:
  2432. {
  2433. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2434. switch (hparams.n_layer) {
  2435. case 32: model.type = e_model::MODEL_1B; break;
  2436. default: model.type = e_model::MODEL_UNKNOWN;
  2437. }
  2438. } break;
  2439. case LLM_ARCH_BLOOM:
  2440. {
  2441. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2442. switch (hparams.n_layer) {
  2443. case 24: model.type = e_model::MODEL_1B; break;
  2444. case 30:
  2445. switch (hparams.n_embd) {
  2446. case 2560: model.type = e_model::MODEL_3B; break;
  2447. case 4096: model.type = e_model::MODEL_7B; break;
  2448. } break;
  2449. }
  2450. } break;
  2451. case LLM_ARCH_MPT:
  2452. {
  2453. hparams.f_clamp_kqv = 0.0f;
  2454. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2455. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2456. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2457. switch (hparams.n_layer) {
  2458. case 32: model.type = e_model::MODEL_7B; break;
  2459. case 48: model.type = e_model::MODEL_30B; break;
  2460. default: model.type = e_model::MODEL_UNKNOWN;
  2461. }
  2462. } break;
  2463. case LLM_ARCH_STABLELM:
  2464. {
  2465. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2466. switch (hparams.n_layer) {
  2467. case 32: model.type = e_model::MODEL_3B; break;
  2468. default: model.type = e_model::MODEL_UNKNOWN;
  2469. }
  2470. } break;
  2471. case LLM_ARCH_QWEN:
  2472. {
  2473. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2474. switch (hparams.n_layer) {
  2475. case 32: model.type = e_model::MODEL_7B; break;
  2476. case 40: model.type = e_model::MODEL_13B; break;
  2477. default: model.type = e_model::MODEL_UNKNOWN;
  2478. }
  2479. } break;
  2480. case LLM_ARCH_QWEN2:
  2481. {
  2482. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2483. switch (hparams.n_layer) {
  2484. case 24: model.type = e_model::MODEL_1B; break;
  2485. case 32: model.type = e_model::MODEL_7B; break;
  2486. case 40: model.type = e_model::MODEL_13B; break;
  2487. case 80: model.type = e_model::MODEL_70B; break;
  2488. default: model.type = e_model::MODEL_UNKNOWN;
  2489. }
  2490. } break;
  2491. case LLM_ARCH_PHI2:
  2492. {
  2493. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2494. switch (hparams.n_layer) {
  2495. case 24: model.type = e_model::MODEL_1B; break;
  2496. case 32: model.type = e_model::MODEL_3B; break;
  2497. default: model.type = e_model::MODEL_UNKNOWN;
  2498. }
  2499. } break;
  2500. case LLM_ARCH_PLAMO:
  2501. {
  2502. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2503. switch (hparams.n_layer) {
  2504. case 40: model.type = e_model::MODEL_13B; break;
  2505. default: model.type = e_model::MODEL_UNKNOWN;
  2506. }
  2507. } break;
  2508. case LLM_ARCH_GPT2:
  2509. {
  2510. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2511. switch (hparams.n_layer) {
  2512. case 12: model.type = e_model::MODEL_SMALL; break;
  2513. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2514. case 36: model.type = e_model::MODEL_LARGE; break;
  2515. case 48: model.type = e_model::MODEL_XL; break;
  2516. default: model.type = e_model::MODEL_UNKNOWN;
  2517. }
  2518. } break;
  2519. case LLM_ARCH_CODESHELL:
  2520. {
  2521. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2522. switch (hparams.n_layer) {
  2523. case 42: model.type = e_model::MODEL_SMALL; break;
  2524. default: model.type = e_model::MODEL_UNKNOWN;
  2525. }
  2526. } break;
  2527. default: (void)0;
  2528. }
  2529. model.ftype = ml.ftype;
  2530. }
  2531. // TODO: This should probably be in llama.h
  2532. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2533. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2534. static void llm_load_vocab(
  2535. llama_model_loader & ml,
  2536. llama_model & model) {
  2537. auto & vocab = model.vocab;
  2538. struct gguf_context * ctx = ml.ctx_gguf;
  2539. const auto kv = LLM_KV(model.arch);
  2540. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2541. if (token_idx == -1) {
  2542. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2543. }
  2544. const float * scores = nullptr;
  2545. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2546. if (score_idx != -1) {
  2547. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2548. }
  2549. const int * toktypes = nullptr;
  2550. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2551. if (toktype_idx != -1) {
  2552. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2553. }
  2554. // determine vocab type
  2555. {
  2556. std::string tokenizer_name;
  2557. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2558. if (tokenizer_name == "llama") {
  2559. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2560. // default special tokens
  2561. vocab.special_bos_id = 1;
  2562. vocab.special_eos_id = 2;
  2563. vocab.special_unk_id = 0;
  2564. vocab.special_sep_id = -1;
  2565. vocab.special_pad_id = -1;
  2566. } else if (tokenizer_name == "gpt2") {
  2567. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2568. // read bpe merges and populate bpe ranks
  2569. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2570. if (merges_keyidx == -1) {
  2571. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2572. }
  2573. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2574. for (int i = 0; i < n_merges; i++) {
  2575. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2576. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2577. std::string first;
  2578. std::string second;
  2579. const size_t pos = word.find(' ', 1);
  2580. if (pos != std::string::npos) {
  2581. first = word.substr(0, pos);
  2582. second = word.substr(pos + 1);
  2583. }
  2584. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2585. }
  2586. // default special tokens
  2587. vocab.special_bos_id = 11;
  2588. vocab.special_eos_id = 11;
  2589. vocab.special_unk_id = -1;
  2590. vocab.special_sep_id = -1;
  2591. vocab.special_pad_id = -1;
  2592. } else {
  2593. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2594. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2595. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2596. }
  2597. }
  2598. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2599. vocab.id_to_token.resize(n_vocab);
  2600. for (uint32_t i = 0; i < n_vocab; i++) {
  2601. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2602. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2603. vocab.token_to_id[word] = i;
  2604. auto & token_data = vocab.id_to_token[i];
  2605. token_data.text = std::move(word);
  2606. token_data.score = scores ? scores[i] : 0.0f;
  2607. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2608. }
  2609. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2610. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2611. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2612. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2613. } else {
  2614. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2615. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2616. vocab.linefeed_id = ids[0];
  2617. }
  2618. // special tokens
  2619. {
  2620. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2621. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2622. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2623. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2624. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2625. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2626. };
  2627. for (const auto & it : special_token_types) {
  2628. const std::string & key = kv(std::get<0>(it));
  2629. int32_t & id = std::get<1>(it);
  2630. uint32_t new_id;
  2631. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2632. continue;
  2633. }
  2634. if (new_id >= vocab.id_to_token.size()) {
  2635. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2636. __func__, key.c_str(), new_id, id);
  2637. } else {
  2638. id = new_id;
  2639. }
  2640. }
  2641. // Handle add_bos_token and add_eos_token
  2642. {
  2643. bool temp = true;
  2644. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2645. vocab.special_add_bos = int(temp);
  2646. }
  2647. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2648. vocab.special_add_eos = int(temp);
  2649. }
  2650. }
  2651. }
  2652. // build special tokens cache
  2653. {
  2654. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2655. // and will always be correctly labeled in 'added_tokens.json' etc.
  2656. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2657. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2658. // are special tokens.
  2659. // From testing, this appears to correlate 1:1 with special tokens.
  2660. //
  2661. // Counting special tokens and verifying in only one direction
  2662. // is sufficient to detect difference in those two sets.
  2663. //
  2664. uint32_t special_tokens_count_by_type = 0;
  2665. uint32_t special_tokens_count_from_verification = 0;
  2666. bool special_tokens_definition_mismatch = false;
  2667. for (const auto & t : vocab.token_to_id) {
  2668. const auto & token = t.first;
  2669. const auto & id = t.second;
  2670. // Count all non-normal tokens in the vocab while iterating
  2671. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2672. special_tokens_count_by_type++;
  2673. }
  2674. // Skip single character tokens
  2675. if (token.length() > 1) {
  2676. bool is_tokenizable = false;
  2677. // Split token string representation in two, in all possible ways
  2678. // and check if both halves can be matched to a valid token
  2679. for (unsigned i = 1; i < token.length();) {
  2680. const auto left = token.substr(0, i);
  2681. const auto right = token.substr(i);
  2682. // check if we didnt partition in the middle of a utf sequence
  2683. auto utf = utf8_len(left.at(left.length() - 1));
  2684. if (utf == 1) {
  2685. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2686. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2687. is_tokenizable = true;
  2688. break;
  2689. }
  2690. i++;
  2691. } else {
  2692. // skip over the rest of multibyte utf sequence
  2693. i += utf - 1;
  2694. }
  2695. }
  2696. if (!is_tokenizable) {
  2697. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2698. // it's faster to re-filter them here, since there are way less candidates now
  2699. // Calculate a total "utf" length of a token string representation
  2700. size_t utf8_str_len = 0;
  2701. for (unsigned i = 0; i < token.length();) {
  2702. utf8_str_len++;
  2703. i += utf8_len(token.at(i));
  2704. }
  2705. // And skip the ones which are one character
  2706. if (utf8_str_len > 1) {
  2707. // At this point what we have left are special tokens only
  2708. vocab.special_tokens_cache[token] = id;
  2709. // Count manually found special tokens
  2710. special_tokens_count_from_verification++;
  2711. // If this manually found special token is not marked as such, flag a mismatch
  2712. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2713. special_tokens_definition_mismatch = true;
  2714. }
  2715. }
  2716. }
  2717. }
  2718. }
  2719. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2720. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2721. __func__,
  2722. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2723. special_tokens_count_by_type, vocab.id_to_token.size()
  2724. );
  2725. } else {
  2726. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2727. __func__,
  2728. special_tokens_count_from_verification, vocab.id_to_token.size()
  2729. );
  2730. }
  2731. }
  2732. }
  2733. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2734. const auto & hparams = model.hparams;
  2735. const auto & vocab = model.vocab;
  2736. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2737. // hparams
  2738. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2739. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2740. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2741. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2742. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2743. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2744. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2745. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2746. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2747. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2748. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2749. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2750. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2751. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2752. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2753. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2754. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2755. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2756. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2757. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2758. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2759. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2760. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2761. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2762. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2763. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2764. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2765. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2766. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2767. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2768. if (ml.n_elements >= 1e12) {
  2769. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2770. } else if (ml.n_elements >= 1e9) {
  2771. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2772. } else if (ml.n_elements >= 1e6) {
  2773. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2774. } else {
  2775. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2776. }
  2777. if (ml.n_bytes < GiB) {
  2778. 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);
  2779. } else {
  2780. 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);
  2781. }
  2782. // general kv
  2783. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2784. // special tokens
  2785. 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() ); }
  2786. 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() ); }
  2787. 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() ); }
  2788. 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() ); }
  2789. 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() ); }
  2790. 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() ); }
  2791. }
  2792. // Returns false if cancelled by progress_callback
  2793. static bool llm_load_tensors(
  2794. llama_model_loader & ml,
  2795. llama_model & model,
  2796. int n_gpu_layers,
  2797. enum llama_split_mode split_mode,
  2798. int main_gpu,
  2799. const float * tensor_split,
  2800. bool use_mlock,
  2801. llama_progress_callback progress_callback,
  2802. void * progress_callback_user_data) {
  2803. model.t_start_us = ggml_time_us();
  2804. auto & hparams = model.hparams;
  2805. model.split_mode = split_mode;
  2806. model.main_gpu = main_gpu;
  2807. model.n_gpu_layers = n_gpu_layers;
  2808. const int64_t n_layer = hparams.n_layer;
  2809. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2810. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2811. model.buft_input = llama_default_buffer_type_cpu(true);
  2812. model.buft_layer.resize(n_layer);
  2813. // assign cpu layers
  2814. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2815. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2816. }
  2817. #ifdef GGML_USE_CUBLAS
  2818. if (split_mode == LLAMA_SPLIT_LAYER) {
  2819. // calculate the split points
  2820. int device_count = ggml_backend_cuda_get_device_count();
  2821. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2822. float splits[GGML_CUDA_MAX_DEVICES];
  2823. if (all_zero) {
  2824. // default split, by free memory
  2825. for (int i = 0; i < device_count; ++i) {
  2826. size_t total;
  2827. size_t free;
  2828. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2829. splits[i] = free;
  2830. }
  2831. } else {
  2832. std::copy(tensor_split, tensor_split + device_count, splits);
  2833. }
  2834. // sum and normalize the splits to get the split points
  2835. float split_sum = 0.0f;
  2836. for (int i = 0; i < device_count; ++i) {
  2837. split_sum += splits[i];
  2838. splits[i] = split_sum;
  2839. }
  2840. for (int i = 0; i < device_count; ++i) {
  2841. splits[i] /= split_sum;
  2842. }
  2843. // assign the repeating layers to the devices according to the splits
  2844. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2845. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2846. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2847. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2848. }
  2849. // assign the output layer
  2850. if (n_gpu_layers > n_layer) {
  2851. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2852. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2853. } else {
  2854. model.buft_output = llama_default_buffer_type_cpu(true);
  2855. }
  2856. } else
  2857. #endif
  2858. {
  2859. ggml_backend_buffer_type_t split_buft;
  2860. if (split_mode == LLAMA_SPLIT_ROW) {
  2861. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2862. } else {
  2863. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2864. split_buft = llama_default_buffer_type_offload(main_gpu);
  2865. }
  2866. // assign the repeating layers
  2867. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2868. model.buft_layer[i] = {
  2869. split_buft,
  2870. llama_default_buffer_type_offload(main_gpu)
  2871. };
  2872. }
  2873. // assign the output layer
  2874. if (n_gpu_layers > n_layer) {
  2875. model.buft_output = {
  2876. split_buft,
  2877. llama_default_buffer_type_offload(main_gpu)
  2878. };
  2879. } else {
  2880. model.buft_output = llama_default_buffer_type_cpu(true);
  2881. }
  2882. }
  2883. // count used buffer types
  2884. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2885. buft_layer_count[model.buft_input.buft]++;
  2886. buft_layer_count[model.buft_input.buft_matrix]++;
  2887. buft_layer_count[model.buft_output.buft]++;
  2888. buft_layer_count[model.buft_output.buft_matrix]++;
  2889. for (int64_t i = 0; i < n_layer; ++i) {
  2890. buft_layer_count[model.buft_layer[i].buft]++;
  2891. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  2892. }
  2893. // create one context per buffer type
  2894. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  2895. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2896. for (auto & it : buft_layer_count) {
  2897. struct ggml_init_params params = {
  2898. /*.mem_size =*/ ctx_size,
  2899. /*.mem_buffer =*/ NULL,
  2900. /*.no_alloc =*/ true,
  2901. };
  2902. ggml_context * ctx = ggml_init(params);
  2903. if (!ctx) {
  2904. throw std::runtime_error(format("failed to create context"));
  2905. }
  2906. ctx_map[it.first] = ctx;
  2907. model.ctxs.push_back(ctx);
  2908. }
  2909. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  2910. // create tensors for the weights
  2911. {
  2912. const int64_t n_embd = hparams.n_embd;
  2913. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  2914. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  2915. const int64_t n_embd_gqa = n_embd_v_gqa;
  2916. const int64_t n_vocab = hparams.n_vocab;
  2917. const int64_t n_ff = hparams.n_ff;
  2918. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  2919. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  2920. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  2921. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  2922. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  2923. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  2924. model.layers.resize(n_layer);
  2925. const auto tn = LLM_TN(model.arch);
  2926. switch (model.arch) {
  2927. case LLM_ARCH_LLAMA:
  2928. case LLM_ARCH_REFACT:
  2929. {
  2930. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2931. // output
  2932. {
  2933. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2934. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2935. }
  2936. for (int i = 0; i < n_layer; ++i) {
  2937. ggml_context * ctx_layer = ctx_for_layer(i);
  2938. ggml_context * ctx_split = ctx_for_layer_split(i);
  2939. auto & layer = model.layers[i];
  2940. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2941. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2942. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2943. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2944. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2945. // optional bias tensors
  2946. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  2947. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  2948. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  2949. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  2950. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2951. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  2952. if (layer.ffn_gate_inp == nullptr) {
  2953. GGML_ASSERT(hparams.n_expert == 0);
  2954. GGML_ASSERT(hparams.n_expert_used == 0);
  2955. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2956. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2957. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2958. } else {
  2959. GGML_ASSERT(hparams.n_expert > 0);
  2960. GGML_ASSERT(hparams.n_expert_used > 0);
  2961. // MoE branch
  2962. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  2963. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  2964. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  2965. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  2966. }
  2967. }
  2968. }
  2969. } break;
  2970. case LLM_ARCH_BAICHUAN:
  2971. {
  2972. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2973. {
  2974. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2975. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2976. }
  2977. for (int i = 0; i < n_layer; ++i) {
  2978. ggml_context * ctx_layer = ctx_for_layer(i);
  2979. ggml_context * ctx_split = ctx_for_layer_split(i);
  2980. auto & layer = model.layers[i];
  2981. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2982. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2983. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2984. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2985. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2986. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2987. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2988. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2989. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2990. }
  2991. } break;
  2992. case LLM_ARCH_FALCON:
  2993. {
  2994. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2995. // output
  2996. {
  2997. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2998. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  2999. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3000. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3001. } else {
  3002. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3003. ml.n_created--; // artificial tensor
  3004. }
  3005. }
  3006. for (int i = 0; i < n_layer; ++i) {
  3007. ggml_context * ctx_layer = ctx_for_layer(i);
  3008. ggml_context * ctx_split = ctx_for_layer_split(i);
  3009. auto & layer = model.layers[i];
  3010. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3011. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3012. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3013. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3014. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3015. }
  3016. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3017. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3018. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3019. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3020. }
  3021. } break;
  3022. case LLM_ARCH_STARCODER:
  3023. {
  3024. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3025. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3026. // output
  3027. {
  3028. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3029. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3030. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3031. }
  3032. for (int i = 0; i < n_layer; ++i) {
  3033. ggml_context * ctx_layer = ctx_for_layer(i);
  3034. ggml_context * ctx_split = ctx_for_layer_split(i);
  3035. auto & layer = model.layers[i];
  3036. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3037. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3038. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3039. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3040. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3041. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3042. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3043. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3044. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3045. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3046. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3047. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3048. }
  3049. } break;
  3050. case LLM_ARCH_PERSIMMON:
  3051. {
  3052. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3053. {
  3054. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3055. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3056. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3057. }
  3058. for (int i = 0; i < n_layer; ++i) {
  3059. ggml_context * ctx_layer = ctx_for_layer(i);
  3060. ggml_context * ctx_split = ctx_for_layer_split(i);
  3061. auto & layer = model.layers[i];
  3062. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3063. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3064. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3065. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3066. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3067. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3068. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3069. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3070. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3071. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3072. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3073. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3074. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3075. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3076. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3077. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3078. }
  3079. } break;
  3080. case LLM_ARCH_BLOOM:
  3081. {
  3082. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3083. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3084. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3085. // output
  3086. {
  3087. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3088. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3089. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3090. }
  3091. for (int i = 0; i < n_layer; ++i) {
  3092. ggml_context * ctx_layer = ctx_for_layer(i);
  3093. ggml_context * ctx_split = ctx_for_layer_split(i);
  3094. auto & layer = model.layers[i];
  3095. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3096. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3097. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3098. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3099. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3100. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3101. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3102. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3103. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3104. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3105. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3106. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3107. }
  3108. } break;
  3109. case LLM_ARCH_MPT:
  3110. {
  3111. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3112. // output
  3113. {
  3114. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3115. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3116. }
  3117. for (int i = 0; i < n_layer; ++i) {
  3118. ggml_context * ctx_layer = ctx_for_layer(i);
  3119. ggml_context * ctx_split = ctx_for_layer_split(i);
  3120. auto & layer = model.layers[i];
  3121. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3122. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3123. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3124. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3125. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3126. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3127. // AWQ ScaleActivation layer
  3128. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3129. }
  3130. } break;
  3131. case LLM_ARCH_STABLELM:
  3132. {
  3133. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3134. // output
  3135. {
  3136. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3137. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3138. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3139. }
  3140. for (int i = 0; i < n_layer; ++i) {
  3141. ggml_context * ctx_layer = ctx_for_layer(i);
  3142. ggml_context * ctx_split = ctx_for_layer_split(i);
  3143. auto & layer = model.layers[i];
  3144. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3145. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3146. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3147. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3148. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3149. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3150. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3151. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3152. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3153. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3154. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3155. }
  3156. } break;
  3157. case LLM_ARCH_QWEN:
  3158. {
  3159. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3160. // output
  3161. {
  3162. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3163. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3164. }
  3165. for (int i = 0; i < n_layer; ++i) {
  3166. ggml_context * ctx_layer = ctx_for_layer(i);
  3167. ggml_context * ctx_split = ctx_for_layer_split(i);
  3168. auto & layer = model.layers[i];
  3169. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3170. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3171. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3172. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3173. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3174. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3175. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3176. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3177. }
  3178. } break;
  3179. case LLM_ARCH_QWEN2:
  3180. {
  3181. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3182. // output
  3183. {
  3184. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3185. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3186. }
  3187. for (int i = 0; i < n_layer; ++i) {
  3188. ggml_context * ctx_layer = ctx_for_layer(i);
  3189. ggml_context * ctx_split = ctx_for_layer_split(i);
  3190. auto & layer = model.layers[i];
  3191. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3192. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3193. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3194. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3195. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3196. // optional bias tensors
  3197. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3198. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3199. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3200. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3201. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3202. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3203. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3204. }
  3205. } break;
  3206. case LLM_ARCH_PHI2:
  3207. {
  3208. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3209. // output
  3210. {
  3211. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3212. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3213. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3214. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3215. }
  3216. for (int i = 0; i < n_layer; ++i) {
  3217. ggml_context * ctx_layer = ctx_for_layer(i);
  3218. ggml_context * ctx_split = ctx_for_layer_split(i);
  3219. auto & layer = model.layers[i];
  3220. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3221. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3222. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3223. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3224. if (layer.wqkv == nullptr) {
  3225. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3226. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3227. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3228. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3229. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3230. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3231. }
  3232. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3233. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3234. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3235. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3236. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3237. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3238. }
  3239. } break;
  3240. case LLM_ARCH_PLAMO:
  3241. {
  3242. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3243. // output
  3244. {
  3245. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3246. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3247. }
  3248. for (int i = 0; i < n_layer; ++i) {
  3249. ggml_context * ctx_layer = ctx_for_layer(i);
  3250. ggml_context * ctx_split = ctx_for_layer_split(i);
  3251. auto & layer = model.layers[i];
  3252. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3253. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3254. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3255. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3256. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3257. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3258. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3259. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3260. }
  3261. } break;
  3262. case LLM_ARCH_GPT2:
  3263. {
  3264. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3265. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3266. // output
  3267. {
  3268. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3269. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3270. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3271. }
  3272. for (int i = 0; i < n_layer; ++i) {
  3273. ggml_context * ctx_layer = ctx_for_layer(i);
  3274. ggml_context * ctx_split = ctx_for_layer_split(i);
  3275. auto & layer = model.layers[i];
  3276. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3277. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3278. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3279. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3280. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3281. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3282. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3283. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3284. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3285. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3286. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3287. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3288. }
  3289. } break;
  3290. case LLM_ARCH_CODESHELL:
  3291. {
  3292. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3293. // output
  3294. {
  3295. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3296. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3297. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3298. }
  3299. for (int i = 0; i < n_layer; ++i) {
  3300. ggml_context * ctx_layer = ctx_for_layer(i);
  3301. ggml_context * ctx_split = ctx_for_layer_split(i);
  3302. auto & layer = model.layers[i];
  3303. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3304. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3305. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3306. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3307. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3308. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3309. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3310. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3311. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3312. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3313. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3314. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3315. }
  3316. } break;
  3317. default:
  3318. throw std::runtime_error("unknown architecture");
  3319. }
  3320. }
  3321. ml.done_getting_tensors();
  3322. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3323. // create the backend buffers
  3324. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3325. for (auto & it : ctx_map) {
  3326. ggml_backend_buffer_type_t buft = it.first;
  3327. ggml_context * ctx = it.second;
  3328. ggml_backend_buffer_t buf = nullptr;
  3329. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3330. // 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
  3331. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3332. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3333. size_t first, last;
  3334. ml.get_mapping_range(&first, &last, ctx);
  3335. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3336. }
  3337. #ifdef GGML_USE_METAL
  3338. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3339. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3340. size_t first, last;
  3341. ml.get_mapping_range(&first, &last, ctx);
  3342. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3343. }
  3344. #endif
  3345. else {
  3346. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3347. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3348. model.mlock_bufs.emplace_back(new llama_mlock);
  3349. auto & mlock_buf = model.mlock_bufs.back();
  3350. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3351. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3352. }
  3353. }
  3354. if (buf == nullptr) {
  3355. throw std::runtime_error("failed to allocate buffer");
  3356. }
  3357. // indicate that this buffer contains weights
  3358. // 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
  3359. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3360. model.bufs.push_back(buf);
  3361. ctx_bufs.emplace_back(ctx, buf);
  3362. }
  3363. // print memory requirements
  3364. {
  3365. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3366. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3367. if (n_gpu_layers > (int) hparams.n_layer) {
  3368. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3369. }
  3370. const int max_backend_supported_layers = hparams.n_layer + 1;
  3371. const int max_offloadable_layers = hparams.n_layer + 1;
  3372. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3373. for (ggml_backend_buffer_t buf : model.bufs) {
  3374. 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);
  3375. }
  3376. }
  3377. // populate tensors_by_name
  3378. for (ggml_context * ctx : model.ctxs) {
  3379. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3380. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3381. }
  3382. }
  3383. // load tensor data
  3384. for (auto & it : ctx_bufs) {
  3385. ggml_context * ctx = it.first;
  3386. ggml_backend_buffer_t buf = it.second;
  3387. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3388. return false;
  3389. }
  3390. }
  3391. model.mapping = std::move(ml.mapping);
  3392. // loading time will be recalculate after the first eval, so
  3393. // we take page faults deferred by mmap() into consideration
  3394. model.t_load_us = ggml_time_us() - model.t_start_us;
  3395. return true;
  3396. }
  3397. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3398. static int llama_model_load(const std::string & fname, llama_model & model, const llama_model_params & params) {
  3399. try {
  3400. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3401. model.hparams.vocab_only = params.vocab_only;
  3402. llm_load_arch (ml, model);
  3403. llm_load_hparams(ml, model);
  3404. llm_load_vocab (ml, model);
  3405. llm_load_print_meta(ml, model);
  3406. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3407. throw std::runtime_error("vocab size mismatch");
  3408. }
  3409. if (params.vocab_only) {
  3410. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3411. return 0;
  3412. }
  3413. if (!llm_load_tensors(
  3414. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3415. params.progress_callback, params.progress_callback_user_data
  3416. )) {
  3417. return -2;
  3418. }
  3419. } catch (const std::exception & err) {
  3420. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3421. return -1;
  3422. }
  3423. return 0;
  3424. }
  3425. //
  3426. // llm_build
  3427. //
  3428. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3429. enum llm_rope_type {
  3430. LLM_ROPE,
  3431. LLM_ROPE_NEOX,
  3432. LLM_ROPE_GLM,
  3433. };
  3434. enum llm_ffn_op_type {
  3435. LLM_FFN_SILU,
  3436. LLM_FFN_GELU,
  3437. LLM_FFN_RELU,
  3438. LLM_FFN_RELU_SQR,
  3439. };
  3440. enum llm_ffn_gate_type {
  3441. LLM_FFN_SEQ,
  3442. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3443. };
  3444. enum llm_norm_type {
  3445. LLM_NORM,
  3446. LLM_NORM_RMS,
  3447. };
  3448. static struct ggml_tensor * llm_build_inp_embd(
  3449. struct ggml_context * ctx,
  3450. const llama_hparams & hparams,
  3451. const llama_batch & batch,
  3452. struct ggml_tensor * tok_embd,
  3453. const llm_build_cb & cb) {
  3454. const int64_t n_embd = hparams.n_embd;
  3455. struct ggml_tensor * inpL;
  3456. if (batch.token) {
  3457. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  3458. cb(inp_tokens, "inp_tokens", -1);
  3459. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens);
  3460. } else {
  3461. #ifdef GGML_USE_MPI
  3462. GGML_ASSERT(false && "not implemented");
  3463. #endif
  3464. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  3465. }
  3466. return inpL;
  3467. }
  3468. // Persimmon: n_rot = n_embd_head_k/2
  3469. // Other: n_rot = n_embd_head_k
  3470. static void llm_build_k_shift(
  3471. struct ggml_context * ctx,
  3472. const llama_hparams & hparams,
  3473. const llama_cparams & cparams,
  3474. const llama_kv_cache & kv,
  3475. struct ggml_cgraph * graph,
  3476. llm_rope_type type,
  3477. int64_t n_ctx,
  3478. float freq_base,
  3479. float freq_scale,
  3480. const llm_build_cb & cb) {
  3481. const int64_t n_layer = hparams.n_layer;
  3482. const int64_t n_head_kv = hparams.n_head_kv;
  3483. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3484. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3485. const int32_t n_rot = hparams.n_rot;
  3486. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3487. const float ext_factor = cparams.yarn_ext_factor;
  3488. const float attn_factor = cparams.yarn_attn_factor;
  3489. const float beta_fast = cparams.yarn_beta_fast;
  3490. const float beta_slow = cparams.yarn_beta_slow;
  3491. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_ctx);
  3492. cb(K_shift, "K_shift", -1);
  3493. int rope_type = 0;
  3494. switch (type) {
  3495. case LLM_ROPE: rope_type = 0; break;
  3496. case LLM_ROPE_NEOX: rope_type = 2; break;
  3497. case LLM_ROPE_GLM: rope_type = 4; break;
  3498. }
  3499. for (int il = 0; il < n_layer; ++il) {
  3500. struct ggml_tensor * tmp =
  3501. // we rotate only the first n_rot dimensions
  3502. ggml_rope_custom_inplace(ctx,
  3503. ggml_view_3d(ctx, kv.k_l[il],
  3504. n_embd_head_k, n_head_kv, n_ctx,
  3505. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3506. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3507. 0),
  3508. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3509. ext_factor, attn_factor, beta_fast, beta_slow);
  3510. cb(tmp, "K_shifted", il);
  3511. ggml_build_forward_expand(graph, tmp);
  3512. }
  3513. }
  3514. static void llm_build_kv_store(
  3515. struct ggml_context * ctx,
  3516. const llama_hparams & hparams,
  3517. const llama_kv_cache & kv,
  3518. struct ggml_cgraph * graph,
  3519. struct ggml_tensor * k_cur,
  3520. struct ggml_tensor * v_cur,
  3521. int64_t n_ctx,
  3522. int32_t n_tokens,
  3523. int32_t kv_head,
  3524. const llm_build_cb & cb,
  3525. int64_t il) {
  3526. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3527. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3528. // compute the transposed [n_tokens, n_embd] V matrix
  3529. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3530. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3531. cb(v_cur_t, "v_cur_t", il);
  3532. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3533. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3534. cb(k_cache_view, "k_cache_view", il);
  3535. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3536. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3537. (kv_head)*ggml_element_size(kv.v_l[il]));
  3538. cb(v_cache_view, "v_cache_view", il);
  3539. // important: storing RoPE-ed version of K in the KV cache!
  3540. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3541. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3542. }
  3543. static struct ggml_tensor * llm_build_norm(
  3544. struct ggml_context * ctx,
  3545. struct ggml_tensor * cur,
  3546. const llama_hparams & hparams,
  3547. struct ggml_tensor * mw,
  3548. struct ggml_tensor * mb,
  3549. llm_norm_type type,
  3550. const llm_build_cb & cb,
  3551. int il) {
  3552. switch (type) {
  3553. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3554. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3555. }
  3556. if (mw || mb) {
  3557. cb(cur, "norm", il);
  3558. }
  3559. if (mw) {
  3560. cur = ggml_mul(ctx, cur, mw);
  3561. if (mb) {
  3562. cb(cur, "norm_w", il);
  3563. }
  3564. }
  3565. if (mb) {
  3566. cur = ggml_add(ctx, cur, mb);
  3567. }
  3568. return cur;
  3569. }
  3570. static struct ggml_tensor * llm_build_ffn(
  3571. struct ggml_context * ctx,
  3572. struct ggml_tensor * cur,
  3573. struct ggml_tensor * up,
  3574. struct ggml_tensor * up_b,
  3575. struct ggml_tensor * gate,
  3576. struct ggml_tensor * gate_b,
  3577. struct ggml_tensor * down,
  3578. struct ggml_tensor * down_b,
  3579. struct ggml_tensor * act_scales,
  3580. llm_ffn_op_type type_op,
  3581. llm_ffn_gate_type type_gate,
  3582. const llm_build_cb & cb,
  3583. int il) {
  3584. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3585. cb(tmp, "ffn_up", il);
  3586. if (up_b) {
  3587. tmp = ggml_add(ctx, tmp, up_b);
  3588. cb(tmp, "ffn_up_b", il);
  3589. }
  3590. if (gate) {
  3591. switch (type_gate) {
  3592. case LLM_FFN_SEQ:
  3593. {
  3594. cur = ggml_mul_mat(ctx, gate, tmp);
  3595. cb(cur, "ffn_gate", il);
  3596. } break;
  3597. case LLM_FFN_PAR:
  3598. {
  3599. cur = ggml_mul_mat(ctx, gate, cur);
  3600. cb(cur, "ffn_gate", il);
  3601. } break;
  3602. }
  3603. if (gate_b) {
  3604. cur = ggml_add(ctx, cur, gate_b);
  3605. cb(cur, "ffn_gate_b", il);
  3606. }
  3607. } else {
  3608. cur = tmp;
  3609. }
  3610. switch (type_op) {
  3611. case LLM_FFN_SILU:
  3612. {
  3613. cur = ggml_silu(ctx, cur);
  3614. cb(cur, "ffn_silu", il);
  3615. } break;
  3616. case LLM_FFN_GELU:
  3617. {
  3618. cur = ggml_gelu(ctx, cur);
  3619. cb(cur, "ffn_gelu", il);
  3620. if (act_scales != NULL) {
  3621. cur = ggml_div(ctx, cur, act_scales);
  3622. cb(cur, "ffn_act", il);
  3623. }
  3624. } break;
  3625. case LLM_FFN_RELU:
  3626. {
  3627. cur = ggml_relu(ctx, cur);
  3628. cb(cur, "ffn_relu", il);
  3629. } break;
  3630. case LLM_FFN_RELU_SQR:
  3631. {
  3632. cur = ggml_relu(ctx, cur);
  3633. cb(cur, "ffn_relu", il);
  3634. cur = ggml_sqr(ctx, cur);
  3635. cb(cur, "ffn_sqr(relu)", il);
  3636. } break;
  3637. }
  3638. if (type_gate == LLM_FFN_PAR) {
  3639. cur = ggml_mul(ctx, cur, tmp);
  3640. cb(cur, "ffn_gate_par", il);
  3641. }
  3642. cur = ggml_mul_mat(ctx, down, cur);
  3643. if (down_b) {
  3644. cb(cur, "ffn_down", il);
  3645. }
  3646. if (down_b) {
  3647. cur = ggml_add(ctx, cur, down_b);
  3648. }
  3649. return cur;
  3650. }
  3651. // if max_alibi_bias > 0 then apply ALiBi
  3652. static struct ggml_tensor * llm_build_kqv(
  3653. struct ggml_context * ctx,
  3654. const llama_model & model,
  3655. const llama_hparams & hparams,
  3656. const llama_kv_cache & kv,
  3657. struct ggml_cgraph * graph,
  3658. struct ggml_tensor * wo,
  3659. struct ggml_tensor * wo_b,
  3660. struct ggml_tensor * q_cur,
  3661. struct ggml_tensor * kq_mask,
  3662. int64_t n_ctx,
  3663. int32_t n_tokens,
  3664. int32_t n_kv,
  3665. float max_alibi_bias,
  3666. float kq_scale,
  3667. const llm_build_cb & cb,
  3668. int il) {
  3669. const int64_t n_head = hparams.n_head;
  3670. const int64_t n_head_kv = hparams.n_head_kv;
  3671. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3672. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3673. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3674. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3675. cb(q, "q", il);
  3676. struct ggml_tensor * k =
  3677. ggml_view_3d(ctx, kv.k_l[il],
  3678. n_embd_head_k, n_kv, n_head_kv,
  3679. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3680. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3681. 0);
  3682. cb(k, "k", il);
  3683. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3684. cb(kq, "kq", il);
  3685. if (model.arch == LLM_ARCH_PHI2) {
  3686. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3687. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3688. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3689. }
  3690. if (max_alibi_bias > 0.0f) {
  3691. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3692. kq = ggml_scale(ctx, kq, kq_scale);
  3693. cb(kq, "kq_scaled", il);
  3694. if (max_alibi_bias > 0.0f) {
  3695. // TODO: n_head or n_head_kv
  3696. // TODO: K-shift is likely not working
  3697. // TODO: change to ggml_add
  3698. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3699. cb(kq, "kq_scaled_alibi", il);
  3700. }
  3701. kq = ggml_add(ctx, kq, kq_mask);
  3702. cb(kq, "kq_masked", il);
  3703. kq = ggml_soft_max(ctx, kq);
  3704. cb(kq, "kq_soft_max", il);
  3705. } else {
  3706. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3707. cb(kq, "kq_soft_max_ext", il);
  3708. }
  3709. // split cached v into n_head heads
  3710. struct ggml_tensor * v =
  3711. ggml_view_3d(ctx, kv.v_l[il],
  3712. n_kv, n_embd_head_v, n_head_kv,
  3713. ggml_element_size(kv.v_l[il])*n_ctx,
  3714. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3715. 0);
  3716. cb(v, "v", il);
  3717. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3718. cb(kqv, "kqv", il);
  3719. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3720. cb(kqv_merged, "kqv_merged", il);
  3721. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3722. cb(cur, "kqv_merged_cont", il);
  3723. ggml_build_forward_expand(graph, cur);
  3724. cur = ggml_mul_mat(ctx, wo, cur);
  3725. if (wo_b) {
  3726. cb(cur, "kqv_wo", il);
  3727. }
  3728. if (wo_b) {
  3729. cur = ggml_add(ctx, cur, wo_b);
  3730. }
  3731. return cur;
  3732. }
  3733. static struct ggml_tensor * llm_build_kv(
  3734. struct ggml_context * ctx,
  3735. const llama_model & model,
  3736. const llama_hparams & hparams,
  3737. const llama_kv_cache & kv,
  3738. struct ggml_cgraph * graph,
  3739. struct ggml_tensor * wo,
  3740. struct ggml_tensor * wo_b,
  3741. struct ggml_tensor * k_cur,
  3742. struct ggml_tensor * v_cur,
  3743. struct ggml_tensor * q_cur,
  3744. struct ggml_tensor * kq_mask,
  3745. int64_t n_ctx,
  3746. int32_t n_tokens,
  3747. int32_t kv_head,
  3748. int32_t n_kv,
  3749. float max_alibi_bias,
  3750. float kq_scale,
  3751. const llm_build_cb & cb,
  3752. int il) {
  3753. // these nodes are added to the graph together so that they are not reordered
  3754. // by doing so, the number of splits in the graph is reduced
  3755. ggml_build_forward_expand(graph, k_cur);
  3756. ggml_build_forward_expand(graph, v_cur);
  3757. ggml_build_forward_expand(graph, q_cur);
  3758. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  3759. struct ggml_tensor * cur;
  3760. cur = llm_build_kqv(ctx, model, hparams, kv, graph,
  3761. wo, wo_b,
  3762. q_cur, kq_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, kq_scale, cb, il);
  3763. cb(cur, "kqv_out", il);
  3764. return cur;
  3765. }
  3766. struct llm_build_context {
  3767. const llama_model & model;
  3768. const llama_hparams & hparams;
  3769. const llama_cparams & cparams;
  3770. const llama_batch & batch;
  3771. const llama_kv_cache & kv_self;
  3772. const int64_t n_embd;
  3773. const int64_t n_layer;
  3774. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3775. const int64_t n_head;
  3776. const int64_t n_head_kv;
  3777. const int64_t n_embd_head_k;
  3778. const int64_t n_embd_k_gqa;
  3779. const int64_t n_embd_head_v;
  3780. const int64_t n_embd_v_gqa;
  3781. const int64_t n_expert;
  3782. const int64_t n_expert_used;
  3783. const float freq_base;
  3784. const float freq_scale;
  3785. const float ext_factor;
  3786. const float attn_factor;
  3787. const float beta_fast;
  3788. const float beta_slow;
  3789. const float norm_eps;
  3790. const float norm_rms_eps;
  3791. const int32_t n_tokens;
  3792. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3793. const int32_t kv_head; // index of where we store new KV data in the cache
  3794. const int32_t n_orig_ctx;
  3795. const bool do_rope_shift;
  3796. const llm_build_cb & cb;
  3797. std::vector<uint8_t> & buf_compute_meta;
  3798. struct ggml_context * ctx0 = nullptr;
  3799. // TODO: consider making the entire interface noexcept
  3800. llm_build_context(
  3801. llama_context & lctx,
  3802. const llama_batch & batch,
  3803. const llm_build_cb & cb,
  3804. bool worst_case) :
  3805. model (lctx.model),
  3806. hparams (model.hparams),
  3807. cparams (lctx.cparams),
  3808. batch (batch),
  3809. kv_self (lctx.kv_self),
  3810. n_embd (hparams.n_embd),
  3811. n_layer (hparams.n_layer),
  3812. n_ctx (cparams.n_ctx),
  3813. n_head (hparams.n_head),
  3814. n_head_kv (hparams.n_head_kv),
  3815. n_embd_head_k (hparams.n_embd_head_k),
  3816. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3817. n_embd_head_v (hparams.n_embd_head_v),
  3818. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  3819. n_expert (hparams.n_expert),
  3820. n_expert_used (hparams.n_expert_used),
  3821. freq_base (cparams.rope_freq_base),
  3822. freq_scale (cparams.rope_freq_scale),
  3823. ext_factor (cparams.yarn_ext_factor),
  3824. attn_factor (cparams.yarn_attn_factor),
  3825. beta_fast (cparams.yarn_beta_fast),
  3826. beta_slow (cparams.yarn_beta_slow),
  3827. norm_eps (hparams.f_norm_eps),
  3828. norm_rms_eps (hparams.f_norm_rms_eps),
  3829. n_tokens (batch.n_tokens),
  3830. n_kv (worst_case ? n_ctx : kv_self.n),
  3831. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3832. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3833. do_rope_shift (worst_case || kv_self.has_shift),
  3834. cb (cb),
  3835. buf_compute_meta (lctx.buf_compute_meta) {
  3836. // all initializations should be done in init()
  3837. }
  3838. void init() {
  3839. struct ggml_init_params params = {
  3840. /*.mem_size =*/ buf_compute_meta.size(),
  3841. /*.mem_buffer =*/ buf_compute_meta.data(),
  3842. /*.no_alloc =*/ true,
  3843. };
  3844. ctx0 = ggml_init(params);
  3845. }
  3846. void free() {
  3847. if (ctx0) {
  3848. ggml_free(ctx0);
  3849. ctx0 = nullptr;
  3850. }
  3851. }
  3852. struct ggml_cgraph * build_llama() {
  3853. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3854. const int64_t n_embd_head = hparams.n_embd_head_v;
  3855. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3856. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3857. struct ggml_tensor * cur;
  3858. struct ggml_tensor * inpL;
  3859. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3860. cb(inpL, "inp_embd", -1);
  3861. // inp_pos - contains the positions
  3862. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3863. cb(inp_pos, "inp_pos", -1);
  3864. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3865. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3866. cb(KQ_mask, "KQ_mask", -1);
  3867. // shift the entire K-cache if needed
  3868. if (do_rope_shift) {
  3869. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3870. }
  3871. for (int il = 0; il < n_layer; ++il) {
  3872. struct ggml_tensor * inpSA = inpL;
  3873. // norm
  3874. cur = llm_build_norm(ctx0, inpL, hparams,
  3875. model.layers[il].attn_norm, NULL,
  3876. LLM_NORM_RMS, cb, il);
  3877. cb(cur, "attn_norm", il);
  3878. // self-attention
  3879. {
  3880. // compute Q and K and RoPE them
  3881. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3882. cb(Qcur, "Qcur", il);
  3883. if (model.layers[il].bq) {
  3884. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3885. cb(Qcur, "Qcur", il);
  3886. }
  3887. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3888. cb(Kcur, "Kcur", il);
  3889. if (model.layers[il].bk) {
  3890. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3891. cb(Kcur, "Kcur", il);
  3892. }
  3893. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3894. cb(Vcur, "Vcur", il);
  3895. if (model.layers[il].bv) {
  3896. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3897. cb(Vcur, "Vcur", il);
  3898. }
  3899. Qcur = ggml_rope_custom(
  3900. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3901. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3902. ext_factor, attn_factor, beta_fast, beta_slow
  3903. );
  3904. cb(Qcur, "Qcur", il);
  3905. Kcur = ggml_rope_custom(
  3906. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3907. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3908. ext_factor, attn_factor, beta_fast, beta_slow
  3909. );
  3910. cb(Kcur, "Kcur", il);
  3911. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  3912. model.layers[il].wo, model.layers[il].bo,
  3913. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3914. cb(cur, "kqv_out", il);
  3915. }
  3916. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3917. cb(ffn_inp, "ffn_inp", il);
  3918. // feed-forward network
  3919. if (model.layers[il].ffn_gate_inp == nullptr) {
  3920. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3921. model.layers[il].ffn_norm, NULL,
  3922. LLM_NORM_RMS, cb, il);
  3923. cb(cur, "ffn_norm", il);
  3924. cur = llm_build_ffn(ctx0, cur,
  3925. model.layers[il].ffn_up, NULL,
  3926. model.layers[il].ffn_gate, NULL,
  3927. model.layers[il].ffn_down, NULL,
  3928. NULL,
  3929. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3930. cb(cur, "ffn_out", il);
  3931. } else {
  3932. // MoE branch
  3933. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3934. model.layers[il].ffn_norm, NULL,
  3935. LLM_NORM_RMS, cb, il);
  3936. cb(cur, "ffn_norm", il);
  3937. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  3938. cb(logits, "ffn_moe_logits", il);
  3939. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  3940. cb(probs, "ffn_moe_probs", il);
  3941. // select experts
  3942. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  3943. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  3944. ggml_tensor * weights = ggml_get_rows(ctx0,
  3945. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  3946. cb(weights, "ffn_moe_weights", il);
  3947. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  3948. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  3949. cb(weights_sum, "ffn_moe_weights_sum", il);
  3950. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  3951. cb(weights, "ffn_moe_weights_norm", il);
  3952. // compute expert outputs
  3953. ggml_tensor * moe_out = nullptr;
  3954. for (int i = 0; i < n_expert_used; ++i) {
  3955. ggml_tensor * cur_expert;
  3956. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  3957. cb(cur_up, "ffn_moe_up", il);
  3958. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  3959. cb(cur_gate, "ffn_moe_gate", il);
  3960. cur_gate = ggml_silu(ctx0, cur_gate);
  3961. cb(cur_gate, "ffn_moe_silu", il);
  3962. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  3963. cb(cur_expert, "ffn_moe_gate_par", il);
  3964. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  3965. cb(cur_expert, "ffn_moe_down", il);
  3966. cur_expert = ggml_mul(ctx0, cur_expert,
  3967. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  3968. cb(cur_expert, "ffn_moe_weighted", il);
  3969. if (i == 0) {
  3970. moe_out = cur_expert;
  3971. } else {
  3972. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  3973. cb(moe_out, "ffn_moe_out", il);
  3974. }
  3975. }
  3976. cur = moe_out;
  3977. }
  3978. cur = ggml_add(ctx0, cur, ffn_inp);
  3979. cb(cur, "l_out", il);
  3980. // input for next layer
  3981. inpL = cur;
  3982. }
  3983. cur = inpL;
  3984. cur = llm_build_norm(ctx0, cur, hparams,
  3985. model.output_norm, NULL,
  3986. LLM_NORM_RMS, cb, -1);
  3987. cb(cur, "result_norm", -1);
  3988. // lm_head
  3989. cur = ggml_mul_mat(ctx0, model.output, cur);
  3990. cb(cur, "result_output", -1);
  3991. ggml_build_forward_expand(gf, cur);
  3992. return gf;
  3993. }
  3994. struct ggml_cgraph * build_baichuan() {
  3995. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3996. const int64_t n_embd_head = hparams.n_embd_head_v;
  3997. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3998. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3999. struct ggml_tensor * cur;
  4000. struct ggml_tensor * inpL;
  4001. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4002. cb(inpL, "inp_embd", -1);
  4003. // inp_pos - contains the positions
  4004. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4005. cb(inp_pos, "inp_pos", -1);
  4006. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4007. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4008. cb(KQ_mask, "KQ_mask", -1);
  4009. // shift the entire K-cache if needed
  4010. if (do_rope_shift) {
  4011. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4012. }
  4013. for (int il = 0; il < n_layer; ++il) {
  4014. struct ggml_tensor * inpSA = inpL;
  4015. cur = llm_build_norm(ctx0, inpL, hparams,
  4016. model.layers[il].attn_norm, NULL,
  4017. LLM_NORM_RMS, cb, il);
  4018. cb(cur, "attn_norm", il);
  4019. // self-attention
  4020. {
  4021. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4022. cb(Qcur, "Qcur", il);
  4023. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4024. cb(Kcur, "Kcur", il);
  4025. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4026. cb(Vcur, "Vcur", il);
  4027. switch (model.type) {
  4028. case MODEL_7B:
  4029. Qcur = ggml_rope_custom(
  4030. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4031. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4032. ext_factor, attn_factor, beta_fast, beta_slow
  4033. );
  4034. Kcur = ggml_rope_custom(
  4035. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4036. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4037. ext_factor, attn_factor, beta_fast, beta_slow
  4038. );
  4039. break;
  4040. case MODEL_13B:
  4041. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4042. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4043. break;
  4044. default:
  4045. GGML_ASSERT(false);
  4046. }
  4047. cb(Qcur, "Qcur", il);
  4048. cb(Kcur, "Kcur", il);
  4049. // apply ALiBi for 13B model
  4050. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4051. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4052. model.layers[il].wo, NULL,
  4053. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4054. cb(cur, "kqv_out", il);
  4055. }
  4056. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4057. cb(ffn_inp, "ffn_inp", il);
  4058. // feed-forward network
  4059. {
  4060. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4061. model.layers[il].ffn_norm, NULL,
  4062. LLM_NORM_RMS, cb, il);
  4063. cb(cur, "ffn_norm", il);
  4064. cur = llm_build_ffn(ctx0, cur,
  4065. model.layers[il].ffn_up, NULL,
  4066. model.layers[il].ffn_gate, NULL,
  4067. model.layers[il].ffn_down, NULL,
  4068. NULL,
  4069. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4070. cb(cur, "ffn_out", il);
  4071. }
  4072. cur = ggml_add(ctx0, cur, ffn_inp);
  4073. cb(cur, "l_out", il);
  4074. // input for next layer
  4075. inpL = cur;
  4076. }
  4077. cur = inpL;
  4078. cur = llm_build_norm(ctx0, cur, hparams,
  4079. model.output_norm, NULL,
  4080. LLM_NORM_RMS, cb, -1);
  4081. cb(cur, "result_norm", -1);
  4082. // lm_head
  4083. cur = ggml_mul_mat(ctx0, model.output, cur);
  4084. cb(cur, "result_output", -1);
  4085. ggml_build_forward_expand(gf, cur);
  4086. return gf;
  4087. }
  4088. struct ggml_cgraph * build_falcon() {
  4089. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4090. const int64_t n_embd_head = hparams.n_embd_head_v;
  4091. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4092. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4093. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4094. struct ggml_tensor * cur;
  4095. struct ggml_tensor * inpL;
  4096. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4097. cb(inpL, "inp_embd", -1);
  4098. // inp_pos - contains the positions
  4099. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4100. cb(inp_pos, "inp_pos", -1);
  4101. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4102. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4103. cb(KQ_mask, "KQ_mask", -1);
  4104. // shift the entire K-cache if needed
  4105. if (do_rope_shift) {
  4106. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4107. }
  4108. for (int il = 0; il < n_layer; ++il) {
  4109. struct ggml_tensor * attn_norm;
  4110. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4111. model.layers[il].attn_norm,
  4112. model.layers[il].attn_norm_b,
  4113. LLM_NORM, cb, il);
  4114. cb(attn_norm, "attn_norm", il);
  4115. // self-attention
  4116. {
  4117. if (model.layers[il].attn_norm_2) {
  4118. // Falcon-40B
  4119. cur = llm_build_norm(ctx0, inpL, hparams,
  4120. model.layers[il].attn_norm_2,
  4121. model.layers[il].attn_norm_2_b,
  4122. LLM_NORM, cb, il);
  4123. cb(cur, "attn_norm_2", il);
  4124. } else {
  4125. cur = attn_norm;
  4126. }
  4127. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4128. cb(cur, "wqkv", il);
  4129. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4130. 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)));
  4131. 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)));
  4132. cb(Qcur, "Qcur", il);
  4133. cb(Kcur, "Kcur", il);
  4134. cb(Vcur, "Vcur", il);
  4135. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4136. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4137. // using mode = 2 for neox mode
  4138. Qcur = ggml_rope_custom(
  4139. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4140. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4141. );
  4142. cb(Qcur, "Qcur", il);
  4143. Kcur = ggml_rope_custom(
  4144. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4145. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4146. );
  4147. cb(Kcur, "Kcur", il);
  4148. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4149. model.layers[il].wo, NULL,
  4150. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4151. cb(cur, "kqv_out", il);
  4152. }
  4153. struct ggml_tensor * ffn_inp = cur;
  4154. // feed forward
  4155. {
  4156. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4157. model.layers[il].ffn_up, NULL,
  4158. NULL, NULL,
  4159. model.layers[il].ffn_down, NULL,
  4160. NULL,
  4161. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4162. cb(cur, "ffn_out", il);
  4163. }
  4164. cur = ggml_add(ctx0, cur, ffn_inp);
  4165. cb(cur, "l_out", il);
  4166. cur = ggml_add(ctx0, cur, inpL);
  4167. cb(cur, "l_out", il);
  4168. // input for next layer
  4169. inpL = cur;
  4170. }
  4171. cur = inpL;
  4172. // norm
  4173. cur = llm_build_norm(ctx0, cur, hparams,
  4174. model.output_norm,
  4175. model.output_norm_b,
  4176. LLM_NORM, cb, -1);
  4177. cb(cur, "result_norm", -1);
  4178. cur = ggml_mul_mat(ctx0, model.output, cur);
  4179. cb(cur, "result_output", -1);
  4180. ggml_build_forward_expand(gf, cur);
  4181. return gf;
  4182. }
  4183. struct ggml_cgraph * build_starcoder() {
  4184. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4185. const int64_t n_embd_head = hparams.n_embd_head_v;
  4186. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4187. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4188. struct ggml_tensor * cur;
  4189. struct ggml_tensor * pos;
  4190. struct ggml_tensor * inpL;
  4191. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4192. cb(inpL, "inp_embd", -1);
  4193. // inp_pos - contains the positions
  4194. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4195. cb(inp_pos, "inp_pos", -1);
  4196. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4197. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4198. cb(KQ_mask, "KQ_mask", -1);
  4199. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4200. cb(pos, "pos_embd", -1);
  4201. inpL = ggml_add(ctx0, inpL, pos);
  4202. cb(inpL, "inpL", -1);
  4203. for (int il = 0; il < n_layer; ++il) {
  4204. cur = llm_build_norm(ctx0, inpL, hparams,
  4205. model.layers[il].attn_norm,
  4206. model.layers[il].attn_norm_b,
  4207. LLM_NORM, cb, il);
  4208. cb(cur, "attn_norm", il);
  4209. // self-attention
  4210. {
  4211. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4212. cb(cur, "wqkv", il);
  4213. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4214. cb(cur, "bqkv", il);
  4215. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4216. 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)));
  4217. 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)));
  4218. cb(Qcur, "Qcur", il);
  4219. cb(Kcur, "Kcur", il);
  4220. cb(Vcur, "Vcur", il);
  4221. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4222. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4223. model.layers[il].wo, model.layers[il].bo,
  4224. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4225. cb(cur, "kqv_out", il);
  4226. }
  4227. // add the input
  4228. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4229. cb(ffn_inp, "ffn_inp", il);
  4230. // FF
  4231. {
  4232. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4233. model.layers[il].ffn_norm,
  4234. model.layers[il].ffn_norm_b,
  4235. LLM_NORM, cb, il);
  4236. cb(cur, "ffn_norm", il);
  4237. cur = llm_build_ffn(ctx0, cur,
  4238. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4239. NULL, NULL,
  4240. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4241. NULL,
  4242. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4243. cb(cur, "ffn_out", il);
  4244. }
  4245. inpL = ggml_add(ctx0, cur, ffn_inp);
  4246. cb(inpL, "l_out", il);
  4247. }
  4248. cur = llm_build_norm(ctx0, inpL, hparams,
  4249. model.output_norm,
  4250. model.output_norm_b,
  4251. LLM_NORM, cb, -1);
  4252. cb(cur, "result_norm", -1);
  4253. cur = ggml_mul_mat(ctx0, model.output, cur);
  4254. cb(cur, "result_output", -1);
  4255. ggml_build_forward_expand(gf, cur);
  4256. return gf;
  4257. }
  4258. struct ggml_cgraph * build_persimmon() {
  4259. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4260. const int64_t n_embd_head = hparams.n_embd_head_v;
  4261. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4262. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4263. struct ggml_tensor * cur;
  4264. struct ggml_tensor * inpL;
  4265. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4266. cb(inpL, "inp_embd", -1);
  4267. // inp_pos - contains the positions
  4268. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4269. cb(inp_pos, "inp_pos", -1);
  4270. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4271. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4272. cb(KQ_mask, "KQ_mask", -1);
  4273. if (do_rope_shift) {
  4274. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4275. }
  4276. for (int il = 0; il < n_layer; ++il) {
  4277. struct ggml_tensor * residual = inpL;
  4278. cur = llm_build_norm(ctx0, inpL, hparams,
  4279. model.layers[il].attn_norm,
  4280. model.layers[il].attn_norm_b,
  4281. LLM_NORM, cb, il);
  4282. cb(cur, "attn_norm", il);
  4283. // self attention
  4284. {
  4285. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4286. cb(cur, "wqkv", il);
  4287. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4288. cb(cur, "bqkv", il);
  4289. // split qkv
  4290. GGML_ASSERT(n_head_kv == n_head);
  4291. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4292. cb(tmpqkv, "tmpqkv", il);
  4293. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4294. cb(tmpqkv_perm, "tmpqkv", il);
  4295. struct ggml_tensor * tmpq = ggml_view_3d(
  4296. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4297. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4298. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4299. 0
  4300. );
  4301. cb(tmpq, "tmpq", il);
  4302. struct ggml_tensor * tmpk = ggml_view_3d(
  4303. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4304. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4305. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4306. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4307. );
  4308. cb(tmpk, "tmpk", il);
  4309. // Q/K Layernorm
  4310. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4311. model.layers[il].attn_q_norm,
  4312. model.layers[il].attn_q_norm_b,
  4313. LLM_NORM, cb, il);
  4314. cb(tmpq, "tmpq", il);
  4315. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4316. model.layers[il].attn_k_norm,
  4317. model.layers[il].attn_k_norm_b,
  4318. LLM_NORM, cb, il);
  4319. cb(tmpk, "tmpk", il);
  4320. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4321. struct ggml_tensor * qrot = ggml_view_3d(
  4322. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4323. ggml_element_size(tmpq) * n_embd_head,
  4324. ggml_element_size(tmpq) * n_embd_head * n_head,
  4325. 0
  4326. );
  4327. cb(qrot, "qrot", il);
  4328. struct ggml_tensor * krot = ggml_view_3d(
  4329. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4330. ggml_element_size(tmpk) * n_embd_head,
  4331. ggml_element_size(tmpk) * n_embd_head * n_head,
  4332. 0
  4333. );
  4334. cb(krot, "krot", il);
  4335. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4336. struct ggml_tensor * qpass = ggml_view_3d(
  4337. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4338. ggml_element_size(tmpq) * n_embd_head,
  4339. ggml_element_size(tmpq) * n_embd_head * n_head,
  4340. ggml_element_size(tmpq) * hparams.n_rot
  4341. );
  4342. cb(qpass, "qpass", il);
  4343. struct ggml_tensor * kpass = ggml_view_3d(
  4344. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4345. ggml_element_size(tmpk) * n_embd_head,
  4346. ggml_element_size(tmpk) * n_embd_head * n_head,
  4347. ggml_element_size(tmpk) * hparams.n_rot
  4348. );
  4349. cb(kpass, "kpass", il);
  4350. struct ggml_tensor * qrotated = ggml_rope_custom(
  4351. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4352. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4353. );
  4354. cb(qrotated, "qrotated", il);
  4355. struct ggml_tensor * krotated = ggml_rope_custom(
  4356. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4357. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4358. );
  4359. cb(krotated, "krotated", il);
  4360. // ggml currently only supports concatenation on dim=2
  4361. // so we need to permute qrot, qpass, concat, then permute back.
  4362. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4363. cb(qrotated, "qrotated", il);
  4364. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4365. cb(krotated, "krotated", il);
  4366. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4367. cb(qpass, "qpass", il);
  4368. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4369. cb(kpass, "kpass", il);
  4370. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4371. cb(Qcur, "Qcur", il);
  4372. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4373. cb(Kcur, "Kcur", il);
  4374. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4375. cb(Q, "Q", il);
  4376. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4377. cb(Kcur, "Kcur", il);
  4378. struct ggml_tensor * Vcur = ggml_view_3d(
  4379. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4380. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4381. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4382. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4383. );
  4384. cb(Vcur, "Vcur", il);
  4385. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4386. model.layers[il].wo, model.layers[il].bo,
  4387. Kcur, Vcur, Q, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4388. cb(cur, "kqv_out", il);
  4389. }
  4390. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4391. cb(ffn_inp, "ffn_inp", il);
  4392. // feed-forward network
  4393. {
  4394. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4395. model.layers[il].ffn_norm,
  4396. model.layers[il].ffn_norm_b,
  4397. LLM_NORM, cb, il);
  4398. cb(cur, "ffn_norm", il);
  4399. cur = llm_build_ffn(ctx0, cur,
  4400. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4401. NULL, NULL,
  4402. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4403. NULL,
  4404. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4405. cb(cur, "ffn_out", il);
  4406. }
  4407. cur = ggml_add(ctx0, cur, ffn_inp);
  4408. cb(cur, "l_out", il);
  4409. inpL = cur;
  4410. }
  4411. cur = inpL;
  4412. cur = llm_build_norm(ctx0, cur, hparams,
  4413. model.output_norm,
  4414. model.output_norm_b,
  4415. LLM_NORM, cb, -1);
  4416. cb(cur, "result_norm", -1);
  4417. cur = ggml_mul_mat(ctx0, model.output, cur);
  4418. cb(cur, "result_output", -1);
  4419. ggml_build_forward_expand(gf, cur);
  4420. return gf;
  4421. }
  4422. struct ggml_cgraph * build_refact() {
  4423. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4424. const int64_t n_embd_head = hparams.n_embd_head_v;
  4425. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4426. struct ggml_tensor * cur;
  4427. struct ggml_tensor * inpL;
  4428. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4429. cb(inpL, "inp_embd", -1);
  4430. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4431. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4432. cb(KQ_mask, "KQ_mask", -1);
  4433. for (int il = 0; il < n_layer; ++il) {
  4434. struct ggml_tensor * inpSA = inpL;
  4435. cur = llm_build_norm(ctx0, inpL, hparams,
  4436. model.layers[il].attn_norm, NULL,
  4437. LLM_NORM_RMS, cb, il);
  4438. cb(cur, "attn_norm", il);
  4439. // self-attention
  4440. {
  4441. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4442. cb(Qcur, "Qcur", il);
  4443. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4444. cb(Kcur, "Kcur", il);
  4445. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4446. cb(Vcur, "Vcur", il);
  4447. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4448. cb(Kcur, "Kcur", il);
  4449. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4450. cb(Qcur, "Qcur", il);
  4451. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4452. model.layers[il].wo, NULL,
  4453. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4454. cb(cur, "kqv_out", il);
  4455. }
  4456. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4457. cb(ffn_inp, "ffn_inp", il);
  4458. // feed-forward network
  4459. {
  4460. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4461. model.layers[il].ffn_norm, NULL,
  4462. LLM_NORM_RMS, cb, il);
  4463. cb(cur, "ffn_norm", il);
  4464. cur = llm_build_ffn(ctx0, cur,
  4465. model.layers[il].ffn_up, NULL,
  4466. model.layers[il].ffn_gate, NULL,
  4467. model.layers[il].ffn_down, NULL,
  4468. NULL,
  4469. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4470. cb(cur, "ffn_out", il);
  4471. }
  4472. cur = ggml_add(ctx0, cur, ffn_inp);
  4473. cb(cur, "l_out", il);
  4474. // input for next layer
  4475. inpL = cur;
  4476. }
  4477. cur = inpL;
  4478. cur = llm_build_norm(ctx0, cur, hparams,
  4479. model.output_norm, NULL,
  4480. LLM_NORM_RMS, cb, -1);
  4481. cb(cur, "result_norm", -1);
  4482. // lm_head
  4483. cur = ggml_mul_mat(ctx0, model.output, cur);
  4484. cb(cur, "result_output", -1);
  4485. ggml_build_forward_expand(gf, cur);
  4486. return gf;
  4487. }
  4488. struct ggml_cgraph * build_bloom() {
  4489. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4490. const int64_t n_embd_head = hparams.n_embd_head_v;
  4491. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4492. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4493. struct ggml_tensor * cur;
  4494. struct ggml_tensor * inpL;
  4495. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4496. cb(inpL, "inp_embd", -1);
  4497. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4498. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4499. cb(KQ_mask, "KQ_mask", -1);
  4500. inpL = llm_build_norm(ctx0, inpL, hparams,
  4501. model.tok_norm,
  4502. model.tok_norm_b,
  4503. LLM_NORM, cb, -1);
  4504. cb(inpL, "inp_norm", -1);
  4505. for (int il = 0; il < n_layer; ++il) {
  4506. cur = llm_build_norm(ctx0, inpL, hparams,
  4507. model.layers[il].attn_norm,
  4508. model.layers[il].attn_norm_b,
  4509. LLM_NORM, cb, il);
  4510. cb(cur, "attn_norm", il);
  4511. // self-attention
  4512. {
  4513. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4514. cb(cur, "wqkv", il);
  4515. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4516. cb(cur, "bqkv", il);
  4517. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4518. 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)));
  4519. 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)));
  4520. cb(Qcur, "Qcur", il);
  4521. cb(Kcur, "Kcur", il);
  4522. cb(Vcur, "Vcur", il);
  4523. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4524. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4525. model.layers[il].wo, model.layers[il].bo,
  4526. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4527. cb(cur, "kqv_out", il);
  4528. }
  4529. // Add the input
  4530. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4531. cb(ffn_inp, "ffn_inp", il);
  4532. // FF
  4533. {
  4534. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4535. model.layers[il].ffn_norm,
  4536. model.layers[il].ffn_norm_b,
  4537. LLM_NORM, cb, il);
  4538. cb(cur, "ffn_norm", il);
  4539. cur = llm_build_ffn(ctx0, cur,
  4540. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4541. NULL, NULL,
  4542. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4543. NULL,
  4544. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4545. cb(cur, "ffn_out", il);
  4546. }
  4547. inpL = ggml_add(ctx0, cur, ffn_inp);
  4548. cb(inpL, "l_out", il);
  4549. }
  4550. cur = llm_build_norm(ctx0, inpL, hparams,
  4551. model.output_norm,
  4552. model.output_norm_b,
  4553. LLM_NORM, cb, -1);
  4554. cb(cur, "result_norm", -1);
  4555. cur = ggml_mul_mat(ctx0, model.output, cur);
  4556. cb(cur, "result_output", -1);
  4557. ggml_build_forward_expand(gf, cur);
  4558. return gf;
  4559. }
  4560. struct ggml_cgraph * build_mpt() {
  4561. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4562. const int64_t n_embd_head = hparams.n_embd_head_v;
  4563. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4564. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4565. struct ggml_tensor * cur;
  4566. struct ggml_tensor * inpL;
  4567. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4568. cb(inpL, "inp_embd", -1);
  4569. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4570. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4571. cb(KQ_mask, "KQ_mask", -1);
  4572. for (int il = 0; il < n_layer; ++il) {
  4573. struct ggml_tensor * attn_norm;
  4574. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4575. model.layers[il].attn_norm,
  4576. NULL,
  4577. LLM_NORM, cb, il);
  4578. cb(attn_norm, "attn_norm", il);
  4579. // self-attention
  4580. {
  4581. cur = attn_norm;
  4582. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4583. cb(cur, "wqkv", il);
  4584. if (hparams.f_clamp_kqv > 0.0f) {
  4585. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4586. cb(cur, "wqkv_clamped", il);
  4587. }
  4588. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4589. 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)));
  4590. 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)));
  4591. cb(Qcur, "Qcur", il);
  4592. cb(Kcur, "Kcur", il);
  4593. cb(Vcur, "Vcur", il);
  4594. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4595. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4596. model.layers[il].wo, NULL,
  4597. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4598. cb(cur, "kqv_out", il);
  4599. }
  4600. // Add the input
  4601. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4602. cb(ffn_inp, "ffn_inp", il);
  4603. // feed forward
  4604. {
  4605. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4606. model.layers[il].ffn_norm,
  4607. NULL,
  4608. LLM_NORM, cb, il);
  4609. cb(cur, "ffn_norm", il);
  4610. cur = llm_build_ffn(ctx0, cur,
  4611. model.layers[il].ffn_up, NULL,
  4612. NULL, NULL,
  4613. model.layers[il].ffn_down, NULL,
  4614. model.layers[il].ffn_act,
  4615. LLM_FFN_GELU, LLM_FFN_SEQ, 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,
  4626. NULL,
  4627. LLM_NORM, cb, -1);
  4628. cb(cur, "result_norm", -1);
  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_stablelm() {
  4635. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4636. const int64_t n_embd_head = hparams.n_embd_head_v;
  4637. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4638. struct ggml_tensor * cur;
  4639. struct ggml_tensor * inpL;
  4640. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4641. cb(inpL, "inp_embd", -1);
  4642. // inp_pos - contains the positions
  4643. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4644. cb(inp_pos, "inp_pos", -1);
  4645. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4646. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4647. cb(KQ_mask, "KQ_mask", -1);
  4648. // shift the entire K-cache if needed
  4649. if (do_rope_shift) {
  4650. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4651. }
  4652. for (int il = 0; il < n_layer; ++il) {
  4653. struct ggml_tensor * inpSA = inpL;
  4654. // norm
  4655. cur = llm_build_norm(ctx0, inpL, hparams,
  4656. model.layers[il].attn_norm,
  4657. model.layers[il].attn_norm_b,
  4658. LLM_NORM, cb, il);
  4659. cb(cur, "attn_norm", il);
  4660. // self-attention
  4661. {
  4662. // compute Q and K and RoPE them
  4663. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4664. cb(Qcur, "Qcur", il);
  4665. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4666. cb(Kcur, "Kcur", il);
  4667. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4668. cb(Vcur, "Vcur", il);
  4669. Qcur = ggml_rope_custom(
  4670. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4671. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4672. ext_factor, attn_factor, beta_fast, beta_slow
  4673. );
  4674. cb(Qcur, "Qcur", il);
  4675. Kcur = ggml_rope_custom(
  4676. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4677. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4678. ext_factor, attn_factor, beta_fast, beta_slow
  4679. );
  4680. cb(Kcur, "Kcur", il);
  4681. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4682. model.layers[il].wo, NULL,
  4683. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4684. cb(cur, "kqv_out", il);
  4685. }
  4686. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4687. cb(ffn_inp, "ffn_inp", il);
  4688. // feed-forward network
  4689. {
  4690. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4691. model.layers[il].ffn_norm,
  4692. model.layers[il].ffn_norm_b,
  4693. LLM_NORM, cb, il);
  4694. cb(cur, "ffn_norm", il);
  4695. cur = llm_build_ffn(ctx0, cur,
  4696. model.layers[il].ffn_up, NULL,
  4697. model.layers[il].ffn_gate, NULL,
  4698. model.layers[il].ffn_down, NULL,
  4699. NULL,
  4700. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4701. cb(cur, "ffn_out", il);
  4702. }
  4703. cur = ggml_add(ctx0, cur, ffn_inp);
  4704. cb(cur, "l_out", il);
  4705. // input for next layer
  4706. inpL = cur;
  4707. }
  4708. cur = inpL;
  4709. cur = llm_build_norm(ctx0, cur, hparams,
  4710. model.output_norm,
  4711. model.output_norm_b,
  4712. LLM_NORM, cb, -1);
  4713. cb(cur, "result_norm", -1);
  4714. // lm_head
  4715. cur = ggml_mul_mat(ctx0, model.output, cur);
  4716. cb(cur, "result_output", -1);
  4717. ggml_build_forward_expand(gf, cur);
  4718. return gf;
  4719. }
  4720. struct ggml_cgraph * build_qwen() {
  4721. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4722. const int64_t n_embd_head = hparams.n_embd_head_v;
  4723. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4724. struct ggml_tensor * cur;
  4725. struct ggml_tensor * inpL;
  4726. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4727. cb(inpL, "inp_embd", -1);
  4728. // inp_pos - contains the positions
  4729. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4730. cb(inp_pos, "inp_pos", -1);
  4731. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4732. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4733. cb(KQ_mask, "KQ_mask", -1);
  4734. // shift the entire K-cache if needed
  4735. if (do_rope_shift) {
  4736. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4737. }
  4738. for (int il = 0; il < n_layer; ++il) {
  4739. struct ggml_tensor * inpSA = inpL;
  4740. cur = llm_build_norm(ctx0, inpL, hparams,
  4741. model.layers[il].attn_norm, NULL,
  4742. LLM_NORM_RMS, cb, il);
  4743. cb(cur, "attn_norm", il);
  4744. // self-attention
  4745. {
  4746. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4747. cb(cur, "wqkv", il);
  4748. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4749. cb(cur, "bqkv", il);
  4750. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4751. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4752. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4753. cb(Qcur, "Qcur", il);
  4754. cb(Kcur, "Kcur", il);
  4755. cb(Vcur, "Vcur", il);
  4756. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4757. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4758. // using mode = 2 for neox mode
  4759. Qcur = ggml_rope_custom(
  4760. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4761. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4762. );
  4763. cb(Qcur, "Qcur", il);
  4764. Kcur = ggml_rope_custom(
  4765. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4766. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4767. );
  4768. cb(Kcur, "Kcur", il);
  4769. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4770. model.layers[il].wo, NULL,
  4771. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4772. cb(cur, "kqv_out", il);
  4773. }
  4774. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4775. cb(ffn_inp, "ffn_inp", il);
  4776. // feed-forward forward
  4777. {
  4778. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4779. model.layers[il].ffn_norm, NULL,
  4780. LLM_NORM_RMS, cb, il);
  4781. cb(cur, "ffn_norm", il);
  4782. cur = llm_build_ffn(ctx0, cur,
  4783. model.layers[il].ffn_up, NULL,
  4784. model.layers[il].ffn_gate, NULL,
  4785. model.layers[il].ffn_down, NULL,
  4786. NULL,
  4787. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4788. cb(cur, "ffn_out", il);
  4789. }
  4790. cur = ggml_add(ctx0, cur, ffn_inp);
  4791. cb(cur, "l_out", il);
  4792. // input for next layer
  4793. inpL = cur;
  4794. }
  4795. cur = inpL;
  4796. cur = llm_build_norm(ctx0, cur, hparams,
  4797. model.output_norm, NULL,
  4798. LLM_NORM_RMS, cb, -1);
  4799. cb(cur, "result_norm", -1);
  4800. // lm_head
  4801. cur = ggml_mul_mat(ctx0, model.output, cur);
  4802. cb(cur, "result_output", -1);
  4803. ggml_build_forward_expand(gf, cur);
  4804. return gf;
  4805. }
  4806. struct ggml_cgraph * build_qwen2() {
  4807. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4808. const int64_t n_embd_head = hparams.n_embd_head_v;
  4809. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4810. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4811. struct ggml_tensor * cur;
  4812. struct ggml_tensor * inpL;
  4813. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4814. cb(inpL, "inp_embd", -1);
  4815. // inp_pos - contains the positions
  4816. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4817. cb(inp_pos, "inp_pos", -1);
  4818. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4819. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4820. cb(KQ_mask, "KQ_mask", -1);
  4821. // shift the entire K-cache if needed
  4822. if (do_rope_shift) {
  4823. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4824. }
  4825. for (int il = 0; il < n_layer; ++il) {
  4826. struct ggml_tensor * inpSA = inpL;
  4827. // norm
  4828. cur = llm_build_norm(ctx0, inpL, hparams,
  4829. model.layers[il].attn_norm, NULL,
  4830. LLM_NORM_RMS, cb, il);
  4831. cb(cur, "attn_norm", il);
  4832. // self-attention
  4833. {
  4834. // compute Q and K and RoPE them
  4835. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4836. cb(Qcur, "Qcur", il);
  4837. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4838. cb(Qcur, "Qcur", il);
  4839. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4840. cb(Kcur, "Kcur", il);
  4841. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4842. cb(Kcur, "Kcur", il);
  4843. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4844. cb(Vcur, "Vcur", il);
  4845. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4846. cb(Vcur, "Vcur", il);
  4847. // these nodes are added to the graph together so that they are not reordered
  4848. // by doing so, the number of splits in the graph is reduced
  4849. ggml_build_forward_expand(gf, Qcur);
  4850. ggml_build_forward_expand(gf, Kcur);
  4851. ggml_build_forward_expand(gf, Vcur);
  4852. Qcur = ggml_rope_custom(
  4853. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4854. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4855. ext_factor, attn_factor, beta_fast, beta_slow
  4856. );
  4857. cb(Qcur, "Qcur", il);
  4858. Kcur = ggml_rope_custom(
  4859. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4860. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4861. ext_factor, attn_factor, beta_fast, beta_slow
  4862. );
  4863. cb(Kcur, "Kcur", il);
  4864. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4865. model.layers[il].wo, model.layers[il].bo,
  4866. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4867. cb(cur, "kqv_out", il);
  4868. }
  4869. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4870. cb(ffn_inp, "ffn_inp", il);
  4871. // feed-forward network
  4872. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4873. model.layers[il].ffn_norm, NULL,
  4874. LLM_NORM_RMS, cb, il);
  4875. cb(cur, "ffn_norm", il);
  4876. cur = llm_build_ffn(ctx0, cur,
  4877. model.layers[il].ffn_up, NULL,
  4878. model.layers[il].ffn_gate, NULL,
  4879. model.layers[il].ffn_down, NULL,
  4880. NULL,
  4881. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4882. cb(cur, "ffn_out", il);
  4883. cur = ggml_add(ctx0, cur, ffn_inp);
  4884. cb(cur, "l_out", il);
  4885. // input for next layer
  4886. inpL = cur;
  4887. }
  4888. cur = inpL;
  4889. cur = llm_build_norm(ctx0, cur, hparams,
  4890. model.output_norm, NULL,
  4891. LLM_NORM_RMS, cb, -1);
  4892. cb(cur, "result_norm", -1);
  4893. // lm_head
  4894. cur = ggml_mul_mat(ctx0, model.output, cur);
  4895. cb(cur, "result_output", -1);
  4896. ggml_build_forward_expand(gf, cur);
  4897. return gf;
  4898. }
  4899. struct ggml_cgraph * build_phi2() {
  4900. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4901. const int64_t n_embd_head = hparams.n_embd_head_v;
  4902. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4903. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4904. struct ggml_tensor * cur;
  4905. struct ggml_tensor * attn_norm_output;
  4906. struct ggml_tensor * ffn_output;
  4907. struct ggml_tensor * inpL;
  4908. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4909. cb(inpL, "inp_embd", -1);
  4910. // inp_pos - contains the positions
  4911. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4912. cb(inp_pos, "inp_pos", -1);
  4913. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4914. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4915. cb(KQ_mask, "KQ_mask", -1);
  4916. // shift the entire K-cache if needed
  4917. if (do_rope_shift) {
  4918. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4919. }
  4920. for (int il = 0; il < n_layer; ++il) {
  4921. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  4922. model.layers[il].attn_norm,
  4923. model.layers[il].attn_norm_b,
  4924. LLM_NORM, cb, il);
  4925. cb(attn_norm_output, "attn_norm", il);
  4926. // self-attention
  4927. {
  4928. struct ggml_tensor * Qcur = nullptr;
  4929. struct ggml_tensor * Kcur = nullptr;
  4930. struct ggml_tensor * Vcur = nullptr;
  4931. if (model.layers[il].wqkv) {
  4932. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  4933. cb(cur, "wqkv", il);
  4934. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4935. cb(cur, "bqkv", il);
  4936. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4937. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4938. 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)));
  4939. } else {
  4940. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  4941. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  4942. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  4943. }
  4944. cb(Qcur, "Qcur", il);
  4945. cb(Kcur, "Kcur", il);
  4946. cb(Vcur, "Vcur", il);
  4947. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4948. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4949. Qcur = ggml_rope_custom(
  4950. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4951. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4952. );
  4953. cb(Qcur, "Qcur", il);
  4954. // with phi2, we scale the Q to avoid precision issues
  4955. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  4956. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  4957. cb(Qcur, "Qcur", il);
  4958. Kcur = ggml_rope_custom(
  4959. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4960. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4961. );
  4962. cb(Kcur, "Kcur", il);
  4963. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4964. model.layers[il].wo, model.layers[il].bo,
  4965. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f, cb, il);
  4966. cb(cur, "kqv_out", il);
  4967. }
  4968. // FF
  4969. {
  4970. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  4971. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4972. NULL, NULL,
  4973. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4974. NULL,
  4975. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4976. cb(ffn_output, "ffn_out", il);
  4977. }
  4978. cur = ggml_add(ctx0, cur, ffn_output);
  4979. cb(cur, "l_out", il);
  4980. cur = ggml_add(ctx0, cur, inpL);
  4981. cb(cur, "l_out", il);
  4982. inpL = cur;
  4983. }
  4984. cur = llm_build_norm(ctx0, inpL, hparams,
  4985. model.output_norm,
  4986. model.output_norm_b,
  4987. LLM_NORM, cb, -1);
  4988. cb(cur, "result_norm", -1);
  4989. cur = ggml_mul_mat(ctx0, model.output, cur);
  4990. cb(cur, "result_output_no_bias", -1);
  4991. cur = ggml_add(ctx0, cur, model.output_b);
  4992. cb(cur, "result_output", -1);
  4993. ggml_build_forward_expand(gf, cur);
  4994. return gf;
  4995. }
  4996. struct ggml_cgraph * build_plamo() {
  4997. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4998. const int64_t n_embd_head = hparams.n_embd_head_v;
  4999. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5000. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5001. struct ggml_tensor * cur;
  5002. struct ggml_tensor * inpL;
  5003. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5004. cb(inpL, "inp_embd", -1);
  5005. // inp_pos - contains the positions
  5006. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5007. cb(inp_pos, "inp_pos", -1);
  5008. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5009. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5010. cb(KQ_mask, "KQ_mask", -1);
  5011. // shift the entire K-cache if needed
  5012. if (do_rope_shift) {
  5013. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5014. }
  5015. for (int il = 0; il < n_layer; ++il) {
  5016. // norm
  5017. cur = llm_build_norm(ctx0, inpL, hparams,
  5018. model.layers[il].attn_norm, NULL,
  5019. LLM_NORM_RMS, cb, il);
  5020. cb(cur, "attn_norm", il);
  5021. struct ggml_tensor * attention_norm = cur;
  5022. // self-attention
  5023. {
  5024. // compute Q and K and RoPE them
  5025. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5026. cb(Qcur, "Qcur", il);
  5027. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5028. cb(Kcur, "Kcur", il);
  5029. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5030. cb(Vcur, "Vcur", il);
  5031. Qcur = ggml_rope_custom(
  5032. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5033. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5034. ext_factor, attn_factor, beta_fast, beta_slow);
  5035. cb(Qcur, "Qcur", il);
  5036. Kcur = ggml_rope_custom(
  5037. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5038. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5039. ext_factor, attn_factor, beta_fast, beta_slow);
  5040. cb(Kcur, "Kcur", il);
  5041. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5042. model.layers[il].wo, NULL,
  5043. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5044. cb(cur, "kqv_out", il);
  5045. }
  5046. struct ggml_tensor * sa_out = cur;
  5047. cur = attention_norm;
  5048. // feed-forward network
  5049. {
  5050. cur = llm_build_ffn(ctx0, cur,
  5051. model.layers[il].ffn_up, NULL,
  5052. model.layers[il].ffn_gate, NULL,
  5053. model.layers[il].ffn_down, NULL,
  5054. NULL,
  5055. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5056. cb(cur, "ffn_out", il);
  5057. }
  5058. cur = ggml_add(ctx0, cur, sa_out);
  5059. cb(cur, "l_out", il);
  5060. cur = ggml_add(ctx0, cur, inpL);
  5061. cb(cur, "l_out", il);
  5062. // input for next layer
  5063. inpL = cur;
  5064. }
  5065. cur = inpL;
  5066. cur = llm_build_norm(ctx0, cur, hparams,
  5067. model.output_norm, NULL,
  5068. LLM_NORM_RMS, cb, -1);
  5069. cb(cur, "result_norm", -1);
  5070. // lm_head
  5071. cur = ggml_mul_mat(ctx0, model.output, cur);
  5072. cb(cur, "result_output", -1);
  5073. ggml_build_forward_expand(gf, cur);
  5074. return gf;
  5075. }
  5076. struct ggml_cgraph * build_gpt2() {
  5077. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5078. const int64_t n_embd_head = hparams.n_embd_head_v;
  5079. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5080. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5081. struct ggml_tensor * cur;
  5082. struct ggml_tensor * pos;
  5083. struct ggml_tensor * inpL;
  5084. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5085. cb(inpL, "inp_embd", -1);
  5086. // inp_pos - contains the positions
  5087. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5088. cb(inp_pos, "inp_pos", -1);
  5089. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5090. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5091. cb(KQ_mask, "KQ_mask", -1);
  5092. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5093. cb(pos, "pos_embd", -1);
  5094. inpL = ggml_add(ctx0, inpL, pos);
  5095. cb(inpL, "inpL", -1);
  5096. for (int il = 0; il < n_layer; ++il) {
  5097. cur = llm_build_norm(ctx0, inpL, hparams,
  5098. model.layers[il].attn_norm,
  5099. model.layers[il].attn_norm_b,
  5100. LLM_NORM, cb, il);
  5101. cb(cur, "attn_norm", il);
  5102. // self-attention
  5103. {
  5104. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5105. cb(cur, "wqkv", il);
  5106. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5107. cb(cur, "bqkv", il);
  5108. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5109. 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)));
  5110. 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)));
  5111. cb(Qcur, "Qcur", il);
  5112. cb(Kcur, "Kcur", il);
  5113. cb(Vcur, "Vcur", il);
  5114. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5115. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5116. model.layers[il].wo, model.layers[il].bo,
  5117. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5118. cb(cur, "kqv_out", il);
  5119. }
  5120. // add the input
  5121. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5122. cb(ffn_inp, "ffn_inp", il);
  5123. // FF
  5124. {
  5125. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5126. model.layers[il].ffn_norm,
  5127. model.layers[il].ffn_norm_b,
  5128. LLM_NORM, cb, il);
  5129. cb(cur, "ffn_norm", il);
  5130. cur = llm_build_ffn(ctx0, cur,
  5131. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5132. NULL, NULL,
  5133. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5134. NULL,
  5135. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5136. cb(cur, "ffn_out", il);
  5137. }
  5138. inpL = ggml_add(ctx0, cur, ffn_inp);
  5139. cb(inpL, "l_out", il);
  5140. }
  5141. cur = llm_build_norm(ctx0, inpL, hparams,
  5142. model.output_norm,
  5143. model.output_norm_b,
  5144. LLM_NORM, cb, -1);
  5145. cb(cur, "result_norm", -1);
  5146. cur = ggml_mul_mat(ctx0, model.output, cur);
  5147. cb(cur, "result_output", -1);
  5148. ggml_build_forward_expand(gf, cur);
  5149. return gf;
  5150. }
  5151. struct ggml_cgraph * build_codeshell() {
  5152. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5153. const int64_t n_embd_head = hparams.n_embd_head_v;
  5154. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5155. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5156. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5157. struct ggml_tensor * cur;
  5158. struct ggml_tensor * inpL;
  5159. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5160. cb(inpL, "inp_embd", -1);
  5161. // inp_pos - contains the positions
  5162. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5163. cb(inp_pos, "inp_pos", -1);
  5164. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5165. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5166. cb(KQ_mask, "KQ_mask", -1);
  5167. // shift the entire K-cache if needed
  5168. if (do_rope_shift) {
  5169. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5170. }
  5171. for (int il = 0; il < n_layer; ++il) {
  5172. cur = llm_build_norm(ctx0, inpL, hparams,
  5173. model.layers[il].attn_norm,
  5174. model.layers[il].attn_norm_b,
  5175. LLM_NORM, cb, il);
  5176. cb(cur, "attn_norm", il);
  5177. // self-attention
  5178. {
  5179. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5180. cb(cur, "wqkv", il);
  5181. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5182. cb(cur, "bqkv", il);
  5183. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5184. 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)));
  5185. 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)));
  5186. cb(tmpq, "tmpq", il);
  5187. cb(tmpk, "tmpk", il);
  5188. cb(Vcur, "Vcur", il);
  5189. struct ggml_tensor * Qcur = ggml_rope_custom(
  5190. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5191. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5192. ext_factor, attn_factor, beta_fast, beta_slow
  5193. );
  5194. cb(Qcur, "Qcur", il);
  5195. struct ggml_tensor * Kcur = ggml_rope_custom(
  5196. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5197. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5198. ext_factor, attn_factor, beta_fast, beta_slow
  5199. );
  5200. cb(Kcur, "Kcur", il);
  5201. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5202. model.layers[il].wo, model.layers[il].bo,
  5203. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5204. cb(cur, "kqv_out", il);
  5205. }
  5206. // add the input
  5207. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5208. cb(ffn_inp, "ffn_inp", il);
  5209. // FF
  5210. {
  5211. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5212. model.layers[il].ffn_norm,
  5213. model.layers[il].ffn_norm_b,
  5214. LLM_NORM, cb, il);
  5215. cb(cur, "ffn_norm", il);
  5216. cur = llm_build_ffn(ctx0, cur,
  5217. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5218. NULL, NULL,
  5219. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5220. NULL,
  5221. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5222. cb(cur, "ffn_out", il);
  5223. }
  5224. inpL = ggml_add(ctx0, cur, ffn_inp);
  5225. cb(inpL, "l_out", il);
  5226. }
  5227. cur = llm_build_norm(ctx0, inpL, hparams,
  5228. model.output_norm,
  5229. model.output_norm_b,
  5230. LLM_NORM, cb, -1);
  5231. cb(cur, "result_norm", -1);
  5232. cur = ggml_mul_mat(ctx0, model.output, cur);
  5233. cb(cur, "result_output", -1);
  5234. ggml_build_forward_expand(gf, cur);
  5235. return gf;
  5236. }
  5237. };
  5238. static struct ggml_cgraph * llama_build_graph(
  5239. llama_context & lctx,
  5240. const llama_batch & batch) {
  5241. const auto & model = lctx.model;
  5242. // check if we should build the worst-case graph (for memory measurement)
  5243. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  5244. // keep track of the input that has already been allocated
  5245. bool alloc_inp_tokens = false;
  5246. bool alloc_inp_embd = false;
  5247. bool alloc_inp_pos = false;
  5248. bool alloc_inp_KQ_mask = false;
  5249. bool alloc_inp_K_shift = false;
  5250. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5251. // TODO: improve handling of input and output tensors, then replace this with ggml_set_name
  5252. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5253. if (il >= 0) {
  5254. ggml_format_name(cur, "%s-%d", name, il);
  5255. } else {
  5256. ggml_set_name(cur, name);
  5257. }
  5258. if (!lctx.cparams.offload_kqv) {
  5259. if (strcmp(name, "kqv_merged_cont") == 0) {
  5260. // all nodes between the KV store and the attention output are run on the CPU
  5261. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  5262. }
  5263. }
  5264. //
  5265. // allocate input tensors and set input data
  5266. //
  5267. if (!alloc_inp_tokens && strcmp(name, "inp_tokens") == 0) {
  5268. ggml_tallocr_alloc(lctx.alloc, cur);
  5269. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.token) {
  5270. const int64_t n_tokens = cur->ne[0];
  5271. ggml_backend_tensor_set(cur, batch.token, 0, n_tokens*ggml_element_size(cur));
  5272. }
  5273. alloc_inp_tokens = true;
  5274. }
  5275. if (!alloc_inp_embd && strcmp(name, "inp_embd") == 0 && batch.embd) {
  5276. ggml_tallocr_alloc(lctx.alloc, cur);
  5277. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.embd) {
  5278. const int64_t n_embd = cur->ne[0];
  5279. const int64_t n_tokens = cur->ne[1];
  5280. ggml_backend_tensor_set(cur, batch.embd, 0, n_tokens*n_embd*ggml_element_size(cur));
  5281. }
  5282. alloc_inp_embd = true;
  5283. }
  5284. if (!alloc_inp_pos && strcmp(name, "inp_pos") == 0) {
  5285. ggml_tallocr_alloc(lctx.alloc, cur);
  5286. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.pos) {
  5287. const int64_t n_tokens = cur->ne[0];
  5288. static_assert(std::is_same<llama_pos, int32_t>::value, "llama_pos must be int32_t");
  5289. ggml_backend_tensor_set(cur, batch.pos, 0, n_tokens*ggml_element_size(cur));
  5290. }
  5291. alloc_inp_pos = true;
  5292. }
  5293. if (!alloc_inp_KQ_mask && strcmp(name, "KQ_mask") == 0) {
  5294. ggml_tallocr_alloc(lctx.alloc, cur);
  5295. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5296. const int64_t n_kv = cur->ne[0];
  5297. const int64_t n_tokens = cur->ne[1];
  5298. float * data;
  5299. if (ggml_backend_buffer_is_host(cur->buffer)) {
  5300. data = (float *) cur->data;
  5301. } else {
  5302. lctx.buf_copy.resize(ggml_nbytes(cur));
  5303. data = (float *) lctx.buf_copy.data();
  5304. }
  5305. for (int h = 0; h < 1; ++h) {
  5306. for (int j = 0; j < n_tokens; ++j) {
  5307. const llama_pos pos = batch.pos[j];
  5308. const llama_seq_id seq_id = batch.seq_id[j][0];
  5309. for (int i = 0; i < n_kv; ++i) {
  5310. float f;
  5311. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  5312. f = -INFINITY;
  5313. } else {
  5314. f = 0;
  5315. }
  5316. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  5317. }
  5318. }
  5319. }
  5320. if (data != cur->data) {
  5321. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  5322. }
  5323. }
  5324. alloc_inp_KQ_mask = true;
  5325. }
  5326. if (!alloc_inp_K_shift && strcmp(name, "K_shift") == 0) {
  5327. ggml_tallocr_alloc(lctx.alloc, cur);
  5328. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5329. const int64_t n_ctx = cur->ne[0];
  5330. int32_t * data;
  5331. if (ggml_backend_buffer_is_host(cur->buffer)) {
  5332. data = (int32_t *) cur->data;
  5333. } else {
  5334. lctx.buf_copy.resize(ggml_nbytes(cur));
  5335. data = (int32_t *) lctx.buf_copy.data();
  5336. }
  5337. for (int i = 0; i < n_ctx; ++i) {
  5338. data[i] = lctx.kv_self.cells[i].delta;
  5339. }
  5340. if (data != cur->data) {
  5341. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  5342. }
  5343. }
  5344. alloc_inp_K_shift = true;
  5345. }
  5346. };
  5347. struct ggml_cgraph * result = NULL;
  5348. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5349. llm.init();
  5350. switch (model.arch) {
  5351. case LLM_ARCH_LLAMA:
  5352. {
  5353. result = llm.build_llama();
  5354. } break;
  5355. case LLM_ARCH_BAICHUAN:
  5356. {
  5357. result = llm.build_baichuan();
  5358. } break;
  5359. case LLM_ARCH_FALCON:
  5360. {
  5361. result = llm.build_falcon();
  5362. } break;
  5363. case LLM_ARCH_STARCODER:
  5364. {
  5365. result = llm.build_starcoder();
  5366. } break;
  5367. case LLM_ARCH_PERSIMMON:
  5368. {
  5369. result = llm.build_persimmon();
  5370. } break;
  5371. case LLM_ARCH_REFACT:
  5372. {
  5373. result = llm.build_refact();
  5374. } break;
  5375. case LLM_ARCH_BLOOM:
  5376. {
  5377. result = llm.build_bloom();
  5378. } break;
  5379. case LLM_ARCH_MPT:
  5380. {
  5381. result = llm.build_mpt();
  5382. } break;
  5383. case LLM_ARCH_STABLELM:
  5384. {
  5385. result = llm.build_stablelm();
  5386. } break;
  5387. case LLM_ARCH_QWEN:
  5388. {
  5389. result = llm.build_qwen();
  5390. } break;
  5391. case LLM_ARCH_QWEN2:
  5392. {
  5393. result = llm.build_qwen2();
  5394. } break;
  5395. case LLM_ARCH_PHI2:
  5396. {
  5397. result = llm.build_phi2();
  5398. } break;
  5399. case LLM_ARCH_PLAMO:
  5400. {
  5401. result = llm.build_plamo();
  5402. } break;
  5403. case LLM_ARCH_GPT2:
  5404. {
  5405. result = llm.build_gpt2();
  5406. } break;
  5407. case LLM_ARCH_CODESHELL:
  5408. {
  5409. result = llm.build_codeshell();
  5410. } break;
  5411. default:
  5412. GGML_ASSERT(false);
  5413. }
  5414. llm.free();
  5415. return result;
  5416. }
  5417. // decode a batch of tokens by evaluating the transformer
  5418. //
  5419. // - lctx: llama context
  5420. // - batch: batch to evaluate
  5421. //
  5422. // return 0 on success
  5423. // return positive int on warning
  5424. // return negative int on error
  5425. //
  5426. static int llama_decode_internal(
  5427. llama_context & lctx,
  5428. llama_batch batch) {
  5429. const uint32_t n_tokens = batch.n_tokens;
  5430. if (n_tokens == 0) {
  5431. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5432. return -1;
  5433. }
  5434. const auto & model = lctx.model;
  5435. const auto & hparams = model.hparams;
  5436. const auto & cparams = lctx.cparams;
  5437. const auto n_batch = cparams.n_batch;
  5438. GGML_ASSERT(n_tokens <= n_batch);
  5439. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5440. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5441. const int64_t t_start_us = ggml_time_us();
  5442. #ifdef GGML_USE_MPI
  5443. // TODO: needs fix after #3228
  5444. GGML_ASSERT(false && "not implemented");
  5445. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5446. #endif
  5447. GGML_ASSERT(n_threads > 0);
  5448. auto & kv_self = lctx.kv_self;
  5449. const int64_t n_embd = hparams.n_embd;
  5450. const int64_t n_vocab = hparams.n_vocab;
  5451. // helpers for smoother batch API transition
  5452. // after deprecating the llama_eval calls, these will be removed
  5453. std::vector<llama_pos> pos;
  5454. std::vector<int32_t> n_seq_id;
  5455. std::vector<llama_seq_id *> seq_id_arr;
  5456. std::vector<std::vector<llama_seq_id>> seq_id;
  5457. if (batch.pos == nullptr) {
  5458. pos.resize(n_tokens);
  5459. for (uint32_t i = 0; i < n_tokens; i++) {
  5460. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5461. }
  5462. batch.pos = pos.data();
  5463. }
  5464. if (batch.seq_id == nullptr) {
  5465. n_seq_id.resize(n_tokens);
  5466. seq_id.resize(n_tokens);
  5467. seq_id_arr.resize(n_tokens);
  5468. for (uint32_t i = 0; i < n_tokens; i++) {
  5469. n_seq_id[i] = 1;
  5470. seq_id[i].resize(1);
  5471. seq_id[i][0] = batch.all_seq_id;
  5472. seq_id_arr[i] = seq_id[i].data();
  5473. }
  5474. batch.n_seq_id = n_seq_id.data();
  5475. batch.seq_id = seq_id_arr.data();
  5476. }
  5477. // if we have enough unused cells before the current head ->
  5478. // better to start searching from the beginning of the cache, hoping to fill it
  5479. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5480. kv_self.head = 0;
  5481. }
  5482. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5483. return 1;
  5484. }
  5485. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5486. // after enough generations, the benefit from this heuristic disappears
  5487. // if we start defragmenting the cache, the benefit from this will be more important
  5488. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5489. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5490. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5491. ggml_backend_sched_reset(lctx.sched);
  5492. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  5493. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5494. // the output is always the last tensor in the graph
  5495. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5496. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5497. // the embeddings could be the second to last tensor, or the third to last tensor
  5498. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5499. if (strcmp(embeddings->name, "result_norm") != 0) {
  5500. embeddings = gf->nodes[gf->n_nodes - 3];
  5501. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5502. }
  5503. // 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);
  5504. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5505. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5506. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5507. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5508. // with the BLAS calls. need a better solution
  5509. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5510. n_threads = std::min(4, n_threads);
  5511. }
  5512. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 1;
  5513. if (ggml_cpu_has_cublas() && fully_offloaded) {
  5514. n_threads = 1;
  5515. }
  5516. #ifdef GGML_USE_MPI
  5517. const int64_t n_layer = hparams.n_layer;
  5518. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5519. #endif
  5520. #ifdef GGML_USE_METAL
  5521. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5522. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5523. }
  5524. #endif
  5525. if (lctx.backend_cpu != nullptr) {
  5526. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5527. }
  5528. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5529. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5530. #ifdef GGML_USE_MPI
  5531. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5532. #endif
  5533. // update the kv ring buffer
  5534. {
  5535. if (kv_self.has_shift) {
  5536. kv_self.has_shift = false;
  5537. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5538. kv_self.cells[i].delta = 0;
  5539. }
  5540. }
  5541. kv_self.head += n_tokens;
  5542. // Ensure kv cache head points to a valid index.
  5543. if (kv_self.head >= kv_self.size) {
  5544. kv_self.head = 0;
  5545. }
  5546. }
  5547. #ifdef GGML_PERF
  5548. // print timing information per ggml operation (for debugging purposes)
  5549. // requires GGML_PERF to be defined
  5550. ggml_graph_print(gf);
  5551. #endif
  5552. // plot the computation graph in dot format (for debugging purposes)
  5553. //if (n_past%100 == 0) {
  5554. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5555. //}
  5556. // extract logits
  5557. // TODO: do not compute and extract logits if only embeddings are needed
  5558. // need to update the graphs to skip "result_output"
  5559. {
  5560. auto & logits_out = lctx.logits;
  5561. #ifndef NDEBUG
  5562. auto & logits_valid = lctx.logits_valid;
  5563. logits_valid.clear();
  5564. logits_valid.resize(n_tokens);
  5565. logits_out.clear();
  5566. #endif
  5567. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5568. GGML_ASSERT(res_backend != nullptr);
  5569. if (batch.logits) {
  5570. logits_out.resize(n_vocab * n_tokens);
  5571. for (uint32_t i = 0; i < n_tokens; i++) {
  5572. if (batch.logits[i] == 0) {
  5573. continue;
  5574. }
  5575. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5576. #ifndef NDEBUG
  5577. logits_valid[i] = true;
  5578. #endif
  5579. }
  5580. } else if (lctx.logits_all) {
  5581. logits_out.resize(n_vocab * n_tokens);
  5582. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5583. #ifndef NDEBUG
  5584. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5585. #endif
  5586. } else {
  5587. logits_out.resize(n_vocab);
  5588. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5589. #ifndef NDEBUG
  5590. logits_valid[0] = true;
  5591. #endif
  5592. }
  5593. ggml_backend_synchronize(res_backend);
  5594. }
  5595. // extract embeddings
  5596. if (!lctx.embedding.empty()) {
  5597. auto & embedding_out = lctx.embedding;
  5598. embedding_out.resize(n_embd);
  5599. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5600. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5601. ggml_backend_synchronize(embeddings_backend);
  5602. }
  5603. // measure the performance only for the single-token evals
  5604. if (n_tokens == 1) {
  5605. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5606. lctx.n_eval++;
  5607. }
  5608. else if (n_tokens > 1) {
  5609. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5610. lctx.n_p_eval += n_tokens;
  5611. }
  5612. // get a more accurate load time, upon first eval
  5613. // TODO: fix this
  5614. if (!lctx.has_evaluated_once) {
  5615. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5616. lctx.has_evaluated_once = true;
  5617. }
  5618. return 0;
  5619. }
  5620. //
  5621. // tokenizer
  5622. //
  5623. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5624. return vocab.type;
  5625. }
  5626. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5627. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5628. }
  5629. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5630. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5631. }
  5632. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5633. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5634. }
  5635. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5636. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5637. }
  5638. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5639. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5640. }
  5641. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5642. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5643. const auto& token_data = vocab.id_to_token.at(id);
  5644. switch (llama_vocab_get_type(vocab)) {
  5645. case LLAMA_VOCAB_TYPE_SPM: {
  5646. auto buf = token_data.text.substr(3, 2);
  5647. return strtol(buf.c_str(), NULL, 16);
  5648. }
  5649. case LLAMA_VOCAB_TYPE_BPE: {
  5650. GGML_ASSERT(false);
  5651. return unicode_to_bytes_bpe(token_data.text);
  5652. }
  5653. default:
  5654. GGML_ASSERT(false);
  5655. }
  5656. }
  5657. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5658. static const char * hex = "0123456789ABCDEF";
  5659. switch (llama_vocab_get_type(vocab)) {
  5660. case LLAMA_VOCAB_TYPE_SPM: {
  5661. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5662. return vocab.token_to_id.at(buf);
  5663. }
  5664. case LLAMA_VOCAB_TYPE_BPE: {
  5665. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5666. }
  5667. default:
  5668. GGML_ASSERT(false);
  5669. }
  5670. }
  5671. static void llama_escape_whitespace(std::string & text) {
  5672. replace_all(text, " ", "\xe2\x96\x81");
  5673. }
  5674. static void llama_unescape_whitespace(std::string & word) {
  5675. replace_all(word, "\xe2\x96\x81", " ");
  5676. }
  5677. struct llm_symbol {
  5678. using index = int;
  5679. index prev;
  5680. index next;
  5681. const char * text;
  5682. size_t n;
  5683. };
  5684. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5685. // SPM tokenizer
  5686. // original implementation:
  5687. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5688. struct llm_bigram_spm {
  5689. struct comparator {
  5690. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5691. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5692. }
  5693. };
  5694. using queue_storage = std::vector<llm_bigram_spm>;
  5695. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5696. llm_symbol::index left;
  5697. llm_symbol::index right;
  5698. float score;
  5699. size_t size;
  5700. };
  5701. struct llm_tokenizer_spm {
  5702. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5703. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5704. // split string into utf8 chars
  5705. int index = 0;
  5706. size_t offs = 0;
  5707. while (offs < text.size()) {
  5708. llm_symbol sym;
  5709. size_t len = utf8_len(text[offs]);
  5710. sym.text = text.c_str() + offs;
  5711. sym.n = std::min(len, text.size() - offs);
  5712. offs += sym.n;
  5713. sym.prev = index - 1;
  5714. sym.next = offs == text.size() ? -1 : index + 1;
  5715. index++;
  5716. symbols.emplace_back(sym);
  5717. }
  5718. // seed the work queue with all possible 2-character tokens.
  5719. for (size_t i = 1; i < symbols.size(); ++i) {
  5720. try_add_bigram(i - 1, i);
  5721. }
  5722. // keep substituting the highest frequency pairs for as long as we can.
  5723. while (!work_queue.empty()) {
  5724. auto bigram = work_queue.top();
  5725. work_queue.pop();
  5726. auto & left_sym = symbols[bigram.left];
  5727. auto & right_sym = symbols[bigram.right];
  5728. // if one of the symbols already got merged, skip it.
  5729. if (left_sym.n == 0 || right_sym.n == 0 ||
  5730. left_sym.n + right_sym.n != bigram.size) {
  5731. continue;
  5732. }
  5733. // merge the right sym into the left one
  5734. left_sym.n += right_sym.n;
  5735. right_sym.n = 0;
  5736. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5737. // remove the right sym from the chain
  5738. left_sym.next = right_sym.next;
  5739. if (right_sym.next >= 0) {
  5740. symbols[right_sym.next].prev = bigram.left;
  5741. }
  5742. // find more substitutions
  5743. try_add_bigram(left_sym.prev, bigram.left);
  5744. try_add_bigram(bigram.left, left_sym.next);
  5745. }
  5746. for (int i = 0; i != -1; i = symbols[i].next) {
  5747. auto & symbol = symbols[i];
  5748. resegment(symbol, output);
  5749. }
  5750. }
  5751. private:
  5752. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5753. auto text = std::string(symbol.text, symbol.n);
  5754. auto token = vocab.token_to_id.find(text);
  5755. // Do we need to support is_unused?
  5756. if (token != vocab.token_to_id.end()) {
  5757. output.push_back((*token).second);
  5758. return;
  5759. }
  5760. const auto p = rev_merge.find(text);
  5761. if (p == rev_merge.end()) {
  5762. // output any symbols that did not form tokens as bytes.
  5763. for (int j = 0; j < (int)symbol.n; ++j) {
  5764. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5765. output.push_back(token_id);
  5766. }
  5767. return;
  5768. }
  5769. resegment(symbols[p->second.first], output);
  5770. resegment(symbols[p->second.second], output);
  5771. }
  5772. void try_add_bigram(int left, int right) {
  5773. if (left == -1 || right == -1) {
  5774. return;
  5775. }
  5776. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5777. auto token = vocab.token_to_id.find(text);
  5778. if (token == vocab.token_to_id.end()) {
  5779. return;
  5780. }
  5781. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5782. return;
  5783. }
  5784. const auto & tok_data = vocab.id_to_token[(*token).second];
  5785. llm_bigram_spm bigram;
  5786. bigram.left = left;
  5787. bigram.right = right;
  5788. bigram.score = tok_data.score;
  5789. bigram.size = text.size();
  5790. work_queue.push(bigram);
  5791. // Do we need to support is_unused?
  5792. rev_merge[text] = std::make_pair(left, right);
  5793. }
  5794. const llama_vocab & vocab;
  5795. std::vector<llm_symbol> symbols;
  5796. llm_bigram_spm::queue work_queue;
  5797. std::map<std::string, std::pair<int, int>> rev_merge;
  5798. };
  5799. // BPE tokenizer
  5800. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5801. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5802. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5803. struct llm_bigram_bpe {
  5804. struct comparator {
  5805. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5806. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5807. }
  5808. };
  5809. using queue_storage = std::vector<llm_bigram_bpe>;
  5810. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5811. llm_symbol::index left;
  5812. llm_symbol::index right;
  5813. std::string text;
  5814. int rank;
  5815. size_t size;
  5816. };
  5817. struct llm_tokenizer_bpe {
  5818. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5819. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5820. int final_prev_index = -1;
  5821. auto word_collection = bpe_gpt2_preprocess(text);
  5822. symbols_final.clear();
  5823. for (auto & word : word_collection) {
  5824. work_queue = llm_bigram_bpe::queue();
  5825. symbols.clear();
  5826. int index = 0;
  5827. size_t offset = 0;
  5828. while (offset < word.size()) {
  5829. llm_symbol sym;
  5830. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  5831. sym.text = word.c_str() + offset;
  5832. sym.n = char_len;
  5833. offset += sym.n;
  5834. sym.prev = index - 1;
  5835. sym.next = offset == word.size() ? -1 : index + 1;
  5836. index++;
  5837. symbols.emplace_back(sym);
  5838. }
  5839. for (size_t i = 1; i < symbols.size(); ++i) {
  5840. add_new_bigram(i - 1, i);
  5841. }
  5842. // build token(s)
  5843. while (!work_queue.empty()) {
  5844. auto bigram = work_queue.top();
  5845. work_queue.pop();
  5846. auto & left_symbol = symbols[bigram.left];
  5847. auto & right_symbol = symbols[bigram.right];
  5848. if (left_symbol.n == 0 || right_symbol.n == 0) {
  5849. continue;
  5850. }
  5851. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  5852. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  5853. if (left_token + right_token != bigram.text) {
  5854. continue; // Skip this bigram if it's outdated
  5855. }
  5856. // merge the right sym into the left one
  5857. left_symbol.n += right_symbol.n;
  5858. right_symbol.n = 0;
  5859. // remove the right sym from the chain
  5860. left_symbol.next = right_symbol.next;
  5861. if (right_symbol.next >= 0) {
  5862. symbols[right_symbol.next].prev = bigram.left;
  5863. }
  5864. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  5865. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  5866. }
  5867. // add the fnished tokens to the final list keeping correct order for next and prev
  5868. for (auto & sym : symbols) {
  5869. if (sym.n > 0) {
  5870. sym.prev = final_prev_index;
  5871. sym.next = -1;
  5872. if (final_prev_index != -1) {
  5873. symbols_final[final_prev_index].next = symbols_final.size();
  5874. }
  5875. symbols_final.emplace_back(sym);
  5876. final_prev_index = symbols_final.size() - 1;
  5877. }
  5878. }
  5879. }
  5880. symbols = symbols_final;
  5881. if (!symbols.empty()) {
  5882. for (int i = 0; i != -1; i = symbols[i].next) {
  5883. auto & symbol = symbols[i];
  5884. if (symbol.n == 0) {
  5885. continue;
  5886. }
  5887. const std::string str = std::string(symbol.text, symbol.n);
  5888. const auto token = vocab.token_to_id.find(str);
  5889. if (token == vocab.token_to_id.end()) {
  5890. for (auto j = str.begin(); j != str.end(); ++j) {
  5891. std::string byte_str(1, *j);
  5892. auto token_multibyte = vocab.token_to_id.find(byte_str);
  5893. if (token_multibyte == vocab.token_to_id.end()) {
  5894. throw std::runtime_error("ERROR: byte not found in vocab");
  5895. }
  5896. output.push_back((*token_multibyte).second);
  5897. }
  5898. } else {
  5899. output.push_back((*token).second);
  5900. }
  5901. }
  5902. }
  5903. }
  5904. private:
  5905. void add_new_bigram(int left, int right) {
  5906. if (left == -1 || right == -1) {
  5907. return;
  5908. }
  5909. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  5910. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  5911. int rank_found = -1;
  5912. rank_found = vocab.find_bpe_rank(left_token, right_token);
  5913. if (rank_found < 0) {
  5914. return;
  5915. }
  5916. llm_bigram_bpe bigram;
  5917. bigram.left = left;
  5918. bigram.right = right;
  5919. bigram.text = left_token + right_token;
  5920. bigram.size = left_token.size() + right_token.size();
  5921. bigram.rank = rank_found;
  5922. work_queue.push(bigram);
  5923. }
  5924. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  5925. std::vector<std::string> bpe_words;
  5926. std::vector<std::string> bpe_encoded_words;
  5927. std::string token = "";
  5928. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  5929. bool collecting_numeric = false;
  5930. bool collecting_letter = false;
  5931. bool collecting_special = false;
  5932. bool collecting_whitespace_lookahead = false;
  5933. bool collecting = false;
  5934. std::vector<std::string> text_utf;
  5935. text_utf.reserve(text.size());
  5936. bpe_words.reserve(text.size());
  5937. bpe_encoded_words.reserve(text.size());
  5938. auto cps = codepoints_from_utf8(text);
  5939. for (size_t i = 0; i < cps.size(); ++i)
  5940. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  5941. for (int i = 0; i < (int)text_utf.size(); i++) {
  5942. const std::string & utf_char = text_utf[i];
  5943. bool split_condition = false;
  5944. int bytes_remain = text_utf.size() - i;
  5945. // forward backward lookups
  5946. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  5947. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  5948. // handling contractions
  5949. if (!split_condition && bytes_remain >= 2) {
  5950. // 's|'t|'m|'d
  5951. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  5952. split_condition = true;
  5953. }
  5954. if (split_condition) {
  5955. if (token.size()) {
  5956. bpe_words.emplace_back(token); // push previous content as token
  5957. }
  5958. token = utf_char + utf_char_next;
  5959. bpe_words.emplace_back(token);
  5960. token = "";
  5961. i++;
  5962. continue;
  5963. }
  5964. }
  5965. if (!split_condition && bytes_remain >= 3) {
  5966. // 're|'ve|'ll
  5967. if (utf_char == "\'" && (
  5968. (utf_char_next == "r" && utf_char_next_next == "e") ||
  5969. (utf_char_next == "v" && utf_char_next_next == "e") ||
  5970. (utf_char_next == "l" && utf_char_next_next == "l"))
  5971. ) {
  5972. split_condition = true;
  5973. }
  5974. if (split_condition) {
  5975. // current token + next token can be defined
  5976. if (token.size()) {
  5977. bpe_words.emplace_back(token); // push previous content as token
  5978. }
  5979. token = utf_char + utf_char_next + utf_char_next_next;
  5980. bpe_words.emplace_back(token); // the contraction
  5981. token = "";
  5982. i += 2;
  5983. continue;
  5984. }
  5985. }
  5986. if (!split_condition && !collecting) {
  5987. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  5988. collecting_letter = true;
  5989. collecting = true;
  5990. }
  5991. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5992. collecting_numeric = true;
  5993. collecting = true;
  5994. }
  5995. else if (
  5996. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  5997. (!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)
  5998. ) {
  5999. collecting_special = true;
  6000. collecting = true;
  6001. }
  6002. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  6003. collecting_whitespace_lookahead = true;
  6004. collecting = true;
  6005. }
  6006. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  6007. split_condition = true;
  6008. }
  6009. }
  6010. else if (!split_condition && collecting) {
  6011. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  6012. split_condition = true;
  6013. }
  6014. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  6015. split_condition = true;
  6016. }
  6017. 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)) {
  6018. split_condition = true;
  6019. }
  6020. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6021. split_condition = true;
  6022. }
  6023. }
  6024. if (utf_char_next == "") {
  6025. split_condition = true; // final
  6026. token += utf_char;
  6027. }
  6028. if (split_condition) {
  6029. if (token.size()) {
  6030. bpe_words.emplace_back(token);
  6031. }
  6032. token = utf_char;
  6033. collecting = false;
  6034. collecting_letter = false;
  6035. collecting_numeric = false;
  6036. collecting_special = false;
  6037. collecting_whitespace_lookahead = false;
  6038. }
  6039. else {
  6040. token += utf_char;
  6041. }
  6042. }
  6043. for (std::string & word : bpe_words) {
  6044. std::string encoded_token = "";
  6045. for (char & c : word) {
  6046. encoded_token += bytes_to_unicode_bpe(c);
  6047. }
  6048. bpe_encoded_words.emplace_back(encoded_token);
  6049. }
  6050. return bpe_encoded_words;
  6051. }
  6052. const llama_vocab & vocab;
  6053. std::vector<llm_symbol> symbols;
  6054. std::vector<llm_symbol> symbols_final;
  6055. llm_bigram_bpe::queue work_queue;
  6056. };
  6057. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  6058. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6059. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6060. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6061. struct fragment_buffer_variant{
  6062. fragment_buffer_variant(llama_vocab::id _token)
  6063. :
  6064. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6065. token(_token),
  6066. raw_text(_dummy),
  6067. offset(0),
  6068. length(0){}
  6069. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6070. :
  6071. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6072. token((llama_vocab::id)-1),
  6073. raw_text(_raw_text),
  6074. offset(_offset),
  6075. length(_length){
  6076. GGML_ASSERT( _offset >= 0 );
  6077. GGML_ASSERT( _length >= 1 );
  6078. GGML_ASSERT( offset + length <= raw_text.length() );
  6079. }
  6080. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6081. const llama_vocab::id token;
  6082. const std::string _dummy;
  6083. const std::string & raw_text;
  6084. const uint64_t offset;
  6085. const uint64_t length;
  6086. };
  6087. // #define PRETOKENIZERDEBUG
  6088. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  6089. {
  6090. // for each special token
  6091. for (const auto & st: vocab.special_tokens_cache) {
  6092. const auto & special_token = st.first;
  6093. const auto & special_id = st.second;
  6094. // for each text fragment
  6095. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  6096. while (it != buffer.end()) {
  6097. auto & fragment = (*it);
  6098. // if a fragment is text ( not yet processed )
  6099. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  6100. auto * raw_text = &(fragment.raw_text);
  6101. auto raw_text_base_offset = fragment.offset;
  6102. auto raw_text_base_length = fragment.length;
  6103. // loop over the text
  6104. while (true) {
  6105. // find the first occurrence of a given special token in this fragment
  6106. // passing offset argument only limit the "search area" but match coordinates
  6107. // are still relative to the source full raw_text
  6108. auto match = raw_text->find(special_token, raw_text_base_offset);
  6109. // no occurrences found, stop processing this fragment for a given special token
  6110. if (match == std::string::npos) break;
  6111. // check if match is within bounds of offset <-> length
  6112. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  6113. #ifdef PRETOKENIZERDEBUG
  6114. 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());
  6115. #endif
  6116. auto source = std::distance(buffer.begin(), it);
  6117. // if match is further than base offset
  6118. // then we have some text to the left of it
  6119. if (match > raw_text_base_offset) {
  6120. // left
  6121. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  6122. const int64_t left_reminder_length = match - raw_text_base_offset;
  6123. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  6124. #ifdef PRETOKENIZERDEBUG
  6125. 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());
  6126. #endif
  6127. it++;
  6128. }
  6129. // special token
  6130. buffer.emplace_after(it, special_id);
  6131. it++;
  6132. // right
  6133. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  6134. const int64_t right_reminder_offset = match + special_token.length();
  6135. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  6136. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  6137. #ifdef PRETOKENIZERDEBUG
  6138. 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());
  6139. #endif
  6140. it++;
  6141. if (source == 0) {
  6142. buffer.erase_after(buffer.before_begin());
  6143. } else {
  6144. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6145. }
  6146. // repeat for the right side
  6147. raw_text_base_offset = right_reminder_offset;
  6148. raw_text_base_length = right_reminder_length;
  6149. #ifdef PRETOKENIZERDEBUG
  6150. 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());
  6151. #endif
  6152. } else {
  6153. if (source == 0) {
  6154. buffer.erase_after(buffer.before_begin());
  6155. } else {
  6156. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6157. }
  6158. break;
  6159. }
  6160. }
  6161. }
  6162. it++;
  6163. }
  6164. }
  6165. }
  6166. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  6167. std::vector<llama_vocab::id> output;
  6168. // OG tokenizer behavior:
  6169. //
  6170. // tokenizer.encode('', add_bos=True) returns [1]
  6171. // tokenizer.encode('', add_bos=False) returns []
  6172. if (bos && vocab.special_bos_id != -1) {
  6173. output.push_back(vocab.special_bos_id);
  6174. }
  6175. if (raw_text.empty()) {
  6176. return output;
  6177. }
  6178. std::forward_list<fragment_buffer_variant> fragment_buffer;
  6179. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  6180. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  6181. switch (vocab.type) {
  6182. case LLAMA_VOCAB_TYPE_SPM:
  6183. {
  6184. for (const auto & fragment: fragment_buffer)
  6185. {
  6186. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6187. {
  6188. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  6189. // TODO: It's likely possible to get rid of this string copy entirely
  6190. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  6191. // and passing 'add space prefix' as bool argument
  6192. //
  6193. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6194. if (&fragment == &fragment_buffer.front()) {
  6195. raw_text = " " + raw_text; // prefix with space if the first token is not special
  6196. }
  6197. #ifdef PRETOKENIZERDEBUG
  6198. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6199. #endif
  6200. llm_tokenizer_spm tokenizer(vocab);
  6201. llama_escape_whitespace(raw_text);
  6202. tokenizer.tokenize(raw_text, output);
  6203. }
  6204. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6205. {
  6206. output.push_back(fragment.token);
  6207. }
  6208. }
  6209. } break;
  6210. case LLAMA_VOCAB_TYPE_BPE:
  6211. {
  6212. for (const auto & fragment: fragment_buffer)
  6213. {
  6214. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6215. {
  6216. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6217. #ifdef PRETOKENIZERDEBUG
  6218. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6219. #endif
  6220. llm_tokenizer_bpe tokenizer(vocab);
  6221. tokenizer.tokenize(raw_text, output);
  6222. }
  6223. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6224. {
  6225. output.push_back(fragment.token);
  6226. }
  6227. }
  6228. } break;
  6229. }
  6230. return output;
  6231. }
  6232. //
  6233. // grammar - internal
  6234. //
  6235. struct llama_partial_utf8 {
  6236. uint32_t value; // bit value so far (unshifted)
  6237. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  6238. };
  6239. struct llama_grammar {
  6240. const std::vector<std::vector<llama_grammar_element>> rules;
  6241. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6242. // buffer for partially generated UTF-8 sequence from accepted tokens
  6243. llama_partial_utf8 partial_utf8;
  6244. };
  6245. struct llama_grammar_candidate {
  6246. size_t index;
  6247. const uint32_t * code_points;
  6248. llama_partial_utf8 partial_utf8;
  6249. };
  6250. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  6251. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  6252. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  6253. const std::string & src,
  6254. llama_partial_utf8 partial_start) {
  6255. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  6256. const char * pos = src.c_str();
  6257. std::vector<uint32_t> code_points;
  6258. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  6259. code_points.reserve(src.size() + 1);
  6260. uint32_t value = partial_start.value;
  6261. int n_remain = partial_start.n_remain;
  6262. // continue previous decode, if applicable
  6263. while (*pos != 0 && n_remain > 0) {
  6264. uint8_t next_byte = static_cast<uint8_t>(*pos);
  6265. if ((next_byte >> 6) != 2) {
  6266. // invalid sequence, abort
  6267. code_points.push_back(0);
  6268. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  6269. }
  6270. value = (value << 6) + (next_byte & 0x3F);
  6271. ++pos;
  6272. --n_remain;
  6273. }
  6274. if (partial_start.n_remain > 0 && n_remain == 0) {
  6275. code_points.push_back(value);
  6276. }
  6277. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  6278. while (*pos != 0) {
  6279. uint8_t first_byte = static_cast<uint8_t>(*pos);
  6280. uint8_t highbits = first_byte >> 4;
  6281. n_remain = lookup[highbits] - 1;
  6282. if (n_remain < 0) {
  6283. // invalid sequence, abort
  6284. code_points.clear();
  6285. code_points.push_back(0);
  6286. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  6287. }
  6288. uint8_t mask = (1 << (7 - n_remain)) - 1;
  6289. value = first_byte & mask;
  6290. ++pos;
  6291. while (*pos != 0 && n_remain > 0) {
  6292. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  6293. ++pos;
  6294. --n_remain;
  6295. }
  6296. if (n_remain == 0) {
  6297. code_points.push_back(value);
  6298. }
  6299. }
  6300. code_points.push_back(0);
  6301. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  6302. }
  6303. // returns true iff pos points to the end of one of the definitions of a rule
  6304. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  6305. switch (pos->type) {
  6306. case LLAMA_GRETYPE_END: return true; // NOLINT
  6307. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  6308. default: return false;
  6309. }
  6310. }
  6311. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  6312. // asserts that pos is pointing to a char range element
  6313. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  6314. const llama_grammar_element * pos,
  6315. const uint32_t chr) {
  6316. bool found = false;
  6317. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6318. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  6319. do {
  6320. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6321. // inclusive range, e.g. [a-z]
  6322. found = found || (pos->value <= chr && chr <= pos[1].value);
  6323. pos += 2;
  6324. } else {
  6325. // exact char match, e.g. [a] or "a"
  6326. found = found || pos->value == chr;
  6327. pos += 1;
  6328. }
  6329. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6330. return std::make_pair(found == is_positive_char, pos);
  6331. }
  6332. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  6333. // range at pos (regular or inverse range)
  6334. // asserts that pos is pointing to a char range element
  6335. static bool llama_grammar_match_partial_char(
  6336. const llama_grammar_element * pos,
  6337. const llama_partial_utf8 partial_utf8) {
  6338. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6339. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6340. uint32_t partial_value = partial_utf8.value;
  6341. int n_remain = partial_utf8.n_remain;
  6342. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6343. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6344. return false;
  6345. }
  6346. // range of possible code points this partial UTF-8 sequence could complete to
  6347. uint32_t low = partial_value << (n_remain * 6);
  6348. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6349. if (low == 0) {
  6350. if (n_remain == 2) {
  6351. low = 1 << 11;
  6352. } else if (n_remain == 3) {
  6353. low = 1 << 16;
  6354. }
  6355. }
  6356. do {
  6357. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6358. // inclusive range, e.g. [a-z]
  6359. if (pos->value <= high && low <= pos[1].value) {
  6360. return is_positive_char;
  6361. }
  6362. pos += 2;
  6363. } else {
  6364. // exact char match, e.g. [a] or "a"
  6365. if (low <= pos->value && pos->value <= high) {
  6366. return is_positive_char;
  6367. }
  6368. pos += 1;
  6369. }
  6370. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6371. return !is_positive_char;
  6372. }
  6373. // transforms a grammar pushdown stack into N possible stacks, all ending
  6374. // at a character range (terminal element)
  6375. static void llama_grammar_advance_stack(
  6376. const std::vector<std::vector<llama_grammar_element>> & rules,
  6377. const std::vector<const llama_grammar_element *> & stack,
  6378. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6379. if (stack.empty()) {
  6380. new_stacks.emplace_back(stack);
  6381. return;
  6382. }
  6383. const llama_grammar_element * pos = stack.back();
  6384. switch (pos->type) {
  6385. case LLAMA_GRETYPE_RULE_REF: {
  6386. const size_t rule_id = static_cast<size_t>(pos->value);
  6387. const llama_grammar_element * subpos = rules[rule_id].data();
  6388. do {
  6389. // init new stack without the top (pos)
  6390. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6391. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6392. // if this rule ref is followed by another element, add that to stack
  6393. new_stack.push_back(pos + 1);
  6394. }
  6395. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6396. // if alternate is nonempty, add to stack
  6397. new_stack.push_back(subpos);
  6398. }
  6399. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6400. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6401. // scan to end of alternate def
  6402. subpos++;
  6403. }
  6404. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6405. // there's another alternate def of this rule to process
  6406. subpos++;
  6407. } else {
  6408. break;
  6409. }
  6410. } while (true);
  6411. break;
  6412. }
  6413. case LLAMA_GRETYPE_CHAR:
  6414. case LLAMA_GRETYPE_CHAR_NOT:
  6415. new_stacks.emplace_back(stack);
  6416. break;
  6417. default:
  6418. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6419. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6420. // those
  6421. GGML_ASSERT(false);
  6422. }
  6423. }
  6424. // takes a set of possible pushdown stacks on a grammar, which are required to
  6425. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6426. // produces the N possible stacks if the given char is accepted at those
  6427. // positions
  6428. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6429. const std::vector<std::vector<llama_grammar_element>> & rules,
  6430. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6431. const uint32_t chr) {
  6432. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6433. for (const auto & stack : stacks) {
  6434. if (stack.empty()) {
  6435. continue;
  6436. }
  6437. auto match = llama_grammar_match_char(stack.back(), chr);
  6438. if (match.first) {
  6439. const llama_grammar_element * pos = match.second;
  6440. // update top of stack to next element, if any
  6441. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6442. if (!llama_grammar_is_end_of_sequence(pos)) {
  6443. new_stack.push_back(pos);
  6444. }
  6445. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6446. }
  6447. }
  6448. return new_stacks;
  6449. }
  6450. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6451. const std::vector<std::vector<llama_grammar_element>> & rules,
  6452. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6453. const std::vector<llama_grammar_candidate> & candidates);
  6454. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6455. const std::vector<std::vector<llama_grammar_element>> & rules,
  6456. const std::vector<const llama_grammar_element *> & stack,
  6457. const std::vector<llama_grammar_candidate> & candidates) {
  6458. std::vector<llama_grammar_candidate> rejects;
  6459. if (stack.empty()) {
  6460. for (const auto & tok : candidates) {
  6461. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6462. rejects.push_back(tok);
  6463. }
  6464. }
  6465. return rejects;
  6466. }
  6467. const llama_grammar_element * stack_pos = stack.back();
  6468. std::vector<llama_grammar_candidate> next_candidates;
  6469. for (const auto & tok : candidates) {
  6470. if (*tok.code_points == 0) {
  6471. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6472. // that cannot satisfy this position in grammar
  6473. if (tok.partial_utf8.n_remain != 0 &&
  6474. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6475. rejects.push_back(tok);
  6476. }
  6477. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6478. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6479. } else {
  6480. rejects.push_back(tok);
  6481. }
  6482. }
  6483. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6484. // update top of stack to next element, if any
  6485. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6486. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6487. stack_after.push_back(stack_pos_after);
  6488. }
  6489. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6490. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6491. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6492. for (const auto & tok : next_rejects) {
  6493. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6494. }
  6495. return rejects;
  6496. }
  6497. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6498. const std::vector<std::vector<llama_grammar_element>> & rules,
  6499. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6500. const std::vector<llama_grammar_candidate> & candidates) {
  6501. GGML_ASSERT(!stacks.empty()); // REVIEW
  6502. if (candidates.empty()) {
  6503. return std::vector<llama_grammar_candidate>();
  6504. }
  6505. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6506. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6507. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6508. }
  6509. return rejects;
  6510. }
  6511. //
  6512. // grammar - external
  6513. //
  6514. struct llama_grammar * llama_grammar_init(
  6515. const llama_grammar_element ** rules,
  6516. size_t n_rules,
  6517. size_t start_rule_index) {
  6518. const llama_grammar_element * pos;
  6519. // copy rule definitions into vectors
  6520. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6521. for (size_t i = 0; i < n_rules; i++) {
  6522. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6523. vec_rules[i].push_back(*pos);
  6524. }
  6525. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6526. }
  6527. // loop over alternates of start rule to build initial stacks
  6528. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6529. pos = rules[start_rule_index];
  6530. do {
  6531. std::vector<const llama_grammar_element *> stack;
  6532. if (!llama_grammar_is_end_of_sequence(pos)) {
  6533. // if alternate is nonempty, add to stack
  6534. stack.push_back(pos);
  6535. }
  6536. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6537. while (!llama_grammar_is_end_of_sequence(pos)) {
  6538. // scan to end of alternate def
  6539. pos++;
  6540. }
  6541. if (pos->type == LLAMA_GRETYPE_ALT) {
  6542. // there's another alternate def of this rule to process
  6543. pos++;
  6544. } else {
  6545. break;
  6546. }
  6547. } while (true);
  6548. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6549. }
  6550. void llama_grammar_free(struct llama_grammar * grammar) {
  6551. delete grammar;
  6552. }
  6553. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6554. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6555. // redirect elements in stacks to point to new rules
  6556. for (size_t is = 0; is < result->stacks.size(); is++) {
  6557. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6558. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6559. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6560. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6561. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6562. }
  6563. }
  6564. }
  6565. }
  6566. }
  6567. return result;
  6568. }
  6569. //
  6570. // sampling
  6571. //
  6572. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6573. if (seed == LLAMA_DEFAULT_SEED) {
  6574. seed = time(NULL);
  6575. }
  6576. ctx->rng.seed(seed);
  6577. }
  6578. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6579. GGML_ASSERT(candidates->size > 0);
  6580. const int64_t t_start_sample_us = ggml_time_us();
  6581. // Sort the logits in descending order
  6582. if (!candidates->sorted) {
  6583. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6584. return a.logit > b.logit;
  6585. });
  6586. candidates->sorted = true;
  6587. }
  6588. float max_l = candidates->data[0].logit;
  6589. float cum_sum = 0.0f;
  6590. for (size_t i = 0; i < candidates->size; ++i) {
  6591. float p = expf(candidates->data[i].logit - max_l);
  6592. candidates->data[i].p = p;
  6593. cum_sum += p;
  6594. }
  6595. for (size_t i = 0; i < candidates->size; ++i) {
  6596. candidates->data[i].p /= cum_sum;
  6597. }
  6598. if (ctx) {
  6599. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6600. }
  6601. }
  6602. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6603. const int64_t t_start_sample_us = ggml_time_us();
  6604. k = std::max(k, (int) min_keep);
  6605. k = std::min(k, (int) candidates->size);
  6606. // Sort scores in descending order
  6607. if (!candidates->sorted) {
  6608. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6609. return a.logit > b.logit;
  6610. };
  6611. if (k == (int) candidates->size) {
  6612. std::sort(candidates->data, candidates->data + candidates->size, comp);
  6613. } else {
  6614. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6615. }
  6616. candidates->sorted = true;
  6617. }
  6618. candidates->size = k;
  6619. if (ctx) {
  6620. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6621. }
  6622. }
  6623. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6624. if (p >= 1.0f) {
  6625. return;
  6626. }
  6627. llama_sample_softmax(ctx, candidates);
  6628. const int64_t t_start_sample_us = ggml_time_us();
  6629. // Compute the cumulative probabilities
  6630. float cum_sum = 0.0f;
  6631. size_t last_idx = candidates->size;
  6632. for (size_t i = 0; i < candidates->size; ++i) {
  6633. cum_sum += candidates->data[i].p;
  6634. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6635. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6636. if (cum_sum >= p && i + 1 >= min_keep) {
  6637. last_idx = i + 1;
  6638. break;
  6639. }
  6640. }
  6641. // Resize the output vector to keep only the top-p tokens
  6642. candidates->size = last_idx;
  6643. if (ctx) {
  6644. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6645. }
  6646. }
  6647. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6648. if (p <= 0.0f || !candidates->size) {
  6649. return;
  6650. }
  6651. llama_sample_softmax(ctx, candidates);
  6652. const int64_t t_start_sample_us = ggml_time_us();
  6653. float scale = candidates->data[0].p; // scale by max prob
  6654. size_t i = 1; // first token always matches
  6655. for (; i < candidates->size; ++i) {
  6656. if (candidates->data[i].p < p * scale && i >= min_keep) {
  6657. break; // prob too small
  6658. }
  6659. }
  6660. // Resize the output vector to keep only the matching tokens
  6661. candidates->size = i;
  6662. if (ctx) {
  6663. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6664. }
  6665. }
  6666. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6667. if (z >= 1.0f || candidates->size <= 2) {
  6668. return;
  6669. }
  6670. llama_sample_softmax(nullptr, candidates);
  6671. const int64_t t_start_sample_us = ggml_time_us();
  6672. // Compute the first and second derivatives
  6673. std::vector<float> first_derivatives(candidates->size - 1);
  6674. std::vector<float> second_derivatives(candidates->size - 2);
  6675. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6676. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6677. }
  6678. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6679. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6680. }
  6681. // Calculate absolute value of second derivatives
  6682. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6683. second_derivatives[i] = std::abs(second_derivatives[i]);
  6684. }
  6685. // Normalize the second derivatives
  6686. {
  6687. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6688. if (second_derivatives_sum > 1e-6f) {
  6689. for (float & value : second_derivatives) {
  6690. value /= second_derivatives_sum;
  6691. }
  6692. } else {
  6693. for (float & value : second_derivatives) {
  6694. value = 1.0f / second_derivatives.size();
  6695. }
  6696. }
  6697. }
  6698. float cum_sum = 0.0f;
  6699. size_t last_idx = candidates->size;
  6700. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6701. cum_sum += second_derivatives[i];
  6702. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6703. if (cum_sum > z && i >= min_keep) {
  6704. last_idx = i;
  6705. break;
  6706. }
  6707. }
  6708. // Resize the output vector to keep only the tokens above the tail location
  6709. candidates->size = last_idx;
  6710. if (ctx) {
  6711. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6712. }
  6713. }
  6714. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6715. // Reference implementation:
  6716. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6717. if (p >= 1.0f) {
  6718. return;
  6719. }
  6720. // Compute the softmax of logits and calculate entropy
  6721. llama_sample_softmax(nullptr, candidates);
  6722. const int64_t t_start_sample_us = ggml_time_us();
  6723. float entropy = 0.0f;
  6724. for (size_t i = 0; i < candidates->size; ++i) {
  6725. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6726. }
  6727. // Compute the absolute difference between negative log probability and entropy for each candidate
  6728. std::vector<float> shifted_scores;
  6729. for (size_t i = 0; i < candidates->size; ++i) {
  6730. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6731. shifted_scores.push_back(shifted_score);
  6732. }
  6733. // Sort tokens based on the shifted_scores and their corresponding indices
  6734. std::vector<size_t> indices(candidates->size);
  6735. std::iota(indices.begin(), indices.end(), 0);
  6736. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6737. return shifted_scores[a] < shifted_scores[b];
  6738. });
  6739. // Compute the cumulative probabilities
  6740. float cum_sum = 0.0f;
  6741. size_t last_idx = indices.size();
  6742. for (size_t i = 0; i < indices.size(); ++i) {
  6743. size_t idx = indices[i];
  6744. cum_sum += candidates->data[idx].p;
  6745. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  6746. if (cum_sum > p && i >= min_keep - 1) {
  6747. last_idx = i + 1;
  6748. break;
  6749. }
  6750. }
  6751. // Resize the output vector to keep only the locally typical tokens
  6752. std::vector<llama_token_data> new_candidates;
  6753. for (size_t i = 0; i < last_idx; ++i) {
  6754. size_t idx = indices[i];
  6755. new_candidates.push_back(candidates->data[idx]);
  6756. }
  6757. // Replace the data in candidates with the new_candidates data
  6758. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  6759. candidates->size = new_candidates.size();
  6760. candidates->sorted = false;
  6761. if (ctx) {
  6762. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6763. }
  6764. }
  6765. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6766. const int64_t t_start_sample_us = ggml_time_us();
  6767. for (size_t i = 0; i < candidates_p->size; ++i) {
  6768. candidates_p->data[i].logit /= temp;
  6769. }
  6770. if (ctx) {
  6771. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6772. }
  6773. }
  6774. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6775. llama_sample_temp(ctx, candidates_p, temp);
  6776. }
  6777. void llama_sample_repetition_penalties(
  6778. struct llama_context * ctx,
  6779. llama_token_data_array * candidates,
  6780. const llama_token * last_tokens,
  6781. size_t penalty_last_n,
  6782. float penalty_repeat,
  6783. float penalty_freq,
  6784. float penalty_present) {
  6785. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  6786. return;
  6787. }
  6788. const int64_t t_start_sample_us = ggml_time_us();
  6789. // Create a frequency map to count occurrences of each token in last_tokens
  6790. std::unordered_map<llama_token, int> token_count;
  6791. for (size_t i = 0; i < penalty_last_n; ++i) {
  6792. token_count[last_tokens[i]]++;
  6793. }
  6794. // Apply frequency and presence penalties to the candidates
  6795. for (size_t i = 0; i < candidates->size; ++i) {
  6796. const auto token_iter = token_count.find(candidates->data[i].id);
  6797. if (token_iter == token_count.end()) {
  6798. continue;
  6799. }
  6800. const int count = token_iter->second;
  6801. // 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.
  6802. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  6803. if (candidates->data[i].logit <= 0) {
  6804. candidates->data[i].logit *= penalty_repeat;
  6805. } else {
  6806. candidates->data[i].logit /= penalty_repeat;
  6807. }
  6808. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  6809. }
  6810. candidates->sorted = false;
  6811. if (ctx) {
  6812. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6813. }
  6814. }
  6815. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  6816. GGML_ASSERT(ctx);
  6817. const int64_t t_start_sample_us = ggml_time_us();
  6818. bool allow_eos = false;
  6819. for (const auto & stack : grammar->stacks) {
  6820. if (stack.empty()) {
  6821. allow_eos = true;
  6822. break;
  6823. }
  6824. }
  6825. const llama_token eos = llama_token_eos(&ctx->model);
  6826. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  6827. candidates_decoded.reserve(candidates->size);
  6828. std::vector<llama_grammar_candidate> candidates_grammar;
  6829. candidates_grammar.reserve(candidates->size);
  6830. for (size_t i = 0; i < candidates->size; ++i) {
  6831. const llama_token id = candidates->data[i].id;
  6832. const std::string piece = llama_token_to_piece(ctx, id);
  6833. if (id == eos) {
  6834. if (!allow_eos) {
  6835. candidates->data[i].logit = -INFINITY;
  6836. }
  6837. } else if (piece.empty() || piece[0] == 0) {
  6838. candidates->data[i].logit = -INFINITY;
  6839. } else {
  6840. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  6841. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  6842. }
  6843. }
  6844. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  6845. for (const auto & reject : rejects) {
  6846. candidates->data[reject.index].logit = -INFINITY;
  6847. }
  6848. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6849. }
  6850. static void llama_log_softmax(float * array, size_t size) {
  6851. float max_l = *std::max_element(array, array + size);
  6852. float sum = 0.f;
  6853. for (size_t i = 0; i < size; ++i) {
  6854. float p = expf(array[i] - max_l);
  6855. sum += p;
  6856. array[i] = p;
  6857. }
  6858. for (size_t i = 0; i < size; ++i) {
  6859. array[i] = logf(array[i] / sum);
  6860. }
  6861. }
  6862. void llama_sample_apply_guidance(
  6863. struct llama_context * ctx,
  6864. float * logits,
  6865. float * logits_guidance,
  6866. float scale) {
  6867. GGML_ASSERT(ctx);
  6868. const auto t_start_sample_us = ggml_time_us();
  6869. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  6870. llama_log_softmax(logits, n_vocab);
  6871. llama_log_softmax(logits_guidance, n_vocab);
  6872. for (int i = 0; i < n_vocab; ++i) {
  6873. auto & l = logits[i];
  6874. const auto & g = logits_guidance[i];
  6875. l = scale * (l - g) + g;
  6876. }
  6877. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6878. }
  6879. void llama_sample_classifier_free_guidance(
  6880. struct llama_context * ctx,
  6881. llama_token_data_array * candidates,
  6882. struct llama_context * guidance_ctx,
  6883. float scale) {
  6884. GGML_ASSERT(ctx);
  6885. int64_t t_start_sample_us;
  6886. t_start_sample_us = ggml_time_us();
  6887. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  6888. GGML_ASSERT(n_vocab == candidates->size);
  6889. GGML_ASSERT(!candidates->sorted);
  6890. std::vector<float> logits_base(n_vocab);
  6891. for (size_t i = 0; i < n_vocab; ++i) {
  6892. logits_base[i] = candidates->data[i].logit;
  6893. }
  6894. float * logits_guidance = llama_get_logits(guidance_ctx);
  6895. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6896. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  6897. t_start_sample_us = ggml_time_us();
  6898. for (size_t i = 0; i < n_vocab; ++i) {
  6899. candidates->data[i].logit = logits_base[i];
  6900. }
  6901. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6902. }
  6903. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  6904. GGML_ASSERT(ctx);
  6905. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  6906. int64_t t_start_sample_us;
  6907. t_start_sample_us = ggml_time_us();
  6908. llama_sample_softmax(nullptr, candidates);
  6909. // Estimate s_hat using the most probable m tokens
  6910. float s_hat = 0.0;
  6911. float sum_ti_bi = 0.0;
  6912. float sum_ti_sq = 0.0;
  6913. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  6914. float t_i = logf(float(i + 2) / float(i + 1));
  6915. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  6916. sum_ti_bi += t_i * b_i;
  6917. sum_ti_sq += t_i * t_i;
  6918. }
  6919. s_hat = sum_ti_bi / sum_ti_sq;
  6920. // Compute k from the estimated s_hat and target surprise value
  6921. float epsilon_hat = s_hat - 1;
  6922. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  6923. // Sample the next word X using top-k sampling
  6924. llama_sample_top_k(nullptr, candidates, int(k), 1);
  6925. if (ctx) {
  6926. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6927. }
  6928. llama_token X = llama_sample_token(ctx, candidates);
  6929. t_start_sample_us = ggml_time_us();
  6930. // Compute error as the difference between observed surprise and target surprise value
  6931. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6932. return candidate.id == X;
  6933. }));
  6934. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6935. float e = observed_surprise - tau;
  6936. // Update mu using the learning rate and error
  6937. *mu = *mu - eta * e;
  6938. if (ctx) {
  6939. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6940. }
  6941. return X;
  6942. }
  6943. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  6944. int64_t t_start_sample_us;
  6945. t_start_sample_us = ggml_time_us();
  6946. llama_sample_softmax(ctx, candidates);
  6947. // Truncate the words with surprise values greater than mu
  6948. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6949. return -log2f(candidate.p) > *mu;
  6950. }));
  6951. if (candidates->size == 0) {
  6952. candidates->size = 1;
  6953. }
  6954. if (ctx) {
  6955. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6956. }
  6957. // Normalize the probabilities of the remaining words
  6958. llama_sample_softmax(ctx, candidates);
  6959. // Sample the next word X from the remaining words
  6960. llama_token X = llama_sample_token(ctx, candidates);
  6961. t_start_sample_us = ggml_time_us();
  6962. // Compute error as the difference between observed surprise and target surprise value
  6963. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6964. return candidate.id == X;
  6965. }));
  6966. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6967. float e = observed_surprise - tau;
  6968. // Update mu using the learning rate and error
  6969. *mu = *mu - eta * e;
  6970. if (ctx) {
  6971. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6972. }
  6973. return X;
  6974. }
  6975. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  6976. const int64_t t_start_sample_us = ggml_time_us();
  6977. // Find max element
  6978. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6979. return a.logit < b.logit;
  6980. });
  6981. llama_token result = max_iter->id;
  6982. if (ctx) {
  6983. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6984. ctx->n_sample++;
  6985. }
  6986. return result;
  6987. }
  6988. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  6989. GGML_ASSERT(ctx);
  6990. const int64_t t_start_sample_us = ggml_time_us();
  6991. llama_sample_softmax(nullptr, candidates);
  6992. std::vector<float> probs;
  6993. probs.reserve(candidates->size);
  6994. for (size_t i = 0; i < candidates->size; ++i) {
  6995. probs.push_back(candidates->data[i].p);
  6996. }
  6997. std::discrete_distribution<> dist(probs.begin(), probs.end());
  6998. auto & rng = ctx->rng;
  6999. int idx = dist(rng);
  7000. llama_token result = candidates->data[idx].id;
  7001. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7002. ctx->n_sample++;
  7003. return result;
  7004. }
  7005. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  7006. const int64_t t_start_sample_us = ggml_time_us();
  7007. if (token == llama_token_eos(&ctx->model)) {
  7008. for (const auto & stack : grammar->stacks) {
  7009. if (stack.empty()) {
  7010. return;
  7011. }
  7012. }
  7013. GGML_ASSERT(false);
  7014. }
  7015. const std::string piece = llama_token_to_piece(ctx, token);
  7016. // Note terminating 0 in decoded string
  7017. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  7018. const auto & code_points = decoded.first;
  7019. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  7020. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  7021. }
  7022. grammar->partial_utf8 = decoded.second;
  7023. GGML_ASSERT(!grammar->stacks.empty());
  7024. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7025. }
  7026. //
  7027. // Beam search
  7028. //
  7029. struct llama_beam {
  7030. std::vector<llama_token> tokens;
  7031. float p; // Cumulative beam probability (renormalized relative to all beams)
  7032. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  7033. // Sort beams by probability. In case of ties, prefer beams at eob.
  7034. bool operator<(const llama_beam & rhs) const {
  7035. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  7036. }
  7037. // Shift off first n tokens and discard them.
  7038. void shift_tokens(const size_t n) {
  7039. if (n) {
  7040. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  7041. tokens.resize(tokens.size() - n);
  7042. }
  7043. }
  7044. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  7045. };
  7046. // A struct for calculating logit-related info.
  7047. struct llama_logit_info {
  7048. const float * const logits;
  7049. const int n_vocab;
  7050. const float max_l;
  7051. const float normalizer;
  7052. struct sum_exp {
  7053. float max_l;
  7054. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  7055. };
  7056. llama_logit_info(llama_context * ctx)
  7057. : logits(llama_get_logits(ctx))
  7058. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  7059. , max_l(*std::max_element(logits, logits + n_vocab))
  7060. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  7061. { }
  7062. llama_token_data get_token_data(const llama_token token_id) const {
  7063. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  7064. return {token_id, logits[token_id], p};
  7065. }
  7066. // Return top k token_data by logit.
  7067. std::vector<llama_token_data> top_k(size_t k) {
  7068. std::vector<llama_token_data> min_heap; // min-heap by logit
  7069. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  7070. min_heap.reserve(k_min);
  7071. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  7072. min_heap.push_back(get_token_data(token_id));
  7073. }
  7074. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  7075. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  7076. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  7077. if (min_heap.front().logit < logits[token_id]) {
  7078. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  7079. min_heap.back().id = token_id;
  7080. min_heap.back().logit = logits[token_id];
  7081. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  7082. }
  7083. }
  7084. return min_heap;
  7085. }
  7086. float probability_from_logit(float logit) const {
  7087. return normalizer * std::exp(logit - max_l);
  7088. }
  7089. };
  7090. struct llama_beam_search_data {
  7091. llama_context * ctx;
  7092. size_t n_beams;
  7093. int n_past;
  7094. int n_predict;
  7095. std::vector<llama_beam> beams;
  7096. std::vector<llama_beam> next_beams;
  7097. // Re-calculated on each loop iteration
  7098. size_t common_prefix_length;
  7099. // Used to communicate to/from callback on beams state.
  7100. std::vector<llama_beam_view> beam_views;
  7101. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  7102. : ctx(ctx)
  7103. , n_beams(n_beams)
  7104. , n_past(n_past)
  7105. , n_predict(n_predict)
  7106. , beam_views(n_beams) {
  7107. beams.reserve(n_beams);
  7108. next_beams.reserve(n_beams);
  7109. }
  7110. // Collapse beams to a single beam given by index.
  7111. void collapse_beams(const size_t beam_idx) {
  7112. if (0u < beam_idx) {
  7113. std::swap(beams[0], beams[beam_idx]);
  7114. }
  7115. beams.resize(1);
  7116. }
  7117. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  7118. // The repetitive patterns below reflect the 2 stages of heaps:
  7119. // * Gather elements until the vector is full, then call std::make_heap() on it.
  7120. // * If the heap is full and a new element is found that should be included, pop the
  7121. // least element to the back(), replace it with the new, then push it into the heap.
  7122. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  7123. // Min-heaps use a greater-than comparator.
  7124. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  7125. if (beam.eob) {
  7126. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  7127. if (next_beams.size() < n_beams) {
  7128. next_beams.push_back(std::move(beam));
  7129. if (next_beams.size() == n_beams) {
  7130. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7131. }
  7132. } else if (next_beams.front().p < beam.p) {
  7133. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7134. next_beams.back() = std::move(beam);
  7135. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7136. }
  7137. } else {
  7138. // beam is not at end-of-sentence, so branch with next top_k tokens.
  7139. if (!beam.tokens.empty()) {
  7140. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  7141. }
  7142. llama_logit_info logit_info(ctx);
  7143. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  7144. size_t i=0;
  7145. if (next_beams.size() < n_beams) {
  7146. for (; next_beams.size() < n_beams ; ++i) {
  7147. llama_beam next_beam = beam;
  7148. next_beam.tokens.push_back(next_tokens[i].id);
  7149. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7150. next_beams.push_back(std::move(next_beam));
  7151. }
  7152. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7153. } else {
  7154. for (; next_beams.front().p == 0.0f ; ++i) {
  7155. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7156. next_beams.back() = beam;
  7157. next_beams.back().tokens.push_back(next_tokens[i].id);
  7158. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7159. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7160. }
  7161. }
  7162. for (; i < n_beams ; ++i) {
  7163. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  7164. if (next_beams.front().p < next_p) {
  7165. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7166. next_beams.back() = beam;
  7167. next_beams.back().tokens.push_back(next_tokens[i].id);
  7168. next_beams.back().p = next_p;
  7169. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7170. }
  7171. }
  7172. }
  7173. }
  7174. // Find common_prefix_length based on beams.
  7175. // Requires beams is not empty.
  7176. size_t find_common_prefix_length() {
  7177. size_t common_prefix_length = beams[0].tokens.size();
  7178. for (size_t i = 1 ; i < beams.size() ; ++i) {
  7179. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  7180. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  7181. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  7182. common_prefix_length = j;
  7183. break;
  7184. }
  7185. }
  7186. }
  7187. return common_prefix_length;
  7188. }
  7189. // Construct beams_state to send back to caller via the callback function.
  7190. // Side effect: set common_prefix_length = find_common_prefix_length();
  7191. llama_beams_state get_beams_state(const bool last_call) {
  7192. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7193. beam_views[i] = beams[i].view();
  7194. }
  7195. common_prefix_length = find_common_prefix_length();
  7196. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  7197. }
  7198. // Loop:
  7199. // * while i < n_predict, AND
  7200. // * any of the beams have not yet reached end-of-beam (eob), AND
  7201. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  7202. // (since all other beam probabilities can only decrease)
  7203. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  7204. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  7205. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  7206. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  7207. !beams[top_beam_index()].eob ; ++i) {
  7208. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  7209. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  7210. if (common_prefix_length) {
  7211. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  7212. n_past += common_prefix_length;
  7213. }
  7214. // Zero-out next_beam probabilities to place them last in following min-heap.
  7215. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  7216. for (llama_beam & beam : beams) {
  7217. beam.shift_tokens(common_prefix_length);
  7218. fill_next_beams_by_top_probabilities(beam);
  7219. }
  7220. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  7221. beams.swap(next_beams);
  7222. renormalize_beam_probabilities(beams);
  7223. }
  7224. collapse_beams(top_beam_index());
  7225. callback(callback_data, get_beams_state(true));
  7226. }
  7227. // As beams grow, the cumulative probabilities decrease.
  7228. // Renormalize them to avoid floating point underflow.
  7229. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  7230. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  7231. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  7232. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  7233. }
  7234. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  7235. size_t top_beam_index() {
  7236. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  7237. }
  7238. // Copy (p,eob) for each beam which may have been changed by the callback.
  7239. void update_beams_from_beam_views() {
  7240. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7241. beams[i].p = beam_views[i].p;
  7242. beams[i].eob = beam_views[i].eob;
  7243. }
  7244. }
  7245. };
  7246. void llama_beam_search(llama_context * ctx,
  7247. llama_beam_search_callback_fn_t callback, void * callback_data,
  7248. size_t n_beams, int n_past, int n_predict) {
  7249. assert(ctx);
  7250. const int64_t t_start_sample_us = ggml_time_us();
  7251. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  7252. beam_search_data.loop(callback, callback_data);
  7253. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7254. ctx->n_sample++;
  7255. }
  7256. //
  7257. // quantization
  7258. //
  7259. struct quantize_state_internal {
  7260. const llama_model & model;
  7261. const llama_model_quantize_params * params;
  7262. int n_attention_wv = 0;
  7263. int n_feed_forward_w2 = 0;
  7264. int i_attention_wv = 0;
  7265. int i_feed_forward_w2 = 0;
  7266. int n_k_quantized = 0;
  7267. int n_fallback = 0;
  7268. bool has_imatrix = false;
  7269. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  7270. : model(model)
  7271. , params(params)
  7272. {}
  7273. };
  7274. static void llama_convert_tensor_internal(
  7275. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  7276. const size_t nelements, const int nthread
  7277. ) {
  7278. if (output.size() < nelements) {
  7279. output.resize(nelements);
  7280. }
  7281. float * f32_output = (float *) output.data();
  7282. ggml_type_traits_t qtype;
  7283. if (ggml_is_quantized(tensor->type)) {
  7284. qtype = ggml_internal_get_type_traits(tensor->type);
  7285. if (qtype.to_float == NULL) {
  7286. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  7287. }
  7288. } else if (tensor->type != GGML_TYPE_F16) {
  7289. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  7290. }
  7291. if (nthread < 2) {
  7292. if (tensor->type == GGML_TYPE_F16) {
  7293. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  7294. } else if (ggml_is_quantized(tensor->type)) {
  7295. qtype.to_float(tensor->data, f32_output, nelements);
  7296. } else {
  7297. GGML_ASSERT(false); // unreachable
  7298. }
  7299. return;
  7300. }
  7301. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  7302. size_t block_size_bytes = ggml_type_size(tensor->type);
  7303. GGML_ASSERT(nelements % block_size == 0);
  7304. size_t nblocks = nelements / block_size;
  7305. size_t blocks_per_thread = nblocks / nthread;
  7306. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  7307. size_t in_buff_offs = 0;
  7308. size_t out_buff_offs = 0;
  7309. for (int tnum = 0; tnum < nthread; tnum++) {
  7310. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  7311. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  7312. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  7313. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  7314. if (typ == GGML_TYPE_F16) {
  7315. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  7316. } else {
  7317. qtype.to_float(inbuf, outbuf, nels);
  7318. }
  7319. };
  7320. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  7321. in_buff_offs += thr_block_bytes;
  7322. out_buff_offs += thr_elems;
  7323. }
  7324. for (auto & w : workers) { w.join(); }
  7325. workers.clear();
  7326. }
  7327. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  7328. const std::string name = ggml_get_name(tensor);
  7329. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7330. const llm_arch arch = qs.model.arch;
  7331. const auto tn = LLM_TN(arch);
  7332. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  7333. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  7334. };
  7335. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  7336. int nx = tensor->ne[0];
  7337. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  7338. new_type = GGML_TYPE_Q8_0;
  7339. }
  7340. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7341. new_type = GGML_TYPE_Q5_K;
  7342. }
  7343. else if (new_type != GGML_TYPE_Q8_0) {
  7344. new_type = GGML_TYPE_Q6_K;
  7345. }
  7346. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7347. if (name.find("attn_v.weight") != std::string::npos) {
  7348. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  7349. else new_type = GGML_TYPE_Q2_K;
  7350. ++qs.i_attention_wv;
  7351. }
  7352. else if (name.find("ffn_down") != std::string::npos) {
  7353. if (qs.i_feed_forward_w2 < qs.n_feed_forward_w2/8) new_type = GGML_TYPE_Q2_K;
  7354. ++qs.i_feed_forward_w2;
  7355. }
  7356. else if (name == "token_embd.weight") new_type = GGML_TYPE_Q2_K;
  7357. } else if (name.find("attn_v.weight") != std::string::npos) {
  7358. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  7359. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  7360. }
  7361. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  7362. new_type = GGML_TYPE_Q4_K;
  7363. }
  7364. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7365. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7366. }
  7367. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7368. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  7369. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  7370. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  7371. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  7372. (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;
  7373. if (qs.model.type == MODEL_70B) {
  7374. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7375. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7376. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7377. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7378. }
  7379. if (qs.model.hparams.n_expert == 8) {
  7380. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7381. // TODO: explore better strategies
  7382. new_type = GGML_TYPE_Q8_0;
  7383. }
  7384. ++qs.i_attention_wv;
  7385. } else if (name.find("attn_k.weight") != std::string::npos) {
  7386. if (qs.model.hparams.n_expert == 8) {
  7387. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7388. // TODO: explore better strategies
  7389. new_type = GGML_TYPE_Q8_0;
  7390. }
  7391. } else if (name.find("ffn_down") != std::string::npos) {
  7392. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  7393. int i_layer, n_layer;
  7394. if (n_expert == 1) {
  7395. i_layer = qs.i_feed_forward_w2;
  7396. n_layer = qs.n_feed_forward_w2;
  7397. } else {
  7398. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  7399. // sprinkled in the model. Hence, simply dividing i_feed_forward_w2 by n_expert does not work
  7400. // for getting the current layer as I initially thought, and we need to resort to parsing the
  7401. // tensor name.
  7402. n_layer = qs.n_feed_forward_w2 / n_expert;
  7403. if (sscanf(name.c_str(), "blk.%d.ffn_down", &i_layer) != 1) {
  7404. throw std::runtime_error(format("Failed to determine layer for tensor %s", name.c_str()));
  7405. }
  7406. if (i_layer < 0 || i_layer >= n_layer) {
  7407. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name.c_str(), n_layer));
  7408. }
  7409. }
  7410. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7411. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  7412. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  7413. }
  7414. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7415. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  7416. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  7417. : GGML_TYPE_Q3_K;
  7418. }
  7419. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7420. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7421. }
  7422. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7423. if (arch == LLM_ARCH_FALCON) {
  7424. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  7425. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7426. } else {
  7427. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7428. }
  7429. }
  7430. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7431. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  7432. new_type = GGML_TYPE_Q5_K;
  7433. }
  7434. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  7435. && qs.has_imatrix && i_layer < n_layer/8) {
  7436. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  7437. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  7438. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  7439. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  7440. }
  7441. ++qs.i_feed_forward_w2;
  7442. } else if (name.find("attn_output.weight") != std::string::npos) {
  7443. if (arch != LLM_ARCH_FALCON) {
  7444. if (qs.model.hparams.n_expert == 8) {
  7445. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  7446. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7447. new_type = GGML_TYPE_Q5_K;
  7448. }
  7449. } else {
  7450. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7451. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7452. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7453. }
  7454. } else {
  7455. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7456. }
  7457. }
  7458. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7459. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7460. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7461. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7462. }
  7463. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7464. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7465. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7466. //}
  7467. // This can be used to reduce the size of the Q5_K_S model.
  7468. // The associated PPL increase is fully in line with the size reduction
  7469. //else {
  7470. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7471. //}
  7472. bool convert_incompatible_tensor = false;
  7473. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7474. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  7475. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS) {
  7476. int nx = tensor->ne[0];
  7477. int ny = tensor->ne[1];
  7478. if (nx % QK_K != 0) {
  7479. 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));
  7480. convert_incompatible_tensor = true;
  7481. } else {
  7482. ++qs.n_k_quantized;
  7483. }
  7484. }
  7485. if (convert_incompatible_tensor) {
  7486. switch (new_type) {
  7487. case GGML_TYPE_IQ2_XXS:
  7488. case GGML_TYPE_IQ2_XS:
  7489. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  7490. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  7491. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  7492. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  7493. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  7494. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  7495. }
  7496. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  7497. ++qs.n_fallback;
  7498. }
  7499. return new_type;
  7500. }
  7501. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  7502. ggml_type quantized_type;
  7503. llama_ftype ftype = params->ftype;
  7504. switch (params->ftype) {
  7505. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  7506. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  7507. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  7508. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  7509. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  7510. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  7511. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  7512. // K-quants
  7513. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  7514. case LLAMA_FTYPE_MOSTLY_Q2_K_S: quantized_type = GGML_TYPE_Q2_K; break;
  7515. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  7516. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  7517. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  7518. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  7519. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  7520. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  7521. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  7522. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  7523. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  7524. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  7525. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  7526. }
  7527. int nthread = params->nthread;
  7528. if (nthread <= 0) {
  7529. nthread = std::thread::hardware_concurrency();
  7530. }
  7531. // mmap consistently increases speed Linux, and also increases speed on Windows with
  7532. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  7533. #if defined(__linux__) || defined(_WIN32)
  7534. constexpr bool use_mmap = true;
  7535. #else
  7536. constexpr bool use_mmap = false;
  7537. #endif
  7538. llama_model_loader ml(fname_inp, use_mmap, NULL);
  7539. ml.init_mapping(false); // no prefetching?
  7540. llama_model model;
  7541. llm_load_arch(ml, model);
  7542. llm_load_hparams(ml, model);
  7543. struct quantize_state_internal qs(model, params);
  7544. if (params->only_copy) {
  7545. ftype = model.ftype;
  7546. }
  7547. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  7548. if (params->imatrix) {
  7549. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  7550. if (imatrix_data) {
  7551. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  7552. qs.has_imatrix = true;
  7553. }
  7554. }
  7555. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  7556. struct gguf_context * ctx_out = gguf_init_empty();
  7557. // copy the KV pairs from the input file
  7558. gguf_set_kv (ctx_out, ml.ctx_gguf);
  7559. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  7560. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  7561. for (int i = 0; i < ml.n_tensors; ++i) {
  7562. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7563. const std::string name = ggml_get_name(meta);
  7564. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7565. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  7566. ++qs.n_attention_wv;
  7567. }
  7568. else if (name.find("ffn_down") != std::string::npos) {
  7569. ++qs.n_feed_forward_w2;
  7570. }
  7571. }
  7572. if (qs.n_attention_wv != qs.n_feed_forward_w2 || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  7573. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  7574. __func__, qs.n_attention_wv, qs.n_feed_forward_w2, model.hparams.n_layer);
  7575. }
  7576. size_t total_size_org = 0;
  7577. size_t total_size_new = 0;
  7578. std::vector<int64_t> hist_all(1 << 4, 0);
  7579. std::vector<std::thread> workers;
  7580. workers.reserve(nthread);
  7581. std::mutex mutex;
  7582. int idx = 0;
  7583. std::vector<no_init<uint8_t>> read_data;
  7584. std::vector<no_init<uint8_t>> work;
  7585. std::vector<no_init<float>> f32_conv_buf;
  7586. // populate the original tensors so we get an initial meta data
  7587. for (int i = 0; i < ml.n_tensors; ++i) {
  7588. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7589. gguf_add_tensor(ctx_out, meta);
  7590. }
  7591. std::ofstream fout(fname_out, std::ios::binary);
  7592. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  7593. const size_t meta_size = gguf_get_meta_size(ctx_out);
  7594. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  7595. // placeholder for the meta data
  7596. ::zeros(fout, meta_size);
  7597. for (int i = 0; i < ml.n_tensors; ++i) {
  7598. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7599. const std::string name = ggml_get_name(tensor);
  7600. if (!ml.use_mmap) {
  7601. if (read_data.size() < ggml_nbytes(tensor)) {
  7602. read_data.resize(ggml_nbytes(tensor));
  7603. }
  7604. tensor->data = read_data.data();
  7605. }
  7606. ml.load_data_for(tensor);
  7607. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7608. ++idx, ml.n_tensors,
  7609. ggml_get_name(tensor),
  7610. llama_format_tensor_shape(tensor).c_str(),
  7611. ggml_type_name(tensor->type));
  7612. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7613. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7614. // quantize only 2D tensors
  7615. quantize &= (ggml_n_dims(tensor) == 2);
  7616. quantize &= params->quantize_output_tensor || name != "output.weight";
  7617. quantize &= !params->only_copy;
  7618. // do not quantize expert gating tensors
  7619. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7620. enum ggml_type new_type;
  7621. void * new_data;
  7622. size_t new_size;
  7623. if (quantize) {
  7624. new_type = quantized_type;
  7625. if (!params->pure) {
  7626. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7627. }
  7628. // If we've decided to quantize to the same type the tensor is already
  7629. // in then there's nothing to do.
  7630. quantize = tensor->type != new_type;
  7631. }
  7632. if (!quantize) {
  7633. new_type = tensor->type;
  7634. new_data = tensor->data;
  7635. new_size = ggml_nbytes(tensor);
  7636. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7637. } else {
  7638. const size_t nelements = ggml_nelements(tensor);
  7639. const float * imatrix = nullptr;
  7640. if (imatrix_data) {
  7641. auto it = imatrix_data->find(tensor->name);
  7642. if (it == imatrix_data->end()) {
  7643. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  7644. } else {
  7645. if (it->second.size() == (size_t)tensor->ne[0]) {
  7646. imatrix = it->second.data();
  7647. } else {
  7648. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  7649. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  7650. }
  7651. }
  7652. }
  7653. if ((new_type == GGML_TYPE_IQ2_XXS ||
  7654. new_type == GGML_TYPE_IQ2_XS ||
  7655. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  7656. LLAMA_LOG_ERROR("\n\n============================================================\n");
  7657. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  7658. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  7659. LLAMA_LOG_ERROR("============================================================\n\n");
  7660. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  7661. }
  7662. float * f32_data;
  7663. if (tensor->type == GGML_TYPE_F32) {
  7664. f32_data = (float *) tensor->data;
  7665. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  7666. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  7667. } else {
  7668. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  7669. f32_data = (float *) f32_conv_buf.data();
  7670. }
  7671. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  7672. fflush(stdout);
  7673. if (work.size() < nelements * 4) {
  7674. work.resize(nelements * 4); // upper bound on size
  7675. }
  7676. new_data = work.data();
  7677. std::array<int64_t, 1 << 4> hist_cur = {};
  7678. const int n_per_row = tensor->ne[0];
  7679. const int nrows = nelements / n_per_row;
  7680. static const int min_chunk_size = 32 * 512;
  7681. 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);
  7682. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  7683. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  7684. if (nthread_use < 2) {
  7685. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  7686. } else {
  7687. int counter = 0;
  7688. new_size = 0;
  7689. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  7690. nrows, n_per_row, imatrix]() {
  7691. std::array<int64_t, 1 << 4> local_hist = {};
  7692. const int nrows_per_chunk = chunk_size / n_per_row;
  7693. size_t local_size = 0;
  7694. while (true) {
  7695. std::unique_lock<std::mutex> lock(mutex);
  7696. int first_row = counter; counter += nrows_per_chunk;
  7697. if (first_row >= nrows) {
  7698. if (local_size > 0) {
  7699. for (int j=0; j<int(local_hist.size()); ++j) {
  7700. hist_cur[j] += local_hist[j];
  7701. }
  7702. new_size += local_size;
  7703. }
  7704. break;
  7705. }
  7706. lock.unlock();
  7707. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  7708. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  7709. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  7710. }
  7711. };
  7712. for (int it = 0; it < nthread_use - 1; ++it) {
  7713. workers.emplace_back(compute);
  7714. }
  7715. compute();
  7716. for (auto & w : workers) { w.join(); }
  7717. workers.clear();
  7718. }
  7719. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  7720. int64_t tot_count = 0;
  7721. for (size_t i = 0; i < hist_cur.size(); i++) {
  7722. hist_all[i] += hist_cur[i];
  7723. tot_count += hist_cur[i];
  7724. }
  7725. if (tot_count > 0) {
  7726. LLAMA_LOG_INFO(" | hist: ");
  7727. for (size_t i = 0; i < hist_cur.size(); i++) {
  7728. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  7729. }
  7730. }
  7731. LLAMA_LOG_INFO("\n");
  7732. }
  7733. total_size_org += ggml_nbytes(tensor);
  7734. total_size_new += new_size;
  7735. // update the gguf meta data as we go
  7736. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  7737. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  7738. // write tensor data + padding
  7739. fout.write((const char *) new_data, new_size);
  7740. zeros(fout, GGML_PAD(new_size, align) - new_size);
  7741. }
  7742. // go back to beginning of file and write the updated meta data
  7743. {
  7744. fout.seekp(0);
  7745. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  7746. gguf_get_meta_data(ctx_out, data.data());
  7747. fout.write((const char *) data.data(), data.size());
  7748. }
  7749. fout.close();
  7750. gguf_free(ctx_out);
  7751. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  7752. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  7753. // print histogram for all tensors
  7754. {
  7755. int64_t sum_all = 0;
  7756. for (size_t i = 0; i < hist_all.size(); i++) {
  7757. sum_all += hist_all[i];
  7758. }
  7759. if (sum_all > 0) {
  7760. LLAMA_LOG_INFO("%s: hist: ", __func__);
  7761. for (size_t i = 0; i < hist_all.size(); i++) {
  7762. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  7763. }
  7764. LLAMA_LOG_INFO("\n");
  7765. }
  7766. }
  7767. if (qs.n_fallback > 0) {
  7768. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  7769. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  7770. }
  7771. }
  7772. static int llama_apply_lora_from_file_internal(
  7773. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  7774. ) {
  7775. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  7776. const int64_t t_start_lora_us = ggml_time_us();
  7777. llama_file fin(path_lora, "rb");
  7778. // verify magic and version
  7779. {
  7780. uint32_t magic = fin.read_u32();
  7781. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  7782. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  7783. return 1;
  7784. }
  7785. uint32_t format_version = fin.read_u32();
  7786. if (format_version != 1) {
  7787. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  7788. return 1;
  7789. }
  7790. }
  7791. int32_t lora_r = fin.read_u32();
  7792. int32_t lora_alpha = fin.read_u32();
  7793. float scaling = scale * (float)lora_alpha / (float)lora_r;
  7794. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  7795. // load base model
  7796. std::unique_ptr<llama_model_loader> ml;
  7797. if (path_base_model) {
  7798. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  7799. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  7800. ml->init_mapping(/*prefetch*/ false); // no prefetching
  7801. }
  7802. struct tensor_meta {
  7803. std::string name;
  7804. ggml_type type;
  7805. int32_t ne[2];
  7806. size_t offset;
  7807. };
  7808. std::map<std::string, tensor_meta> tensor_meta_map;
  7809. // load all tensor meta
  7810. while (true) {
  7811. if (fin.tell() == fin.size) {
  7812. // eof
  7813. break;
  7814. }
  7815. int32_t n_dims;
  7816. int32_t name_len;
  7817. int32_t ftype;
  7818. fin.read_raw(&n_dims, sizeof(n_dims));
  7819. fin.read_raw(&name_len, sizeof(name_len));
  7820. fin.read_raw(&ftype, sizeof(ftype));
  7821. if (n_dims != 1 && n_dims != 2) {
  7822. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  7823. return 1;
  7824. }
  7825. int32_t ne[2] = { 1, 1 };
  7826. for (int i = 0; i < n_dims; ++i) {
  7827. fin.read_raw(&ne[i], sizeof(ne[i]));
  7828. }
  7829. std::string name;
  7830. {
  7831. GGML_ASSERT(name_len < GGML_MAX_NAME);
  7832. char buf[GGML_MAX_NAME];
  7833. fin.read_raw(buf, name_len);
  7834. name = std::string(buf, name_len);
  7835. }
  7836. // check for lora suffix
  7837. std::string lora_suffix;
  7838. if (name.length() > 6) {
  7839. lora_suffix = name.substr(name.length() - 6);
  7840. }
  7841. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  7842. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  7843. return 1;
  7844. }
  7845. // tensor type
  7846. ggml_type wtype;
  7847. switch (ftype) {
  7848. case 0: wtype = GGML_TYPE_F32; break;
  7849. case 1: wtype = GGML_TYPE_F16; break;
  7850. default:
  7851. {
  7852. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  7853. __func__, ftype);
  7854. return false;
  7855. }
  7856. }
  7857. // data offset
  7858. size_t offset = fin.tell();
  7859. offset = (offset + 31) & -32;
  7860. // skip tensor data
  7861. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  7862. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  7863. }
  7864. bool warned = false;
  7865. int n_tensors = 0;
  7866. // apply
  7867. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  7868. if (backend_cpu == nullptr) {
  7869. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  7870. return 1;
  7871. }
  7872. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  7873. std::vector<no_init<uint8_t>> read_buf;
  7874. for (const auto & it : model.tensors_by_name) {
  7875. const std::string & base_name = it.first;
  7876. ggml_tensor * model_t = it.second;
  7877. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  7878. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  7879. continue;
  7880. }
  7881. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  7882. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  7883. ggml_init_params lora_init_params = {
  7884. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  7885. /* .mem_buffer */ nullptr,
  7886. /* .no_alloc */ true,
  7887. };
  7888. ggml_context * lora_ctx = ggml_init(lora_init_params);
  7889. if (lora_ctx == nullptr) {
  7890. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  7891. ggml_backend_free(backend_cpu);
  7892. return 1;
  7893. }
  7894. // create tensors
  7895. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  7896. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  7897. ggml_set_name(loraA, metaA.name.c_str());
  7898. ggml_set_name(loraB, metaB.name.c_str());
  7899. ggml_tensor * base_t;
  7900. if (ml) {
  7901. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  7902. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  7903. return 1;
  7904. }
  7905. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  7906. } else {
  7907. base_t = ggml_dup_tensor(lora_ctx, model_t);
  7908. }
  7909. ggml_set_name(base_t, base_name.c_str());
  7910. // allocate in backend buffer
  7911. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7912. if (lora_buf == nullptr) {
  7913. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  7914. return 1;
  7915. }
  7916. // load tensor data
  7917. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  7918. read_buf.resize(ggml_nbytes(tensor));
  7919. fin.seek(tensor_meta.offset, SEEK_SET);
  7920. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  7921. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  7922. };
  7923. load_tensor(metaA, loraA);
  7924. load_tensor(metaB, loraB);
  7925. // load base model tensor data
  7926. if (ml) {
  7927. ml->load_data_for(base_t);
  7928. } else {
  7929. ggml_backend_tensor_copy(model_t, base_t);
  7930. }
  7931. if (ggml_is_quantized(base_t->type) && !warned) {
  7932. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  7933. "use a f16 or f32 base model with --lora-base\n", __func__);
  7934. warned = true;
  7935. }
  7936. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  7937. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  7938. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  7939. ggml_free(lora_ctx);
  7940. ggml_backend_buffer_free(lora_buf);
  7941. ggml_backend_free(backend_cpu);
  7942. return 1;
  7943. }
  7944. auto build_lora_graph = [&]() {
  7945. // w = w + BA*s
  7946. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  7947. ggml_set_name(BA, "BA");
  7948. if (scaling != 1.0f) {
  7949. BA = ggml_scale(lora_ctx, BA, scaling);
  7950. ggml_set_name(BA, "BA_scaled");
  7951. }
  7952. ggml_tensor * r;
  7953. r = ggml_add_inplace(lora_ctx, base_t, BA);
  7954. ggml_set_name(r, "r_add");
  7955. if (base_t->type != model_t->type) {
  7956. // convert the result to the model type
  7957. r = ggml_cast(lora_ctx, r, model_t->type);
  7958. ggml_set_name(r, "r_cast");
  7959. }
  7960. return r;
  7961. };
  7962. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  7963. ggml_tensor * r = build_lora_graph();
  7964. ggml_build_forward_expand(gf, r);
  7965. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7966. if (graph_buf == nullptr) {
  7967. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  7968. ggml_free(lora_ctx);
  7969. ggml_backend_buffer_free(lora_buf);
  7970. ggml_backend_free(backend_cpu);
  7971. return 1;
  7972. }
  7973. ggml_backend_graph_compute(backend_cpu, gf);
  7974. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  7975. #if 0
  7976. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  7977. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  7978. // sched compute
  7979. ggml_build_forward_expand(gf, build_graph());
  7980. ggml_backend_sched_init_measure(sched, gf);
  7981. // create the graph again, since the previous one was destroyed by the measure
  7982. ggml_graph_clear(gf);
  7983. ggml_build_forward_expand(gf, build_graph());
  7984. ggml_backend_sched_graph_compute(sched, gf);
  7985. ggml_backend_sched_free(sched);
  7986. #endif
  7987. ggml_backend_buffer_free(lora_buf);
  7988. ggml_backend_buffer_free(graph_buf);
  7989. ggml_free(lora_ctx);
  7990. n_tensors++;
  7991. if (n_tensors % 4 == 0) {
  7992. LLAMA_LOG_INFO(".");
  7993. }
  7994. }
  7995. ggml_backend_free(backend_cpu);
  7996. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  7997. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  7998. return 0;
  7999. }
  8000. //
  8001. // interface implementation
  8002. //
  8003. struct llama_model_params llama_model_default_params() {
  8004. struct llama_model_params result = {
  8005. /*.n_gpu_layers =*/ 0,
  8006. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  8007. /*.main_gpu =*/ 0,
  8008. /*.tensor_split =*/ nullptr,
  8009. /*.progress_callback =*/ nullptr,
  8010. /*.progress_callback_user_data =*/ nullptr,
  8011. /*.kv_overrides =*/ nullptr,
  8012. /*.vocab_only =*/ false,
  8013. /*.use_mmap =*/ true,
  8014. /*.use_mlock =*/ false,
  8015. };
  8016. #ifdef GGML_USE_METAL
  8017. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  8018. result.n_gpu_layers = 999;
  8019. #endif
  8020. return result;
  8021. }
  8022. struct llama_context_params llama_context_default_params() {
  8023. struct llama_context_params result = {
  8024. /*.seed =*/ LLAMA_DEFAULT_SEED,
  8025. /*.n_ctx =*/ 512,
  8026. /*.n_batch =*/ 512,
  8027. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  8028. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  8029. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  8030. /*.rope_freq_base =*/ 0.0f,
  8031. /*.rope_freq_scale =*/ 0.0f,
  8032. /*.yarn_ext_factor =*/ -1.0f,
  8033. /*.yarn_attn_factor =*/ 1.0f,
  8034. /*.yarn_beta_fast =*/ 32.0f,
  8035. /*.yarn_beta_slow =*/ 1.0f,
  8036. /*.yarn_orig_ctx =*/ 0,
  8037. /*.cb_eval =*/ nullptr,
  8038. /*.cb_eval_user_data =*/ nullptr,
  8039. /*.type_k =*/ GGML_TYPE_F16,
  8040. /*.type_v =*/ GGML_TYPE_F16,
  8041. /*.mul_mat_q =*/ true,
  8042. /*.logits_all =*/ false,
  8043. /*.embedding =*/ false,
  8044. /*.offload_kqv =*/ true,
  8045. };
  8046. return result;
  8047. }
  8048. struct llama_model_quantize_params llama_model_quantize_default_params() {
  8049. struct llama_model_quantize_params result = {
  8050. /*.nthread =*/ 0,
  8051. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  8052. /*.allow_requantize =*/ false,
  8053. /*.quantize_output_tensor =*/ true,
  8054. /*.only_copy =*/ false,
  8055. /*.pure =*/ false,
  8056. /*.imatrix =*/ nullptr,
  8057. };
  8058. return result;
  8059. }
  8060. int32_t llama_max_devices(void) {
  8061. return LLAMA_MAX_DEVICES;
  8062. }
  8063. bool llama_mmap_supported(void) {
  8064. return llama_mmap::SUPPORTED;
  8065. }
  8066. bool llama_mlock_supported(void) {
  8067. return llama_mlock::SUPPORTED;
  8068. }
  8069. void llama_backend_init(bool numa) {
  8070. ggml_time_init();
  8071. // needed to initialize f16 tables
  8072. {
  8073. struct ggml_init_params params = { 0, NULL, false };
  8074. struct ggml_context * ctx = ggml_init(params);
  8075. ggml_free(ctx);
  8076. }
  8077. if (numa) {
  8078. ggml_numa_init();
  8079. }
  8080. #ifdef GGML_USE_MPI
  8081. ggml_mpi_backend_init();
  8082. #endif
  8083. }
  8084. void llama_backend_free(void) {
  8085. #ifdef GGML_USE_MPI
  8086. ggml_mpi_backend_free();
  8087. #endif
  8088. ggml_quantize_free();
  8089. }
  8090. int64_t llama_time_us(void) {
  8091. return ggml_time_us();
  8092. }
  8093. struct llama_model * llama_load_model_from_file(
  8094. const char * path_model,
  8095. struct llama_model_params params) {
  8096. ggml_time_init();
  8097. llama_model * model = new llama_model;
  8098. unsigned cur_percentage = 0;
  8099. if (params.progress_callback == NULL) {
  8100. params.progress_callback_user_data = &cur_percentage;
  8101. params.progress_callback = [](float progress, void * ctx) {
  8102. unsigned * cur_percentage_p = (unsigned *) ctx;
  8103. unsigned percentage = (unsigned) (100 * progress);
  8104. while (percentage > *cur_percentage_p) {
  8105. *cur_percentage_p = percentage;
  8106. LLAMA_LOG_INFO(".");
  8107. if (percentage >= 100) {
  8108. LLAMA_LOG_INFO("\n");
  8109. }
  8110. }
  8111. return true;
  8112. };
  8113. }
  8114. int status = llama_model_load(path_model, *model, params);
  8115. GGML_ASSERT(status <= 0);
  8116. if (status < 0) {
  8117. if (status == -1) {
  8118. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  8119. } else if (status == -2) {
  8120. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  8121. }
  8122. delete model;
  8123. return nullptr;
  8124. }
  8125. return model;
  8126. }
  8127. void llama_free_model(struct llama_model * model) {
  8128. delete model;
  8129. }
  8130. struct llama_context * llama_new_context_with_model(
  8131. struct llama_model * model,
  8132. struct llama_context_params params) {
  8133. if (!model) {
  8134. return nullptr;
  8135. }
  8136. llama_context * ctx = new llama_context(*model);
  8137. const auto & hparams = model->hparams;
  8138. auto & cparams = ctx->cparams;
  8139. cparams.n_batch = params.n_batch;
  8140. cparams.n_threads = params.n_threads;
  8141. cparams.n_threads_batch = params.n_threads_batch;
  8142. cparams.yarn_ext_factor = params.yarn_ext_factor;
  8143. cparams.yarn_attn_factor = params.yarn_attn_factor;
  8144. cparams.yarn_beta_fast = params.yarn_beta_fast;
  8145. cparams.yarn_beta_slow = params.yarn_beta_slow;
  8146. cparams.mul_mat_q = params.mul_mat_q;
  8147. cparams.offload_kqv = params.offload_kqv;
  8148. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  8149. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  8150. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  8151. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  8152. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  8153. hparams.n_ctx_train;
  8154. cparams.cb_eval = params.cb_eval;
  8155. cparams.cb_eval_user_data = params.cb_eval_user_data;
  8156. auto rope_scaling_type = params.rope_scaling_type;
  8157. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  8158. rope_scaling_type = hparams.rope_scaling_type_train;
  8159. }
  8160. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  8161. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  8162. }
  8163. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  8164. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  8165. }
  8166. if (params.seed == LLAMA_DEFAULT_SEED) {
  8167. params.seed = time(NULL);
  8168. }
  8169. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  8170. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  8171. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  8172. ctx->rng = std::mt19937(params.seed);
  8173. ctx->logits_all = params.logits_all;
  8174. const ggml_type type_k = params.type_k;
  8175. const ggml_type type_v = params.type_v;
  8176. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  8177. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  8178. if (!hparams.vocab_only) {
  8179. // initialize backends
  8180. #ifdef GGML_USE_METAL
  8181. if (model->n_gpu_layers > 0) {
  8182. ctx->backend_metal = ggml_backend_metal_init();
  8183. if (ctx->backend_metal == nullptr) {
  8184. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  8185. llama_free(ctx);
  8186. return nullptr;
  8187. }
  8188. ctx->backends.push_back(ctx->backend_metal);
  8189. }
  8190. #elif defined(GGML_USE_CUBLAS)
  8191. if (model->n_gpu_layers > 0) {
  8192. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  8193. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  8194. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  8195. if (backend == nullptr) {
  8196. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  8197. llama_free(ctx);
  8198. return nullptr;
  8199. }
  8200. ctx->backends.push_back(backend);
  8201. } else {
  8202. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  8203. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  8204. ggml_backend_t backend = ggml_backend_cuda_init(device);
  8205. if (backend == nullptr) {
  8206. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  8207. llama_free(ctx);
  8208. return nullptr;
  8209. }
  8210. ctx->backends.push_back(backend);
  8211. }
  8212. }
  8213. }
  8214. #endif
  8215. ctx->backend_cpu = ggml_backend_cpu_init();
  8216. if (ctx->backend_cpu == nullptr) {
  8217. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  8218. llama_free(ctx);
  8219. return nullptr;
  8220. }
  8221. ctx->backends.push_back(ctx->backend_cpu);
  8222. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  8223. cparams.n_ctx, cparams.offload_kqv)) {
  8224. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  8225. llama_free(ctx);
  8226. return nullptr;
  8227. }
  8228. {
  8229. size_t memory_size_k = 0;
  8230. size_t memory_size_v = 0;
  8231. for (auto & k : ctx->kv_self.k_l) {
  8232. memory_size_k += ggml_nbytes(k);
  8233. }
  8234. for (auto & v : ctx->kv_self.v_l) {
  8235. memory_size_v += ggml_nbytes(v);
  8236. }
  8237. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  8238. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  8239. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  8240. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  8241. }
  8242. // resized during inference, reserve maximum
  8243. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  8244. if (params.embedding){
  8245. ctx->embedding.resize(hparams.n_embd);
  8246. }
  8247. {
  8248. // buffer types used for the compute buffer of each backend
  8249. std::vector<ggml_backend_buffer_type_t> backend_buft;
  8250. for (auto * backend : ctx->backends) {
  8251. if (ggml_backend_is_cpu(backend)) {
  8252. // use host buffers for the CPU backend compute buffer
  8253. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  8254. } else {
  8255. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  8256. }
  8257. }
  8258. // buffer used to store the computation graph and the tensor meta data
  8259. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  8260. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  8261. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8262. // build worst-case graph
  8263. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  8264. int n_past = cparams.n_ctx - n_tokens;
  8265. 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
  8266. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  8267. // initialize scheduler with the worst-case graph
  8268. ggml_backend_sched_init_measure(ctx->sched, gf);
  8269. // note: the number of splits during measure is higher than during inference due to the kv shift
  8270. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  8271. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  8272. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8273. for (ggml_backend_t backend : ctx->backends) {
  8274. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  8275. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  8276. ggml_backend_buffer_name(buf),
  8277. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8278. }
  8279. }
  8280. }
  8281. #ifdef GGML_USE_MPI
  8282. ctx->ctx_mpi = ggml_mpi_init();
  8283. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  8284. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  8285. // TODO: needs fix after #3228
  8286. GGML_ASSERT(false && "not implemented");
  8287. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  8288. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  8289. llama_backend_free();
  8290. exit(1);
  8291. }
  8292. #endif
  8293. return ctx;
  8294. }
  8295. void llama_free(struct llama_context * ctx) {
  8296. delete ctx;
  8297. }
  8298. const llama_model * llama_get_model(const struct llama_context * ctx) {
  8299. return &ctx->model;
  8300. }
  8301. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  8302. return ctx->cparams.n_ctx;
  8303. }
  8304. uint32_t llama_n_batch(const struct llama_context * ctx) {
  8305. return ctx->cparams.n_batch;
  8306. }
  8307. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  8308. return model->vocab.type;
  8309. }
  8310. int32_t llama_n_vocab(const struct llama_model * model) {
  8311. return model->vocab.id_to_token.size();
  8312. }
  8313. int32_t llama_n_ctx_train(const struct llama_model * model) {
  8314. return model->hparams.n_ctx_train;
  8315. }
  8316. int32_t llama_n_embd(const struct llama_model * model) {
  8317. return model->hparams.n_embd;
  8318. }
  8319. float llama_rope_freq_scale_train(const struct llama_model * model) {
  8320. return model->hparams.rope_freq_scale_train;
  8321. }
  8322. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  8323. const auto & it = model->gguf_kv.find(key);
  8324. if (it == model->gguf_kv.end()) {
  8325. if (buf_size > 0) {
  8326. buf[0] = '\0';
  8327. }
  8328. return -1;
  8329. }
  8330. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8331. }
  8332. int32_t llama_model_meta_count(const struct llama_model * model) {
  8333. return (int)model->gguf_kv.size();
  8334. }
  8335. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  8336. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8337. if (buf_size > 0) {
  8338. buf[0] = '\0';
  8339. }
  8340. return -1;
  8341. }
  8342. auto it = model->gguf_kv.begin();
  8343. std::advance(it, i);
  8344. return snprintf(buf, buf_size, "%s", it->first.c_str());
  8345. }
  8346. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  8347. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8348. if (buf_size > 0) {
  8349. buf[0] = '\0';
  8350. }
  8351. return -1;
  8352. }
  8353. auto it = model->gguf_kv.begin();
  8354. std::advance(it, i);
  8355. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8356. }
  8357. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  8358. return snprintf(buf, buf_size, "%s %s %s",
  8359. llama_model_arch_name(model->arch).c_str(),
  8360. llama_model_type_name(model->type),
  8361. llama_model_ftype_name(model->ftype).c_str());
  8362. }
  8363. uint64_t llama_model_size(const struct llama_model * model) {
  8364. uint64_t size = 0;
  8365. for (const auto & it : model->tensors_by_name) {
  8366. size += ggml_nbytes(it.second);
  8367. }
  8368. return size;
  8369. }
  8370. uint64_t llama_model_n_params(const struct llama_model * model) {
  8371. uint64_t nparams = 0;
  8372. for (const auto & it : model->tensors_by_name) {
  8373. nparams += ggml_nelements(it.second);
  8374. }
  8375. return nparams;
  8376. }
  8377. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  8378. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  8379. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  8380. return it.first == name;
  8381. });
  8382. if (it == model->tensors_by_name.end()) {
  8383. return nullptr;
  8384. }
  8385. return it->second;
  8386. }
  8387. uint32_t llama_model_quantize(
  8388. const char * fname_inp,
  8389. const char * fname_out,
  8390. const llama_model_quantize_params * params) {
  8391. try {
  8392. llama_model_quantize_internal(fname_inp, fname_out, params);
  8393. return 0;
  8394. } catch (const std::exception & err) {
  8395. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  8396. return 1;
  8397. }
  8398. }
  8399. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  8400. try {
  8401. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  8402. } catch (const std::exception & err) {
  8403. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8404. return 1;
  8405. }
  8406. }
  8407. 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) {
  8408. try {
  8409. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  8410. } catch (const std::exception & err) {
  8411. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8412. return 1;
  8413. }
  8414. }
  8415. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  8416. struct llama_kv_cache_view result = {
  8417. /*.n_cells = */ 0,
  8418. /*.n_max_seq = */ n_max_seq,
  8419. /*.token_count = */ 0,
  8420. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  8421. /*.max_contiguous = */ 0,
  8422. /*.max_contiguous_idx = */ -1,
  8423. /*.cells = */ nullptr,
  8424. /*.cells_sequences = */ nullptr,
  8425. };
  8426. return result;
  8427. }
  8428. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  8429. if (view->cells != nullptr) {
  8430. free(view->cells);
  8431. view->cells = nullptr;
  8432. }
  8433. if (view->cells_sequences != nullptr) {
  8434. free(view->cells_sequences);
  8435. view->cells_sequences = nullptr;
  8436. }
  8437. }
  8438. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  8439. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  8440. view->n_cells = int32_t(ctx->kv_self.size);
  8441. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  8442. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  8443. view->cells = (struct llama_kv_cache_view_cell *)p;
  8444. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  8445. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  8446. view->cells_sequences = (llama_seq_id *)p;
  8447. }
  8448. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  8449. llama_kv_cache_view_cell * c_curr = view->cells;
  8450. llama_seq_id * cs_curr = view->cells_sequences;
  8451. int32_t used_cells = 0;
  8452. int32_t token_count = 0;
  8453. int32_t curr_contig_idx = -1;
  8454. uint32_t max_contig = 0;
  8455. int32_t max_contig_idx = -1;
  8456. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  8457. const size_t curr_size = kv_cells[i].seq_id.size();
  8458. token_count += curr_size;
  8459. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  8460. if (curr_size > 0) {
  8461. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  8462. max_contig = i - curr_contig_idx;
  8463. max_contig_idx = curr_contig_idx;
  8464. }
  8465. curr_contig_idx = -1;
  8466. } else if (curr_contig_idx < 0) {
  8467. curr_contig_idx = i;
  8468. }
  8469. int seq_idx = 0;
  8470. for (const llama_seq_id it : kv_cells[i].seq_id) {
  8471. if (seq_idx >= view->n_max_seq) {
  8472. break;
  8473. }
  8474. cs_curr[seq_idx] = it;
  8475. seq_idx++;
  8476. }
  8477. if (seq_idx != 0) {
  8478. used_cells++;
  8479. }
  8480. for (; seq_idx < view->n_max_seq; seq_idx++) {
  8481. cs_curr[seq_idx] = -1;
  8482. }
  8483. }
  8484. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  8485. max_contig_idx = curr_contig_idx;
  8486. max_contig = kv_cells.size() - curr_contig_idx;
  8487. }
  8488. view->max_contiguous = max_contig;
  8489. view->max_contiguous_idx = max_contig_idx;
  8490. view->token_count = token_count;
  8491. view->used_cells = used_cells;
  8492. if (uint32_t(used_cells) != ctx->kv_self.used) {
  8493. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  8494. __func__, ctx->kv_self.used, used_cells);
  8495. }
  8496. }
  8497. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  8498. int result = 0;
  8499. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  8500. result += ctx->kv_self.cells[i].seq_id.size();
  8501. }
  8502. return result;
  8503. }
  8504. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  8505. return ctx->kv_self.used;
  8506. }
  8507. void llama_kv_cache_clear(struct llama_context * ctx) {
  8508. llama_kv_cache_clear(ctx->kv_self);
  8509. }
  8510. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  8511. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  8512. }
  8513. 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) {
  8514. if (seq_id_src == seq_id_dst) {
  8515. return;
  8516. }
  8517. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  8518. }
  8519. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  8520. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  8521. }
  8522. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  8523. if (delta == 0) {
  8524. return;
  8525. }
  8526. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  8527. }
  8528. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  8529. if (d == 1) {
  8530. return;
  8531. }
  8532. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  8533. }
  8534. // Returns the *maximum* size of the state
  8535. size_t llama_get_state_size(const struct llama_context * ctx) {
  8536. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  8537. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  8538. const size_t s_rng_size = sizeof(size_t);
  8539. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  8540. const size_t s_logits_size = sizeof(size_t);
  8541. // assume worst case for logits although only currently set ones are serialized
  8542. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  8543. const size_t s_embedding_size = sizeof(size_t);
  8544. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  8545. const size_t s_kv_size = sizeof(size_t);
  8546. const size_t s_kv_ntok = sizeof(int);
  8547. const size_t s_kv = ctx->kv_self.total_size();
  8548. const size_t s_total = (
  8549. + s_rng_size
  8550. + s_rng
  8551. + s_logits_size
  8552. + s_logits
  8553. + s_embedding_size
  8554. + s_embedding
  8555. + s_kv_size
  8556. + s_kv_ntok
  8557. + s_kv
  8558. );
  8559. return s_total;
  8560. }
  8561. // llama_context_data
  8562. struct llama_data_context {
  8563. virtual void write(const void * src, size_t size) = 0;
  8564. virtual size_t get_size_written() = 0;
  8565. virtual ~llama_data_context() = default;
  8566. };
  8567. struct llama_data_buffer_context : llama_data_context {
  8568. uint8_t * ptr;
  8569. size_t size_written = 0;
  8570. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  8571. void write(const void * src, size_t size) override {
  8572. memcpy(ptr, src, size);
  8573. ptr += size;
  8574. size_written += size;
  8575. }
  8576. size_t get_size_written() override {
  8577. return size_written;
  8578. }
  8579. };
  8580. struct llama_data_file_context : llama_data_context {
  8581. llama_file * file;
  8582. size_t size_written = 0;
  8583. llama_data_file_context(llama_file * f) : file(f) {}
  8584. void write(const void * src, size_t size) override {
  8585. file->write_raw(src, size);
  8586. size_written += size;
  8587. }
  8588. size_t get_size_written() override {
  8589. return size_written;
  8590. }
  8591. };
  8592. /** copy state data into either a buffer or file depending on the passed in context
  8593. *
  8594. * file context:
  8595. * llama_file file("/path", "wb");
  8596. * llama_data_file_context data_ctx(&file);
  8597. * llama_copy_state_data(ctx, &data_ctx);
  8598. *
  8599. * buffer context:
  8600. * std::vector<uint8_t> buf(max_size, 0);
  8601. * llama_data_buffer_context data_ctx(&buf.data());
  8602. * llama_copy_state_data(ctx, &data_ctx);
  8603. *
  8604. */
  8605. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  8606. // copy rng
  8607. {
  8608. std::ostringstream rng_ss;
  8609. rng_ss << ctx->rng;
  8610. const std::string & rng_str = rng_ss.str();
  8611. const size_t rng_size = rng_str.size();
  8612. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8613. data_ctx->write(&rng_size, sizeof(rng_size));
  8614. data_ctx->write(rng_str.data(), rng_size);
  8615. }
  8616. // copy logits
  8617. {
  8618. const size_t logits_size = ctx->logits.size();
  8619. data_ctx->write(&logits_size, sizeof(logits_size));
  8620. if (logits_size) {
  8621. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  8622. }
  8623. }
  8624. // copy embeddings
  8625. {
  8626. const size_t embedding_size = ctx->embedding.size();
  8627. data_ctx->write(&embedding_size, sizeof(embedding_size));
  8628. if (embedding_size) {
  8629. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  8630. }
  8631. }
  8632. // copy kv cache
  8633. {
  8634. const auto & kv_self = ctx->kv_self;
  8635. const auto & hparams = ctx->model.hparams;
  8636. const auto & cparams = ctx->cparams;
  8637. const auto n_layer = hparams.n_layer;
  8638. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  8639. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  8640. const auto n_ctx = cparams.n_ctx;
  8641. const size_t kv_buf_size = kv_self.total_size();
  8642. const uint32_t kv_head = kv_self.head;
  8643. const uint32_t kv_size = kv_self.size;
  8644. const uint32_t kv_used = kv_self.used;
  8645. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  8646. data_ctx->write(&kv_head, sizeof(kv_head));
  8647. data_ctx->write(&kv_size, sizeof(kv_size));
  8648. data_ctx->write(&kv_used, sizeof(kv_used));
  8649. if (kv_buf_size) {
  8650. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8651. std::vector<uint8_t> tmp_buf;
  8652. for (int il = 0; il < (int) n_layer; ++il) {
  8653. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  8654. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  8655. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8656. // v is not contiguous, copy row by row
  8657. tmp_buf.resize(elt_size*kv_head);
  8658. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8659. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  8660. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8661. }
  8662. }
  8663. }
  8664. for (uint32_t i = 0; i < kv_size; ++i) {
  8665. const auto & cell = kv_self.cells[i];
  8666. const llama_pos pos = cell.pos;
  8667. const size_t seq_id_size = cell.seq_id.size();
  8668. data_ctx->write(&pos, sizeof(pos));
  8669. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  8670. for (auto seq_id : cell.seq_id) {
  8671. data_ctx->write(&seq_id, sizeof(seq_id));
  8672. }
  8673. }
  8674. }
  8675. }
  8676. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  8677. llama_data_buffer_context data_ctx(dst);
  8678. llama_copy_state_data_internal(ctx, &data_ctx);
  8679. return data_ctx.get_size_written();
  8680. }
  8681. // Sets the state reading from the specified source address
  8682. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  8683. uint8_t * inp = src;
  8684. // set rng
  8685. {
  8686. size_t rng_size;
  8687. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  8688. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8689. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  8690. std::istringstream rng_ss(rng_str);
  8691. rng_ss >> ctx->rng;
  8692. GGML_ASSERT(!rng_ss.fail());
  8693. }
  8694. // set logits
  8695. {
  8696. size_t logits_size;
  8697. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  8698. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  8699. if (logits_size) {
  8700. ctx->logits.resize(logits_size);
  8701. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  8702. inp += logits_size * sizeof(float);
  8703. }
  8704. }
  8705. // set embeddings
  8706. {
  8707. size_t embedding_size;
  8708. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  8709. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  8710. if (embedding_size) {
  8711. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  8712. inp += embedding_size * sizeof(float);
  8713. }
  8714. }
  8715. // set kv cache
  8716. {
  8717. const auto & kv_self = ctx->kv_self;
  8718. const auto & hparams = ctx->model.hparams;
  8719. const auto & cparams = ctx->cparams;
  8720. const int n_layer = hparams.n_layer;
  8721. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  8722. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  8723. const int n_ctx = cparams.n_ctx;
  8724. size_t kv_buf_size;
  8725. uint32_t kv_head;
  8726. uint32_t kv_size;
  8727. uint32_t kv_used;
  8728. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  8729. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  8730. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  8731. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  8732. if (kv_buf_size) {
  8733. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  8734. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8735. for (int il = 0; il < (int) n_layer; ++il) {
  8736. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  8737. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  8738. inp += k_size;
  8739. // v is not contiguous, copy row by row
  8740. size_t v_row_size = elt_size*kv_head;
  8741. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8742. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  8743. inp += v_row_size;
  8744. }
  8745. }
  8746. }
  8747. ctx->kv_self.head = kv_head;
  8748. ctx->kv_self.size = kv_size;
  8749. ctx->kv_self.used = kv_used;
  8750. ctx->kv_self.cells.resize(kv_size);
  8751. for (uint32_t i = 0; i < kv_size; ++i) {
  8752. llama_pos pos;
  8753. size_t seq_id_size;
  8754. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  8755. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  8756. ctx->kv_self.cells[i].pos = pos;
  8757. llama_seq_id seq_id;
  8758. for (size_t j = 0; j < seq_id_size; ++j) {
  8759. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  8760. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  8761. }
  8762. }
  8763. }
  8764. const size_t nread = inp - src;
  8765. const size_t max_size = llama_get_state_size(ctx);
  8766. GGML_ASSERT(nread <= max_size);
  8767. return nread;
  8768. }
  8769. 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) {
  8770. llama_file file(path_session, "rb");
  8771. // sanity checks
  8772. {
  8773. const uint32_t magic = file.read_u32();
  8774. const uint32_t version = file.read_u32();
  8775. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  8776. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  8777. return false;
  8778. }
  8779. llama_hparams session_hparams;
  8780. file.read_raw(&session_hparams, sizeof(llama_hparams));
  8781. if (session_hparams != ctx->model.hparams) {
  8782. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  8783. return false;
  8784. }
  8785. }
  8786. // load the prompt
  8787. {
  8788. const uint32_t n_token_count = file.read_u32();
  8789. if (n_token_count > n_token_capacity) {
  8790. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  8791. return false;
  8792. }
  8793. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  8794. *n_token_count_out = n_token_count;
  8795. }
  8796. // restore the context state
  8797. {
  8798. const size_t n_state_size_cur = file.size - file.tell();
  8799. const size_t n_state_size_max = llama_get_state_size(ctx);
  8800. if (n_state_size_cur > n_state_size_max) {
  8801. 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);
  8802. return false;
  8803. }
  8804. std::vector<uint8_t> state_data(n_state_size_max);
  8805. file.read_raw(state_data.data(), n_state_size_cur);
  8806. llama_set_state_data(ctx, state_data.data());
  8807. }
  8808. return true;
  8809. }
  8810. 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) {
  8811. try {
  8812. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  8813. } catch (const std::exception & err) {
  8814. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  8815. return false;
  8816. }
  8817. }
  8818. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  8819. llama_file file(path_session, "wb");
  8820. file.write_u32(LLAMA_SESSION_MAGIC);
  8821. file.write_u32(LLAMA_SESSION_VERSION);
  8822. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  8823. // save the prompt
  8824. file.write_u32((uint32_t) n_token_count);
  8825. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  8826. // save the context state using stream saving
  8827. llama_data_file_context data_ctx(&file);
  8828. llama_copy_state_data_internal(ctx, &data_ctx);
  8829. return true;
  8830. }
  8831. int llama_eval(
  8832. struct llama_context * ctx,
  8833. llama_token * tokens,
  8834. int32_t n_tokens,
  8835. int32_t n_past) {
  8836. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8837. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  8838. if (ret < 0) {
  8839. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8840. }
  8841. return ret;
  8842. }
  8843. int llama_eval_embd(
  8844. struct llama_context * ctx,
  8845. float * embd,
  8846. int32_t n_tokens,
  8847. int32_t n_past) {
  8848. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8849. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  8850. const int ret = llama_decode_internal(*ctx, batch);
  8851. if (ret < 0) {
  8852. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8853. }
  8854. return ret;
  8855. }
  8856. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  8857. ctx->cparams.n_threads = n_threads;
  8858. ctx->cparams.n_threads_batch = n_threads_batch;
  8859. }
  8860. struct llama_batch llama_batch_get_one(
  8861. llama_token * tokens,
  8862. int32_t n_tokens,
  8863. llama_pos pos_0,
  8864. llama_seq_id seq_id) {
  8865. return {
  8866. /*n_tokens =*/ n_tokens,
  8867. /*tokens =*/ tokens,
  8868. /*embd =*/ nullptr,
  8869. /*pos =*/ nullptr,
  8870. /*n_seq_id =*/ nullptr,
  8871. /*seq_id =*/ nullptr,
  8872. /*logits =*/ nullptr,
  8873. /*all_pos_0 =*/ pos_0,
  8874. /*all_pos_1 =*/ 1,
  8875. /*all_seq_id =*/ seq_id,
  8876. };
  8877. }
  8878. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  8879. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  8880. if (embd) {
  8881. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  8882. } else {
  8883. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  8884. }
  8885. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  8886. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  8887. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  8888. for (int i = 0; i < n_tokens; ++i) {
  8889. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  8890. }
  8891. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  8892. return batch;
  8893. }
  8894. void llama_batch_free(struct llama_batch batch) {
  8895. if (batch.token) free(batch.token);
  8896. if (batch.embd) free(batch.embd);
  8897. if (batch.pos) free(batch.pos);
  8898. if (batch.n_seq_id) free(batch.n_seq_id);
  8899. if (batch.seq_id) {
  8900. for (int i = 0; i < batch.n_tokens; ++i) {
  8901. free(batch.seq_id[i]);
  8902. }
  8903. free(batch.seq_id);
  8904. }
  8905. if (batch.logits) free(batch.logits);
  8906. }
  8907. int32_t llama_decode(
  8908. struct llama_context * ctx,
  8909. struct llama_batch batch) {
  8910. const int ret = llama_decode_internal(*ctx, batch);
  8911. if (ret < 0) {
  8912. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8913. }
  8914. return ret;
  8915. }
  8916. float * llama_get_logits(struct llama_context * ctx) {
  8917. return ctx->logits.data();
  8918. }
  8919. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  8920. assert(ctx->logits_valid.at(i));
  8921. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  8922. }
  8923. float * llama_get_embeddings(struct llama_context * ctx) {
  8924. return ctx->embedding.data();
  8925. }
  8926. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  8927. return model->vocab.id_to_token[token].text.c_str();
  8928. }
  8929. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  8930. return model->vocab.id_to_token[token].score;
  8931. }
  8932. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  8933. return model->vocab.id_to_token[token].type;
  8934. }
  8935. llama_token llama_token_bos(const struct llama_model * model) {
  8936. return model->vocab.special_bos_id;
  8937. }
  8938. llama_token llama_token_eos(const struct llama_model * model) {
  8939. return model->vocab.special_eos_id;
  8940. }
  8941. llama_token llama_token_nl(const struct llama_model * model) {
  8942. return model->vocab.linefeed_id;
  8943. }
  8944. int32_t llama_add_bos_token(const struct llama_model * model) {
  8945. return model->vocab.special_add_bos;
  8946. }
  8947. int32_t llama_add_eos_token(const struct llama_model * model) {
  8948. return model->vocab.special_add_eos;
  8949. }
  8950. llama_token llama_token_prefix(const struct llama_model * model) {
  8951. return model->vocab.special_prefix_id;
  8952. }
  8953. llama_token llama_token_middle(const struct llama_model * model) {
  8954. return model->vocab.special_middle_id;
  8955. }
  8956. llama_token llama_token_suffix(const struct llama_model * model) {
  8957. return model->vocab.special_suffix_id;
  8958. }
  8959. llama_token llama_token_eot(const struct llama_model * model) {
  8960. return model->vocab.special_eot_id;
  8961. }
  8962. int32_t llama_tokenize(
  8963. const struct llama_model * model,
  8964. const char * text,
  8965. int32_t text_len,
  8966. llama_token * tokens,
  8967. int32_t n_max_tokens,
  8968. bool add_bos,
  8969. bool special) {
  8970. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  8971. if (n_max_tokens < (int) res.size()) {
  8972. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  8973. return -((int) res.size());
  8974. }
  8975. for (size_t i = 0; i < res.size(); i++) {
  8976. tokens[i] = res[i];
  8977. }
  8978. return res.size();
  8979. }
  8980. static std::string llama_decode_text(const std::string & text) {
  8981. std::string decoded_text;
  8982. auto unicode_sequences = codepoints_from_utf8(text);
  8983. for (auto& unicode_sequence : unicode_sequences) {
  8984. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  8985. }
  8986. return decoded_text;
  8987. }
  8988. // does not write null-terminator to buf
  8989. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  8990. if (0 <= token && token < llama_n_vocab(model)) {
  8991. switch (llama_vocab_get_type(model->vocab)) {
  8992. case LLAMA_VOCAB_TYPE_SPM: {
  8993. // NOTE: we accept all unsupported token types,
  8994. // suppressing them like CONTROL tokens.
  8995. if (llama_is_normal_token(model->vocab, token)) {
  8996. std::string result = model->vocab.id_to_token[token].text;
  8997. llama_unescape_whitespace(result);
  8998. if (length < (int) result.length()) {
  8999. return -(int) result.length();
  9000. }
  9001. memcpy(buf, result.c_str(), result.length());
  9002. return result.length();
  9003. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9004. std::string result = model->vocab.id_to_token[token].text;
  9005. if (length < (int) result.length()) {
  9006. return -result.length();
  9007. }
  9008. memcpy(buf, result.c_str(), result.length());
  9009. return result.length();
  9010. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  9011. if (length < 3) {
  9012. return -3;
  9013. }
  9014. memcpy(buf, "\xe2\x96\x85", 3);
  9015. return 3;
  9016. } else if (llama_is_control_token(model->vocab, token)) {
  9017. ;
  9018. } else if (llama_is_byte_token(model->vocab, token)) {
  9019. if (length < 1) {
  9020. return -1;
  9021. }
  9022. buf[0] = llama_token_to_byte(model->vocab, token);
  9023. return 1;
  9024. }
  9025. break;
  9026. }
  9027. case LLAMA_VOCAB_TYPE_BPE: {
  9028. // NOTE: we accept all unsupported token types,
  9029. // suppressing them like CONTROL tokens.
  9030. if (llama_is_normal_token(model->vocab, token)) {
  9031. std::string result = model->vocab.id_to_token[token].text;
  9032. result = llama_decode_text(result);
  9033. if (length < (int) result.length()) {
  9034. return -(int) result.length();
  9035. }
  9036. memcpy(buf, result.c_str(), result.length());
  9037. return result.length();
  9038. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9039. std::string result = model->vocab.id_to_token[token].text;
  9040. if (length < (int) result.length()) {
  9041. return -result.length();
  9042. }
  9043. memcpy(buf, result.c_str(), result.length());
  9044. return result.length();
  9045. } else if (llama_is_control_token(model->vocab, token)) {
  9046. ;
  9047. }
  9048. break;
  9049. }
  9050. default:
  9051. GGML_ASSERT(false);
  9052. }
  9053. }
  9054. return 0;
  9055. }
  9056. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  9057. struct llama_timings result = {
  9058. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  9059. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  9060. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  9061. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  9062. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  9063. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  9064. /*.n_sample =*/ std::max(1, ctx->n_sample),
  9065. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  9066. /*.n_eval =*/ std::max(1, ctx->n_eval),
  9067. };
  9068. return result;
  9069. }
  9070. void llama_print_timings(struct llama_context * ctx) {
  9071. const llama_timings timings = llama_get_timings(ctx);
  9072. LLAMA_LOG_INFO("\n");
  9073. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  9074. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9075. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  9076. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  9077. __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);
  9078. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9079. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  9080. 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));
  9081. }
  9082. void llama_reset_timings(struct llama_context * ctx) {
  9083. ctx->t_start_us = ggml_time_us();
  9084. ctx->t_sample_us = ctx->n_sample = 0;
  9085. ctx->t_eval_us = ctx->n_eval = 0;
  9086. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  9087. }
  9088. const char * llama_print_system_info(void) {
  9089. static std::string s;
  9090. s = "";
  9091. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  9092. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  9093. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  9094. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  9095. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  9096. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  9097. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  9098. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  9099. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  9100. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  9101. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  9102. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  9103. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  9104. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  9105. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  9106. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  9107. return s.c_str();
  9108. }
  9109. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  9110. fprintf(stream, "\n");
  9111. fprintf(stream, "###########\n");
  9112. fprintf(stream, "# Timings #\n");
  9113. fprintf(stream, "###########\n");
  9114. fprintf(stream, "\n");
  9115. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  9116. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  9117. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  9118. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  9119. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  9120. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  9121. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  9122. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  9123. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  9124. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  9125. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  9126. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  9127. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  9128. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  9129. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  9130. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  9131. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  9132. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  9133. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  9134. }
  9135. // For internal test use
  9136. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  9137. struct llama_context * ctx
  9138. ) {
  9139. return ctx->model.tensors_by_name;
  9140. }
  9141. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  9142. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  9143. g_state.log_callback_user_data = user_data;
  9144. #ifdef GGML_USE_METAL
  9145. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  9146. #endif
  9147. }
  9148. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  9149. va_list args_copy;
  9150. va_copy(args_copy, args);
  9151. char buffer[128];
  9152. int len = vsnprintf(buffer, 128, format, args);
  9153. if (len < 128) {
  9154. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  9155. } else {
  9156. char* buffer2 = new char[len+1];
  9157. vsnprintf(buffer2, len+1, format, args_copy);
  9158. buffer2[len] = 0;
  9159. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  9160. delete[] buffer2;
  9161. }
  9162. va_end(args_copy);
  9163. }
  9164. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  9165. va_list args;
  9166. va_start(args, format);
  9167. llama_log_internal_v(level, format, args);
  9168. va_end(args);
  9169. }
  9170. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  9171. (void) level;
  9172. (void) user_data;
  9173. fputs(text, stderr);
  9174. fflush(stderr);
  9175. }