llama.cpp 338 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #ifdef GGML_USE_CUBLAS
  7. # include "ggml-cuda.h"
  8. #elif defined(GGML_USE_CLBLAST)
  9. # include "ggml-opencl.h"
  10. #endif
  11. #ifdef GGML_USE_METAL
  12. # include "ggml-metal.h"
  13. #endif
  14. #ifdef GGML_USE_MPI
  15. # include "ggml-mpi.h"
  16. #endif
  17. #ifndef QK_K
  18. # ifdef GGML_QKK_64
  19. # define QK_K 64
  20. # else
  21. # define QK_K 256
  22. # endif
  23. #endif
  24. #ifdef __has_include
  25. #if __has_include(<unistd.h>)
  26. #include <unistd.h>
  27. #if defined(_POSIX_MAPPED_FILES)
  28. #include <sys/mman.h>
  29. #endif
  30. #if defined(_POSIX_MEMLOCK_RANGE)
  31. #include <sys/resource.h>
  32. #endif
  33. #endif
  34. #endif
  35. #if defined(_WIN32)
  36. #define WIN32_LEAN_AND_MEAN
  37. #ifndef NOMINMAX
  38. #define NOMINMAX
  39. #endif
  40. #include <windows.h>
  41. #include <io.h>
  42. #include <stdio.h> // for _fseeki64
  43. #endif
  44. #include <algorithm>
  45. #include <array>
  46. #include <cassert>
  47. #include <cinttypes>
  48. #include <climits>
  49. #include <cstdarg>
  50. #include <cstddef>
  51. #include <cstdint>
  52. #include <cstdio>
  53. #include <cstring>
  54. #include <ctime>
  55. #include <forward_list>
  56. #include <fstream>
  57. #include <functional>
  58. #include <initializer_list>
  59. #include <map>
  60. #include <memory>
  61. #include <mutex>
  62. #include <numeric>
  63. #include <queue>
  64. #include <random>
  65. #include <regex>
  66. #include <set>
  67. #include <sstream>
  68. #include <thread>
  69. #include <unordered_map>
  70. #if defined(_MSC_VER)
  71. #pragma warning(disable: 4244 4267) // possible loss of data
  72. #endif
  73. #ifdef __GNUC__
  74. #ifdef __MINGW32__
  75. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  76. #else
  77. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  78. #endif
  79. #else
  80. #define LLAMA_ATTRIBUTE_FORMAT(...)
  81. #endif
  82. //
  83. // logging
  84. //
  85. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  86. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  87. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  88. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  89. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  90. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  91. //
  92. // helpers
  93. //
  94. static size_t utf8_len(char src) {
  95. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  96. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  97. return lookup[highbits];
  98. }
  99. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  100. std::string result;
  101. for (size_t pos = 0; ; pos += search.length()) {
  102. auto new_pos = s.find(search, pos);
  103. if (new_pos == std::string::npos) {
  104. result += s.substr(pos, s.size() - pos);
  105. break;
  106. }
  107. result += s.substr(pos, new_pos - pos) + replace;
  108. pos = new_pos;
  109. }
  110. s = std::move(result);
  111. }
  112. static bool is_float_close(float a, float b, float abs_tol) {
  113. // Check for non-negative tolerance
  114. if (abs_tol < 0.0) {
  115. throw std::invalid_argument("Tolerance must be non-negative");
  116. }
  117. // Exact equality check
  118. if (a == b) {
  119. return true;
  120. }
  121. // Check for infinities
  122. if (std::isinf(a) || std::isinf(b)) {
  123. return false;
  124. }
  125. // Regular comparison using the provided absolute tolerance
  126. return std::fabs(b - a) <= abs_tol;
  127. }
  128. #ifdef GGML_USE_CPU_HBM
  129. #include <hbwmalloc.h>
  130. #endif
  131. static void zeros(std::ofstream & file, size_t n) {
  132. char zero = 0;
  133. for (size_t i = 0; i < n; ++i) {
  134. file.write(&zero, 1);
  135. }
  136. }
  137. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  138. static std::string format(const char * fmt, ...) {
  139. va_list ap;
  140. va_list ap2;
  141. va_start(ap, fmt);
  142. va_copy(ap2, ap);
  143. int size = vsnprintf(NULL, 0, fmt, ap);
  144. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  145. std::vector<char> buf(size + 1);
  146. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  147. GGML_ASSERT(size2 == size);
  148. va_end(ap2);
  149. va_end(ap);
  150. return std::string(buf.data(), size);
  151. }
  152. //
  153. // gguf constants (sync with gguf.py)
  154. //
  155. enum llm_arch {
  156. LLM_ARCH_LLAMA,
  157. LLM_ARCH_FALCON,
  158. LLM_ARCH_BAICHUAN,
  159. LLM_ARCH_GPT2,
  160. LLM_ARCH_GPTJ,
  161. LLM_ARCH_GPTNEOX,
  162. LLM_ARCH_MPT,
  163. LLM_ARCH_STARCODER,
  164. LLM_ARCH_PERSIMMON,
  165. LLM_ARCH_REFACT,
  166. LLM_ARCH_BLOOM,
  167. LLM_ARCH_UNKNOWN,
  168. };
  169. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  170. { LLM_ARCH_LLAMA, "llama" },
  171. { LLM_ARCH_FALCON, "falcon" },
  172. { LLM_ARCH_GPT2, "gpt2" },
  173. { LLM_ARCH_GPTJ, "gptj" },
  174. { LLM_ARCH_GPTNEOX, "gptneox" },
  175. { LLM_ARCH_MPT, "mpt" },
  176. { LLM_ARCH_BAICHUAN, "baichuan" },
  177. { LLM_ARCH_STARCODER, "starcoder" },
  178. { LLM_ARCH_PERSIMMON, "persimmon" },
  179. { LLM_ARCH_REFACT, "refact" },
  180. { LLM_ARCH_BLOOM, "bloom" },
  181. };
  182. enum llm_kv {
  183. LLM_KV_GENERAL_ARCHITECTURE,
  184. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  185. LLM_KV_GENERAL_ALIGNMENT,
  186. LLM_KV_GENERAL_NAME,
  187. LLM_KV_GENERAL_AUTHOR,
  188. LLM_KV_GENERAL_URL,
  189. LLM_KV_GENERAL_DESCRIPTION,
  190. LLM_KV_GENERAL_LICENSE,
  191. LLM_KV_GENERAL_SOURCE_URL,
  192. LLM_KV_GENERAL_SOURCE_HF_REPO,
  193. LLM_KV_CONTEXT_LENGTH,
  194. LLM_KV_EMBEDDING_LENGTH,
  195. LLM_KV_BLOCK_COUNT,
  196. LLM_KV_FEED_FORWARD_LENGTH,
  197. LLM_KV_USE_PARALLEL_RESIDUAL,
  198. LLM_KV_TENSOR_DATA_LAYOUT,
  199. LLM_KV_ATTENTION_HEAD_COUNT,
  200. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  201. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  202. LLM_KV_ATTENTION_CLAMP_KQV,
  203. LLM_KV_ATTENTION_LAYERNORM_EPS,
  204. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  205. LLM_KV_ROPE_DIMENSION_COUNT,
  206. LLM_KV_ROPE_FREQ_BASE,
  207. LLM_KV_ROPE_SCALE_LINEAR,
  208. LLM_KV_TOKENIZER_MODEL,
  209. LLM_KV_TOKENIZER_LIST,
  210. LLM_KV_TOKENIZER_TOKEN_TYPE,
  211. LLM_KV_TOKENIZER_SCORES,
  212. LLM_KV_TOKENIZER_MERGES,
  213. LLM_KV_TOKENIZER_BOS_ID,
  214. LLM_KV_TOKENIZER_EOS_ID,
  215. LLM_KV_TOKENIZER_UNK_ID,
  216. LLM_KV_TOKENIZER_SEP_ID,
  217. LLM_KV_TOKENIZER_PAD_ID,
  218. LLM_KV_TOKENIZER_HF_JSON,
  219. LLM_KV_TOKENIZER_RWKV,
  220. };
  221. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  222. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  223. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  224. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  225. { LLM_KV_GENERAL_NAME, "general.name" },
  226. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  227. { LLM_KV_GENERAL_URL, "general.url" },
  228. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  229. { LLM_KV_GENERAL_LICENSE, "general.license" },
  230. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  231. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  232. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  233. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  234. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  235. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  236. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  237. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  238. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  239. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  240. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  241. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  242. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  243. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  244. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  245. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  246. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  247. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  248. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  249. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  250. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  251. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  252. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  253. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  254. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  255. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  256. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  257. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  258. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  259. };
  260. struct LLM_KV {
  261. LLM_KV(llm_arch arch) : arch(arch) {}
  262. llm_arch arch;
  263. std::string operator()(llm_kv kv) const {
  264. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  265. }
  266. };
  267. enum llm_tensor {
  268. LLM_TENSOR_TOKEN_EMBD,
  269. LLM_TENSOR_TOKEN_EMBD_NORM,
  270. LLM_TENSOR_POS_EMBD,
  271. LLM_TENSOR_OUTPUT,
  272. LLM_TENSOR_OUTPUT_NORM,
  273. LLM_TENSOR_ROPE_FREQS,
  274. LLM_TENSOR_ATTN_Q,
  275. LLM_TENSOR_ATTN_K,
  276. LLM_TENSOR_ATTN_V,
  277. LLM_TENSOR_ATTN_QKV,
  278. LLM_TENSOR_ATTN_OUT,
  279. LLM_TENSOR_ATTN_NORM,
  280. LLM_TENSOR_ATTN_NORM_2,
  281. LLM_TENSOR_ATTN_ROT_EMBD,
  282. LLM_TENSOR_FFN_GATE,
  283. LLM_TENSOR_FFN_DOWN,
  284. LLM_TENSOR_FFN_UP,
  285. LLM_TENSOR_FFN_NORM,
  286. LLM_TENSOR_ATTN_Q_NORM,
  287. LLM_TENSOR_ATTN_K_NORM,
  288. };
  289. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  290. {
  291. LLM_ARCH_LLAMA,
  292. {
  293. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  294. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  295. { LLM_TENSOR_OUTPUT, "output" },
  296. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  297. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  298. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  299. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  300. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  301. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  302. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  303. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  304. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  305. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  306. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  307. },
  308. },
  309. {
  310. LLM_ARCH_BAICHUAN,
  311. {
  312. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  313. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  314. { LLM_TENSOR_OUTPUT, "output" },
  315. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  316. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  317. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  318. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  319. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  320. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  321. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  322. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  323. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  324. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  325. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  326. },
  327. },
  328. {
  329. LLM_ARCH_FALCON,
  330. {
  331. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  332. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  333. { LLM_TENSOR_OUTPUT, "output" },
  334. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  335. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  336. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  337. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  338. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  339. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  340. },
  341. },
  342. {
  343. LLM_ARCH_GPT2,
  344. {
  345. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  346. },
  347. },
  348. {
  349. LLM_ARCH_GPTJ,
  350. {
  351. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  352. },
  353. },
  354. {
  355. LLM_ARCH_GPTNEOX,
  356. {
  357. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  358. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  359. { LLM_TENSOR_OUTPUT, "output" },
  360. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  361. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  362. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  363. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  364. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  365. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  366. },
  367. },
  368. {
  369. LLM_ARCH_PERSIMMON,
  370. {
  371. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  372. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  373. { LLM_TENSOR_OUTPUT, "output"},
  374. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  375. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  376. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  377. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  378. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  379. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  380. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  381. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  382. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  383. },
  384. },
  385. {
  386. LLM_ARCH_MPT,
  387. {
  388. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  389. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  390. { LLM_TENSOR_OUTPUT, "output" },
  391. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  392. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  393. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  394. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  395. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  396. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  397. },
  398. },
  399. {
  400. LLM_ARCH_STARCODER,
  401. {
  402. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  403. { LLM_TENSOR_POS_EMBD, "position_embd" },
  404. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  405. { LLM_TENSOR_OUTPUT, "output" },
  406. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  407. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  408. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  409. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  410. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  411. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  412. },
  413. },
  414. {
  415. LLM_ARCH_REFACT,
  416. {
  417. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  418. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  419. { LLM_TENSOR_OUTPUT, "output" },
  420. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  421. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  422. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  423. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  424. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  425. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  426. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  427. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  428. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  429. },
  430. },
  431. {
  432. LLM_ARCH_BLOOM,
  433. {
  434. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  435. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  436. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  437. { LLM_TENSOR_OUTPUT, "output" },
  438. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  439. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  440. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  441. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  442. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  443. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  444. },
  445. },
  446. {
  447. LLM_ARCH_UNKNOWN,
  448. {
  449. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  450. },
  451. },
  452. };
  453. static llm_arch llm_arch_from_string(const std::string & name) {
  454. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  455. if (kv.second == name) {
  456. return kv.first;
  457. }
  458. }
  459. return LLM_ARCH_UNKNOWN;
  460. }
  461. // helper to handle gguf constants
  462. // usage:
  463. //
  464. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  465. //
  466. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  467. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  468. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  469. //
  470. struct LLM_TN {
  471. LLM_TN(llm_arch arch) : arch(arch) {}
  472. llm_arch arch;
  473. std::string operator()(llm_tensor tensor) const {
  474. return LLM_TENSOR_NAMES[arch].at(tensor);
  475. }
  476. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  477. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  478. }
  479. std::string operator()(llm_tensor tensor, int bid) const {
  480. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  481. }
  482. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  483. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  484. }
  485. };
  486. //
  487. // gguf helpers
  488. //
  489. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  490. do { \
  491. const std::string skey(key); \
  492. const int kid = gguf_find_key(ctx, skey.c_str()); \
  493. if (kid >= 0) { \
  494. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  495. if (ktype != (type)) { \
  496. throw std::runtime_error(format("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype))); \
  497. } \
  498. (dst) = func(ctx, kid); \
  499. } else if (req) { \
  500. throw std::runtime_error(format("key not found in model: %s", skey.c_str())); \
  501. } \
  502. } while (0)
  503. //
  504. // ggml helpers
  505. //
  506. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  507. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  508. if (plan.work_size > 0) {
  509. buf.resize(plan.work_size);
  510. plan.work_data = buf.data();
  511. }
  512. ggml_graph_compute(graph, &plan);
  513. }
  514. //
  515. // llama helpers
  516. //
  517. #ifdef GGML_USE_CUBLAS
  518. # define llama_host_malloc(n) ggml_cuda_host_malloc(n)
  519. # define llama_host_free(data) ggml_cuda_host_free(data)
  520. #elif GGML_USE_METAL
  521. # define llama_host_malloc(n) ggml_metal_host_malloc(n)
  522. # define llama_host_free(data) ggml_metal_host_free(data)
  523. #elif GGML_USE_CPU_HBM
  524. # define llama_host_malloc(n) hbw_malloc(n)
  525. # define llama_host_free(data) if (data != NULL) hbw_free(data)
  526. #else
  527. # define llama_host_malloc(n) malloc(n)
  528. # define llama_host_free(data) free(data)
  529. #endif
  530. #if defined(_WIN32)
  531. static std::string llama_format_win_err(DWORD err) {
  532. LPSTR buf;
  533. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  534. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  535. if (!size) {
  536. return "FormatMessageA failed";
  537. }
  538. std::string ret(buf, size);
  539. LocalFree(buf);
  540. return ret;
  541. }
  542. #endif
  543. struct llama_buffer {
  544. void * data = NULL;
  545. size_t size = 0;
  546. // fallback to malloc / free
  547. // useful in cases where CUDA can try to allocate PINNED memory
  548. bool fallback = false;
  549. void resize(size_t n) {
  550. llama_host_free(data);
  551. data = llama_host_malloc(n);
  552. if (!data) {
  553. fallback = true;
  554. data = malloc(n);
  555. } else {
  556. fallback = false;
  557. }
  558. GGML_ASSERT(data);
  559. size = n;
  560. }
  561. ~llama_buffer() {
  562. if (data) {
  563. if (fallback) { // NOLINT
  564. free(data);
  565. } else {
  566. llama_host_free(data);
  567. }
  568. }
  569. data = NULL;
  570. }
  571. };
  572. struct llama_file {
  573. // use FILE * so we don't have to re-open the file to mmap
  574. FILE * fp;
  575. size_t size;
  576. llama_file(const char * fname, const char * mode) {
  577. fp = std::fopen(fname, mode);
  578. if (fp == NULL) {
  579. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  580. }
  581. seek(0, SEEK_END);
  582. size = tell();
  583. seek(0, SEEK_SET);
  584. }
  585. size_t tell() const {
  586. #ifdef _WIN32
  587. __int64 ret = _ftelli64(fp);
  588. #else
  589. long ret = std::ftell(fp);
  590. #endif
  591. GGML_ASSERT(ret != -1); // this really shouldn't fail
  592. return (size_t) ret;
  593. }
  594. void seek(size_t offset, int whence) const {
  595. #ifdef _WIN32
  596. int ret = _fseeki64(fp, (__int64) offset, whence);
  597. #else
  598. int ret = std::fseek(fp, (long) offset, whence);
  599. #endif
  600. GGML_ASSERT(ret == 0); // same
  601. }
  602. void read_raw(void * ptr, size_t len) const {
  603. if (len == 0) {
  604. return;
  605. }
  606. errno = 0;
  607. std::size_t ret = std::fread(ptr, len, 1, fp);
  608. if (ferror(fp)) {
  609. throw std::runtime_error(format("read error: %s", strerror(errno)));
  610. }
  611. if (ret != 1) {
  612. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  613. }
  614. }
  615. uint32_t read_u32() const {
  616. uint32_t ret;
  617. read_raw(&ret, sizeof(ret));
  618. return ret;
  619. }
  620. void write_raw(const void * ptr, size_t len) const {
  621. if (len == 0) {
  622. return;
  623. }
  624. errno = 0;
  625. size_t ret = std::fwrite(ptr, len, 1, fp);
  626. if (ret != 1) {
  627. throw std::runtime_error(format("write error: %s", strerror(errno)));
  628. }
  629. }
  630. void write_u32(std::uint32_t val) const {
  631. write_raw(&val, sizeof(val));
  632. }
  633. ~llama_file() {
  634. if (fp) {
  635. std::fclose(fp);
  636. }
  637. }
  638. };
  639. struct llama_mmap {
  640. void * addr;
  641. size_t size;
  642. llama_mmap(const llama_mmap &) = delete;
  643. #ifdef _POSIX_MAPPED_FILES
  644. static constexpr bool SUPPORTED = true;
  645. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  646. size = file->size;
  647. int fd = fileno(file->fp);
  648. int flags = MAP_SHARED;
  649. // prefetch/readahead impairs performance on NUMA systems
  650. if (numa) { prefetch = 0; }
  651. #ifdef __linux__
  652. if (prefetch) { flags |= MAP_POPULATE; }
  653. #endif
  654. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  655. if (addr == MAP_FAILED) {
  656. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  657. }
  658. if (prefetch > 0) {
  659. // Advise the kernel to preload the mapped memory
  660. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  661. fprintf(stderr, "warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  662. strerror(errno));
  663. }
  664. }
  665. if (numa) {
  666. // advise the kernel not to use readahead
  667. // (because the next page might not belong on the same node)
  668. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  669. fprintf(stderr, "warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  670. strerror(errno));
  671. }
  672. }
  673. }
  674. ~llama_mmap() {
  675. munmap(addr, size);
  676. }
  677. #elif defined(_WIN32)
  678. static constexpr bool SUPPORTED = true;
  679. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  680. (void) numa;
  681. size = file->size;
  682. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  683. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  684. DWORD error = GetLastError();
  685. if (hMapping == NULL) {
  686. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  687. }
  688. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  689. error = GetLastError();
  690. CloseHandle(hMapping);
  691. if (addr == NULL) {
  692. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  693. }
  694. if (prefetch) {
  695. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  696. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  697. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  698. // may fail on pre-Windows 8 systems
  699. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  700. if (pPrefetchVirtualMemory) {
  701. // advise the kernel to preload the mapped memory
  702. WIN32_MEMORY_RANGE_ENTRY range;
  703. range.VirtualAddress = addr;
  704. range.NumberOfBytes = (SIZE_T)size;
  705. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  706. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  707. llama_format_win_err(GetLastError()).c_str());
  708. }
  709. }
  710. }
  711. }
  712. ~llama_mmap() {
  713. if (!UnmapViewOfFile(addr)) {
  714. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  715. llama_format_win_err(GetLastError()).c_str());
  716. }
  717. }
  718. #else
  719. static constexpr bool SUPPORTED = false;
  720. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  721. (void) file;
  722. (void) prefetch;
  723. (void) numa;
  724. throw std::runtime_error(std::string("mmap not supported"));
  725. }
  726. #endif
  727. };
  728. // Represents some region of memory being locked using mlock or VirtualLock;
  729. // will automatically unlock on destruction.
  730. struct llama_mlock {
  731. void * addr = NULL;
  732. size_t size = 0;
  733. bool failed_already = false;
  734. llama_mlock() {}
  735. llama_mlock(const llama_mlock &) = delete;
  736. ~llama_mlock() {
  737. if (size) {
  738. raw_unlock(addr, size);
  739. }
  740. }
  741. void init(void * ptr) {
  742. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  743. addr = ptr;
  744. }
  745. void grow_to(size_t target_size) {
  746. GGML_ASSERT(addr);
  747. if (failed_already) {
  748. return;
  749. }
  750. size_t granularity = lock_granularity();
  751. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  752. if (target_size > size) {
  753. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  754. size = target_size;
  755. } else {
  756. failed_already = true;
  757. }
  758. }
  759. }
  760. #ifdef _POSIX_MEMLOCK_RANGE
  761. static constexpr bool SUPPORTED = true;
  762. static size_t lock_granularity() {
  763. return (size_t) sysconf(_SC_PAGESIZE);
  764. }
  765. #ifdef __APPLE__
  766. #define MLOCK_SUGGESTION \
  767. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  768. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  769. #else
  770. #define MLOCK_SUGGESTION \
  771. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  772. #endif
  773. bool raw_lock(const void * addr, size_t size) const {
  774. if (!mlock(addr, size)) {
  775. return true;
  776. }
  777. char* errmsg = std::strerror(errno);
  778. bool suggest = (errno == ENOMEM);
  779. // Check if the resource limit is fine after all
  780. struct rlimit lock_limit;
  781. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  782. suggest = false;
  783. }
  784. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  785. suggest = false;
  786. }
  787. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  788. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  789. return false;
  790. }
  791. #undef MLOCK_SUGGESTION
  792. static void raw_unlock(void * addr, size_t size) {
  793. if (munlock(addr, size)) {
  794. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  795. }
  796. }
  797. #elif defined(_WIN32)
  798. static constexpr bool SUPPORTED = true;
  799. static size_t lock_granularity() {
  800. SYSTEM_INFO si;
  801. GetSystemInfo(&si);
  802. return (size_t) si.dwPageSize;
  803. }
  804. bool raw_lock(void * ptr, size_t len) const {
  805. for (int tries = 1; ; tries++) {
  806. if (VirtualLock(ptr, len)) {
  807. return true;
  808. }
  809. if (tries == 2) {
  810. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  811. len, size, llama_format_win_err(GetLastError()).c_str());
  812. return false;
  813. }
  814. // It failed but this was only the first try; increase the working
  815. // set size and try again.
  816. SIZE_T min_ws_size, max_ws_size;
  817. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  818. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  819. llama_format_win_err(GetLastError()).c_str());
  820. return false;
  821. }
  822. // Per MSDN: "The maximum number of pages that a process can lock
  823. // is equal to the number of pages in its minimum working set minus
  824. // a small overhead."
  825. // Hopefully a megabyte is enough overhead:
  826. size_t increment = len + 1048576;
  827. // The minimum must be <= the maximum, so we need to increase both:
  828. min_ws_size += increment;
  829. max_ws_size += increment;
  830. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  831. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  832. llama_format_win_err(GetLastError()).c_str());
  833. return false;
  834. }
  835. }
  836. }
  837. static void raw_unlock(void * ptr, size_t len) {
  838. if (!VirtualUnlock(ptr, len)) {
  839. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  840. llama_format_win_err(GetLastError()).c_str());
  841. }
  842. }
  843. #else
  844. static constexpr bool SUPPORTED = false;
  845. static size_t lock_granularity() {
  846. return (size_t) 65536;
  847. }
  848. bool raw_lock(const void * addr, size_t len) const {
  849. fprintf(stderr, "warning: mlock not supported on this system\n");
  850. return false;
  851. }
  852. static void raw_unlock(const void * addr, size_t len) {}
  853. #endif
  854. };
  855. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  856. static void ggml_offload_nop(struct ggml_tensor * tensor) {
  857. (void) tensor;
  858. }
  859. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  860. std::vector<char> result(8, 0);
  861. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  862. if (n_tokens < 0) {
  863. result.resize(-n_tokens);
  864. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  865. GGML_ASSERT(check == -n_tokens);
  866. }
  867. else {
  868. result.resize(n_tokens);
  869. }
  870. return std::string(result.data(), result.size());
  871. }
  872. //
  873. // globals
  874. //
  875. struct llama_state {
  876. // We save the log callback globally
  877. ggml_log_callback log_callback = llama_log_callback_default;
  878. void * log_callback_user_data = nullptr;
  879. };
  880. static llama_state g_state;
  881. // available llama models
  882. enum e_model {
  883. MODEL_UNKNOWN,
  884. MODEL_1B,
  885. MODEL_3B,
  886. MODEL_7B,
  887. MODEL_8B,
  888. MODEL_13B,
  889. MODEL_15B,
  890. MODEL_30B,
  891. MODEL_34B,
  892. MODEL_40B,
  893. MODEL_65B,
  894. MODEL_70B,
  895. };
  896. static const size_t kB = 1024;
  897. static const size_t MB = 1024*kB;
  898. static const size_t GB = 1024*MB;
  899. struct llama_hparams {
  900. bool vocab_only;
  901. uint32_t n_vocab;
  902. uint32_t n_ctx_train; // context size the model was trained on
  903. uint32_t n_embd;
  904. uint32_t n_head;
  905. uint32_t n_head_kv;
  906. uint32_t n_layer;
  907. uint32_t n_rot;
  908. uint32_t n_ff;
  909. float f_norm_eps;
  910. float f_norm_rms_eps;
  911. float rope_freq_base_train;
  912. float rope_freq_scale_train;
  913. float f_clamp_kqv;
  914. float f_max_alibi_bias;
  915. bool operator!=(const llama_hparams & other) const {
  916. if (this->vocab_only != other.vocab_only) return true;
  917. if (this->n_vocab != other.n_vocab) return true;
  918. if (this->n_ctx_train != other.n_ctx_train) return true;
  919. if (this->n_embd != other.n_embd) return true;
  920. if (this->n_head != other.n_head) return true;
  921. if (this->n_head_kv != other.n_head_kv) return true;
  922. if (this->n_layer != other.n_layer) return true;
  923. if (this->n_rot != other.n_rot) return true;
  924. if (this->n_ff != other.n_ff) return true;
  925. const float EPSILON = 1e-9;
  926. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  927. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  928. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  929. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  930. return false;
  931. }
  932. uint32_t n_gqa() const {
  933. return n_head/n_head_kv;
  934. }
  935. uint32_t n_embd_head() const {
  936. return n_embd/n_head;
  937. }
  938. uint32_t n_embd_gqa() const {
  939. return n_embd/n_gqa();
  940. }
  941. };
  942. struct llama_cparams {
  943. uint32_t n_ctx; // context size used during inference
  944. uint32_t n_batch;
  945. uint32_t n_threads; // number of threads to use for generation
  946. uint32_t n_threads_batch; // number of threads to use for batch processing
  947. float rope_freq_base;
  948. float rope_freq_scale;
  949. bool mul_mat_q;
  950. };
  951. struct llama_layer {
  952. // normalization
  953. struct ggml_tensor * attn_norm;
  954. struct ggml_tensor * attn_norm_b;
  955. struct ggml_tensor * attn_norm_2;
  956. struct ggml_tensor * attn_norm_2_b;
  957. struct ggml_tensor * attn_q_norm;
  958. struct ggml_tensor * attn_q_norm_b;
  959. struct ggml_tensor * attn_k_norm;
  960. struct ggml_tensor * attn_k_norm_b;
  961. // attention
  962. struct ggml_tensor * wq;
  963. struct ggml_tensor * wk;
  964. struct ggml_tensor * wv;
  965. struct ggml_tensor * wo;
  966. struct ggml_tensor * wqkv;
  967. // attention bias
  968. struct ggml_tensor * bo;
  969. struct ggml_tensor * bqkv;
  970. // normalization
  971. struct ggml_tensor * ffn_norm;
  972. struct ggml_tensor * ffn_norm_b;
  973. // ff
  974. struct ggml_tensor * ffn_gate; // w1
  975. struct ggml_tensor * ffn_down; // w2
  976. struct ggml_tensor * ffn_up; // w3
  977. // ff bias
  978. struct ggml_tensor * ffn_down_b; // b2
  979. struct ggml_tensor * ffn_up_b; // b3
  980. };
  981. struct llama_kv_cell {
  982. llama_pos pos = -1;
  983. llama_pos delta = 0;
  984. std::set<llama_seq_id> seq_id;
  985. bool has_seq_id(const llama_seq_id & id) const {
  986. return seq_id.find(id) != seq_id.end();
  987. }
  988. };
  989. // ring-buffer of cached KV data
  990. struct llama_kv_cache {
  991. bool has_shift = false;
  992. // Note: The value of head isn't only used to optimize searching
  993. // for a free KV slot. llama_decode_internal also uses it, so it
  994. // cannot be freely changed after a slot has been allocated.
  995. uint32_t head = 0;
  996. uint32_t size = 0;
  997. // computed before each graph build
  998. uint32_t n = 0;
  999. std::vector<llama_kv_cell> cells;
  1000. struct ggml_tensor * k = NULL;
  1001. struct ggml_tensor * v = NULL;
  1002. struct ggml_context * ctx = NULL;
  1003. llama_buffer buf;
  1004. ~llama_kv_cache() {
  1005. if (ctx) {
  1006. ggml_free(ctx);
  1007. }
  1008. #ifdef GGML_USE_CUBLAS
  1009. ggml_cuda_free_data(k);
  1010. ggml_cuda_free_data(v);
  1011. #endif // GGML_USE_CUBLAS
  1012. }
  1013. };
  1014. struct llama_vocab {
  1015. using id = int32_t;
  1016. using token = std::string;
  1017. using ttype = llama_token_type;
  1018. struct token_data {
  1019. token text;
  1020. float score;
  1021. ttype type;
  1022. };
  1023. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1024. std::unordered_map<token, id> token_to_id;
  1025. std::vector<token_data> id_to_token;
  1026. std::unordered_map<token, id> special_tokens_cache;
  1027. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1028. // default LLaMA special tokens
  1029. id special_bos_id = 1;
  1030. id special_eos_id = 2;
  1031. id special_unk_id = 0;
  1032. id special_sep_id = -1;
  1033. id special_pad_id = -1;
  1034. id linefeed_id = 13;
  1035. id special_prefix_id = 32007;
  1036. id special_middle_id = 32009;
  1037. id special_suffix_id = 32008;
  1038. id special_eot_id = 32010;
  1039. int find_bpe_rank(std::string token_left, std::string token_right) const {
  1040. GGML_ASSERT(token_left.find(" ") == std::string::npos);
  1041. GGML_ASSERT(token_left.find("\n") == std::string::npos);
  1042. GGML_ASSERT(token_right.find(" ") == std::string::npos);
  1043. GGML_ASSERT(token_right.find("\n") == std::string::npos);
  1044. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1045. if (it == bpe_ranks.end()) {
  1046. return -1;
  1047. }
  1048. return it->second;
  1049. }
  1050. };
  1051. struct llama_model {
  1052. e_model type = MODEL_UNKNOWN;
  1053. llm_arch arch = LLM_ARCH_UNKNOWN;
  1054. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1055. std::string name = "n/a";
  1056. llama_hparams hparams = {};
  1057. llama_vocab vocab;
  1058. struct ggml_tensor * tok_embd;
  1059. struct ggml_tensor * pos_embd;
  1060. struct ggml_tensor * tok_norm;
  1061. struct ggml_tensor * tok_norm_b;
  1062. struct ggml_tensor * output_norm;
  1063. struct ggml_tensor * output_norm_b;
  1064. struct ggml_tensor * output;
  1065. std::vector<llama_layer> layers;
  1066. int n_gpu_layers;
  1067. // context
  1068. struct ggml_context * ctx = NULL;
  1069. // the model memory buffer
  1070. llama_buffer buf;
  1071. // model memory mapped file
  1072. std::unique_ptr<llama_mmap> mapping;
  1073. // objects representing data potentially being locked in memory
  1074. llama_mlock mlock_buf;
  1075. llama_mlock mlock_mmap;
  1076. // for quantize-stats only
  1077. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1078. int64_t t_load_us = 0;
  1079. int64_t t_start_us = 0;
  1080. ~llama_model() {
  1081. if (ctx) {
  1082. ggml_free(ctx);
  1083. }
  1084. #ifdef GGML_USE_CUBLAS
  1085. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  1086. ggml_cuda_free_data(tensors_by_name[i].second);
  1087. }
  1088. ggml_cuda_free_scratch();
  1089. #elif defined(GGML_USE_CLBLAST)
  1090. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  1091. ggml_cl_free_data(tensors_by_name[i].second);
  1092. }
  1093. #endif
  1094. }
  1095. };
  1096. struct llama_context {
  1097. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1098. ~llama_context() {
  1099. #ifdef GGML_USE_METAL
  1100. if (ctx_metal) {
  1101. ggml_metal_free(ctx_metal);
  1102. }
  1103. #endif
  1104. if (alloc) {
  1105. ggml_allocr_free(alloc);
  1106. }
  1107. }
  1108. llama_cparams cparams;
  1109. const llama_model & model;
  1110. // key + value cache for the self attention
  1111. struct llama_kv_cache kv_self;
  1112. std::mt19937 rng;
  1113. bool has_evaluated_once = false;
  1114. int64_t t_start_us;
  1115. int64_t t_load_us;
  1116. int64_t t_sample_us = 0;
  1117. int64_t t_p_eval_us = 0;
  1118. int64_t t_eval_us = 0;
  1119. int32_t n_sample = 0; // number of tokens sampled
  1120. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1121. int32_t n_eval = 0; // number of eval calls
  1122. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1123. std::vector<float> logits;
  1124. bool logits_all = false;
  1125. // input embedding (1-dimensional array: [n_embd])
  1126. std::vector<float> embedding;
  1127. // reusable buffer for `struct ggml_graph_plan.work_data`
  1128. std::vector<uint8_t> work_buffer;
  1129. // memory buffers used to evaluate the model
  1130. llama_buffer buf_compute;
  1131. llama_buffer buf_alloc;
  1132. ggml_allocr * alloc = NULL;
  1133. #ifdef GGML_USE_METAL
  1134. ggml_metal_context * ctx_metal = NULL;
  1135. #endif
  1136. #ifdef GGML_USE_MPI
  1137. ggml_mpi_context * ctx_mpi = NULL;
  1138. #endif
  1139. };
  1140. //
  1141. // kv cache helpers
  1142. //
  1143. static bool llama_kv_cache_init(
  1144. const struct llama_hparams & hparams,
  1145. struct llama_kv_cache & cache,
  1146. ggml_type wtype,
  1147. uint32_t n_ctx,
  1148. int n_gpu_layers) {
  1149. const uint32_t n_embd = hparams.n_embd_gqa();
  1150. const uint32_t n_layer = hparams.n_layer;
  1151. const int64_t n_mem = n_layer*n_ctx;
  1152. const int64_t n_elements = n_embd*n_mem;
  1153. cache.has_shift = false;
  1154. cache.head = 0;
  1155. cache.size = n_ctx;
  1156. cache.cells.clear();
  1157. cache.cells.resize(n_ctx);
  1158. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*ggml_tensor_overhead());
  1159. memset(cache.buf.data, 0, cache.buf.size);
  1160. struct ggml_init_params params;
  1161. params.mem_size = cache.buf.size;
  1162. params.mem_buffer = cache.buf.data;
  1163. params.no_alloc = false;
  1164. cache.ctx = ggml_init(params);
  1165. if (!cache.ctx) {
  1166. LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
  1167. return false;
  1168. }
  1169. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  1170. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  1171. ggml_set_name(cache.k, "cache_k");
  1172. ggml_set_name(cache.v, "cache_v");
  1173. (void) n_gpu_layers;
  1174. #ifdef GGML_USE_CUBLAS
  1175. size_t vram_kv_cache = 0;
  1176. if (n_gpu_layers > (int)n_layer + 1) {
  1177. ggml_cuda_assign_buffers_no_scratch(cache.v);
  1178. LLAMA_LOG_INFO("%s: offloading v cache to GPU\n", __func__);
  1179. vram_kv_cache += ggml_nbytes(cache.v);
  1180. }
  1181. if (n_gpu_layers > (int)n_layer + 2) {
  1182. ggml_cuda_assign_buffers_no_scratch(cache.k);
  1183. LLAMA_LOG_INFO("%s: offloading k cache to GPU\n", __func__);
  1184. vram_kv_cache += ggml_nbytes(cache.k);
  1185. }
  1186. if (vram_kv_cache > 0) {
  1187. LLAMA_LOG_INFO("%s: VRAM kv self = %.2f MB\n", __func__, vram_kv_cache / 1024.0 / 1024.0);
  1188. }
  1189. #endif // GGML_USE_CUBLAS
  1190. return true;
  1191. }
  1192. // find an empty slot of size "n_tokens" in the cache
  1193. // updates the cache head
  1194. // Note: On success, it's important that cache.head points
  1195. // to the first cell of the slot.
  1196. static bool llama_kv_cache_find_slot(
  1197. struct llama_kv_cache & cache,
  1198. const struct llama_batch & batch) {
  1199. const uint32_t n_ctx = cache.size;
  1200. const uint32_t n_tokens = batch.n_tokens;
  1201. if (n_tokens > n_ctx) {
  1202. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1203. return false;
  1204. }
  1205. uint32_t n_tested = 0;
  1206. while (true) {
  1207. if (cache.head + n_tokens > n_ctx) {
  1208. n_tested += n_ctx - cache.head;
  1209. cache.head = 0;
  1210. continue;
  1211. }
  1212. bool found = true;
  1213. for (uint32_t i = 0; i < n_tokens; i++) {
  1214. if (cache.cells[cache.head + i].pos >= 0) {
  1215. found = false;
  1216. cache.head += i + 1;
  1217. n_tested += i + 1;
  1218. break;
  1219. }
  1220. }
  1221. if (found) {
  1222. break;
  1223. }
  1224. if (n_tested >= n_ctx) {
  1225. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1226. return false;
  1227. }
  1228. }
  1229. for (uint32_t i = 0; i < n_tokens; i++) {
  1230. cache.cells[cache.head + i].pos = batch.pos[i];
  1231. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1232. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1233. }
  1234. }
  1235. return true;
  1236. }
  1237. // find how many cells are currently in use
  1238. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1239. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1240. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1241. return i + 1;
  1242. }
  1243. }
  1244. return 0;
  1245. }
  1246. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1247. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1248. cache.cells[i].pos = -1;
  1249. cache.cells[i].seq_id.clear();
  1250. }
  1251. cache.head = 0;
  1252. }
  1253. static void llama_kv_cache_seq_rm(
  1254. struct llama_kv_cache & cache,
  1255. llama_seq_id seq_id,
  1256. llama_pos p0,
  1257. llama_pos p1) {
  1258. uint32_t new_head = cache.size;
  1259. if (p0 < 0) p0 = 0;
  1260. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1261. for (uint32_t i = 0; i < cache.size; ++i) {
  1262. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1263. if (seq_id < 0) {
  1264. cache.cells[i].seq_id.clear();
  1265. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1266. cache.cells[i].seq_id.erase(seq_id);
  1267. } else {
  1268. continue;
  1269. }
  1270. if (cache.cells[i].seq_id.empty()) {
  1271. cache.cells[i].pos = -1;
  1272. if (new_head == cache.size) new_head = i;
  1273. }
  1274. }
  1275. }
  1276. // If we freed up a slot, set head to it so searching can start there.
  1277. if (new_head != cache.size) cache.head = new_head;
  1278. }
  1279. static void llama_kv_cache_seq_cp(
  1280. struct llama_kv_cache & cache,
  1281. llama_seq_id seq_id_src,
  1282. llama_seq_id seq_id_dst,
  1283. llama_pos p0,
  1284. llama_pos p1) {
  1285. if (p0 < 0) p0 = 0;
  1286. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1287. cache.head = 0;
  1288. for (uint32_t i = 0; i < cache.size; ++i) {
  1289. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1290. cache.cells[i].seq_id.insert(seq_id_dst);
  1291. }
  1292. }
  1293. }
  1294. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1295. uint32_t new_head = cache.size;
  1296. for (uint32_t i = 0; i < cache.size; ++i) {
  1297. if (!cache.cells[i].has_seq_id(seq_id)) {
  1298. cache.cells[i].pos = -1;
  1299. cache.cells[i].seq_id.clear();
  1300. if (new_head == cache.size) new_head = i;
  1301. } else {
  1302. cache.cells[i].seq_id.clear();
  1303. cache.cells[i].seq_id.insert(seq_id);
  1304. }
  1305. }
  1306. // If we freed up a slot, set head to it so searching can start there.
  1307. if (new_head != cache.size) cache.head = new_head;
  1308. }
  1309. static void llama_kv_cache_seq_shift(
  1310. struct llama_kv_cache & cache,
  1311. llama_seq_id seq_id,
  1312. llama_pos p0,
  1313. llama_pos p1,
  1314. llama_pos delta) {
  1315. uint32_t new_head = cache.size;
  1316. if (p0 < 0) p0 = 0;
  1317. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1318. for (uint32_t i = 0; i < cache.size; ++i) {
  1319. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1320. cache.has_shift = true;
  1321. cache.cells[i].pos += delta;
  1322. cache.cells[i].delta += delta;
  1323. if (cache.cells[i].pos < 0) {
  1324. cache.cells[i].pos = -1;
  1325. cache.cells[i].seq_id.clear();
  1326. if (new_head == cache.size) new_head = i;
  1327. }
  1328. }
  1329. }
  1330. // If we freed up a slot, set head to it so searching can start there.
  1331. // Otherwise we just start the next search from the beginning.
  1332. cache.head = new_head != cache.size ? new_head : 0;
  1333. }
  1334. //
  1335. // model loading and saving
  1336. //
  1337. enum llama_fver {
  1338. GGUF_FILE_VERSION_V1 = 1,
  1339. GGUF_FILE_VERSION_V2 = 2,
  1340. GGUF_FILE_VERSION_V3 = 3,
  1341. };
  1342. static const char * llama_file_version_name(llama_fver version) {
  1343. switch (version) {
  1344. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1345. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1346. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1347. }
  1348. return "unknown";
  1349. }
  1350. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1351. char buf[256];
  1352. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1353. for (size_t i = 1; i < ne.size(); i++) {
  1354. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1355. }
  1356. return buf;
  1357. }
  1358. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1359. char buf[256];
  1360. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1361. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1362. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1363. }
  1364. return buf;
  1365. }
  1366. struct llama_model_loader {
  1367. int n_kv = 0;
  1368. int n_tensors = 0;
  1369. int n_created = 0;
  1370. int64_t n_elements = 0;
  1371. size_t n_bytes = 0;
  1372. bool use_mmap = false;
  1373. llama_file file;
  1374. llama_ftype ftype;
  1375. llama_fver fver;
  1376. std::unique_ptr<llama_mmap> mapping;
  1377. struct gguf_context * ctx_gguf = NULL;
  1378. struct ggml_context * ctx_meta = NULL;
  1379. llama_model_loader(const std::string & fname, bool use_mmap) : file(fname.c_str(), "rb") {
  1380. struct gguf_init_params params = {
  1381. /*.no_alloc = */ true,
  1382. /*.ctx = */ &ctx_meta,
  1383. };
  1384. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1385. if (!ctx_gguf) {
  1386. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1387. }
  1388. n_kv = gguf_get_n_kv(ctx_gguf);
  1389. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1390. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1391. for (int i = 0; i < n_tensors; i++) {
  1392. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1393. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1394. n_elements += ggml_nelements(t);
  1395. n_bytes += ggml_nbytes(t);
  1396. }
  1397. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1398. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1399. // determine file type based on the number of tensors for each quantization and print meta data
  1400. // TODO: make optional
  1401. {
  1402. std::map<enum ggml_type, uint32_t> n_type;
  1403. uint32_t n_type_max = 0;
  1404. enum ggml_type type_max = GGML_TYPE_F32;
  1405. for (int i = 0; i < n_tensors; i++) {
  1406. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1407. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, name);
  1408. n_type[meta->type]++;
  1409. if (n_type_max < n_type[meta->type]) {
  1410. n_type_max = n_type[meta->type];
  1411. type_max = meta->type;
  1412. }
  1413. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, name, ggml_type_name(meta->type), llama_format_tensor_shape(meta).c_str());
  1414. }
  1415. switch (type_max) {
  1416. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1417. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1418. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1419. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1420. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1421. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1422. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1423. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1424. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1425. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1426. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1427. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1428. default:
  1429. {
  1430. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1431. ftype = LLAMA_FTYPE_ALL_F32;
  1432. } break;
  1433. }
  1434. // this is a way to mark that we have "guessed" the file type
  1435. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1436. {
  1437. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  1438. if (kid >= 0) {
  1439. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  1440. }
  1441. }
  1442. for (int i = 0; i < n_kv; i++) {
  1443. const char * name = gguf_get_key(ctx_gguf, i);
  1444. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1445. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-8s\n", __func__, i, name, gguf_type_name(type));
  1446. }
  1447. // print type counts
  1448. for (auto & kv : n_type) {
  1449. if (kv.second == 0) {
  1450. continue;
  1451. }
  1452. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  1453. }
  1454. }
  1455. if (!llama_mmap::SUPPORTED) {
  1456. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  1457. use_mmap = false;
  1458. }
  1459. this->use_mmap = use_mmap;
  1460. }
  1461. ~llama_model_loader() {
  1462. if (ctx_gguf) {
  1463. gguf_free(ctx_gguf);
  1464. }
  1465. if (ctx_meta) {
  1466. ggml_free(ctx_meta);
  1467. }
  1468. }
  1469. std::string get_arch_name() const {
  1470. const auto kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1471. std::string arch_name;
  1472. GGUF_GET_KEY(ctx_gguf, arch_name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_ARCHITECTURE));
  1473. return arch_name;
  1474. }
  1475. enum llm_arch get_arch() const {
  1476. const std::string arch_name = get_arch_name();
  1477. return llm_arch_from_string(arch_name);
  1478. }
  1479. const char * get_tensor_name(int i) const {
  1480. return gguf_get_tensor_name(ctx_gguf, i);
  1481. }
  1482. struct ggml_tensor * get_tensor_meta(int i) const {
  1483. return ggml_get_tensor(ctx_meta, get_tensor_name(i));
  1484. }
  1485. void calc_sizes(size_t & ctx_size_p, size_t & mmapped_size_p) const {
  1486. ctx_size_p = 0;
  1487. mmapped_size_p = 0;
  1488. for (int i = 0; i < n_tensors; i++) {
  1489. struct ggml_tensor * meta = get_tensor_meta(i);
  1490. ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  1491. (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
  1492. }
  1493. }
  1494. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta, ggml_backend_type backend) {
  1495. if (backend != GGML_BACKEND_CPU) {
  1496. ggml_set_no_alloc(ctx, true);
  1497. }
  1498. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  1499. tensor->backend = backend; // TODO: ggml_set_backend
  1500. ggml_set_name(tensor, ggml_get_name(meta));
  1501. if (backend != GGML_BACKEND_CPU) {
  1502. ggml_set_no_alloc(ctx, use_mmap);
  1503. }
  1504. n_created++;
  1505. return tensor;
  1506. }
  1507. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, ggml_backend_type backend) {
  1508. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  1509. if (cur == NULL) {
  1510. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  1511. }
  1512. {
  1513. bool is_ok = true;
  1514. for (size_t i = 0; i < ne.size(); ++i) {
  1515. if (ne[i] != cur->ne[i]) {
  1516. is_ok = false;
  1517. break;
  1518. }
  1519. }
  1520. if (!is_ok) {
  1521. throw std::runtime_error(
  1522. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  1523. __func__, name.c_str(),
  1524. llama_format_tensor_shape(ne).c_str(),
  1525. llama_format_tensor_shape(cur).c_str()));
  1526. }
  1527. }
  1528. return create_tensor_for(ctx, cur, backend);
  1529. }
  1530. void done_getting_tensors() const {
  1531. if (n_created != n_tensors) {
  1532. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  1533. }
  1534. }
  1535. size_t file_offset(const char * name) const {
  1536. const int idx = gguf_find_tensor(ctx_gguf, name);
  1537. if (idx < 0) {
  1538. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  1539. }
  1540. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  1541. }
  1542. void load_data_for(struct ggml_tensor * cur) const {
  1543. const size_t offs = file_offset(ggml_get_name(cur));
  1544. if (use_mmap) {
  1545. cur->data = (uint8_t *) mapping->addr + offs;
  1546. } else {
  1547. file.seek(offs, SEEK_SET);
  1548. file.read_raw(cur->data, ggml_nbytes(cur));
  1549. }
  1550. }
  1551. void load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  1552. size_t size_data = 0;
  1553. size_t size_lock = 0;
  1554. size_t size_pref = 0; // prefetch
  1555. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1556. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1557. size_data += ggml_nbytes(cur);
  1558. if (cur->backend == GGML_BACKEND_CPU) {
  1559. size_pref += ggml_nbytes(cur);
  1560. }
  1561. }
  1562. if (use_mmap) {
  1563. mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
  1564. if (lmlock) {
  1565. lmlock->init(mapping->addr);
  1566. }
  1567. }
  1568. size_t done_size = 0;
  1569. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1570. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1571. GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
  1572. if (progress_callback) {
  1573. progress_callback((float) done_size / size_data, progress_callback_user_data);
  1574. }
  1575. // allocate temp buffer if not using mmap
  1576. if (!use_mmap && cur->data == NULL) {
  1577. GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
  1578. #ifdef GGML_USE_CPU_HBM
  1579. cur->data = (uint8_t*)hbw_malloc(ggml_nbytes(cur));
  1580. #else
  1581. cur->data = (uint8_t*)malloc(ggml_nbytes(cur));
  1582. #endif
  1583. }
  1584. load_data_for(cur);
  1585. switch (cur->backend) {
  1586. case GGML_BACKEND_CPU:
  1587. if (use_mmap && lmlock) {
  1588. size_lock += ggml_nbytes(cur);
  1589. lmlock->grow_to(size_lock);
  1590. }
  1591. break;
  1592. #ifdef GGML_USE_CUBLAS
  1593. case GGML_BACKEND_GPU:
  1594. case GGML_BACKEND_GPU_SPLIT:
  1595. // old code:
  1596. //ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  1597. // TODO: test if this works !!
  1598. ggml_cuda_transform_tensor(cur->data, cur);
  1599. if (!use_mmap) {
  1600. free(cur->data);
  1601. }
  1602. break;
  1603. #elif defined(GGML_USE_CLBLAST)
  1604. case GGML_BACKEND_GPU:
  1605. ggml_cl_transform_tensor(cur->data, cur);
  1606. if (!use_mmap) {
  1607. free(cur->data);
  1608. }
  1609. break;
  1610. #endif
  1611. default:
  1612. continue;
  1613. }
  1614. done_size += ggml_nbytes(cur);
  1615. }
  1616. }
  1617. };
  1618. //
  1619. // load LLaMA models
  1620. //
  1621. static std::string llama_model_arch_name(llm_arch arch) {
  1622. auto it = LLM_ARCH_NAMES.find(arch);
  1623. if (it == LLM_ARCH_NAMES.end()) {
  1624. return "unknown";
  1625. }
  1626. return it->second;
  1627. }
  1628. static std::string llama_model_ftype_name(llama_ftype ftype) {
  1629. if (ftype & LLAMA_FTYPE_GUESSED) {
  1630. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  1631. }
  1632. switch (ftype) {
  1633. case LLAMA_FTYPE_ALL_F32: return "all F32";
  1634. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  1635. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  1636. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  1637. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  1638. return "mostly Q4_1, some F16";
  1639. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  1640. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  1641. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  1642. // K-quants
  1643. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  1644. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  1645. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  1646. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  1647. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  1648. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  1649. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  1650. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  1651. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  1652. default: return "unknown, may not work";
  1653. }
  1654. }
  1655. static const char * llama_model_type_name(e_model type) {
  1656. switch (type) {
  1657. case MODEL_1B: return "1B";
  1658. case MODEL_3B: return "3B";
  1659. case MODEL_7B: return "7B";
  1660. case MODEL_8B: return "8B";
  1661. case MODEL_13B: return "13B";
  1662. case MODEL_15B: return "15B";
  1663. case MODEL_30B: return "30B";
  1664. case MODEL_34B: return "34B";
  1665. case MODEL_40B: return "40B";
  1666. case MODEL_65B: return "65B";
  1667. case MODEL_70B: return "70B";
  1668. default: return "?B";
  1669. }
  1670. }
  1671. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  1672. model.arch = ml.get_arch();
  1673. if (model.arch == LLM_ARCH_UNKNOWN) {
  1674. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  1675. }
  1676. }
  1677. static void llm_load_hparams(
  1678. llama_model_loader & ml,
  1679. llama_model & model) {
  1680. struct gguf_context * ctx = ml.ctx_gguf;
  1681. const auto kv = LLM_KV(model.arch);
  1682. auto & hparams = model.hparams;
  1683. // get general kv
  1684. GGUF_GET_KEY(ctx, model.name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_NAME));
  1685. // get hparams kv
  1686. GGUF_GET_KEY(ctx, hparams.n_vocab, gguf_get_arr_n, GGUF_TYPE_ARRAY, true, kv(LLM_KV_TOKENIZER_LIST));
  1687. GGUF_GET_KEY(ctx, hparams.n_ctx_train, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_CONTEXT_LENGTH));
  1688. GGUF_GET_KEY(ctx, hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  1689. GGUF_GET_KEY(ctx, hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  1690. GGUF_GET_KEY(ctx, hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  1691. GGUF_GET_KEY(ctx, hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  1692. // n_head_kv is optional, default to n_head
  1693. hparams.n_head_kv = hparams.n_head;
  1694. GGUF_GET_KEY(ctx, hparams.n_head_kv, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ATTENTION_HEAD_COUNT_KV));
  1695. // rope_freq_base (optional)
  1696. hparams.rope_freq_base_train = 10000.0f;
  1697. GGUF_GET_KEY(ctx, hparams.rope_freq_base_train, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_FREQ_BASE));
  1698. // rope_freq_scale (inverse of the kv) is optional
  1699. float ropescale = 1.0f;
  1700. GGUF_GET_KEY(ctx, ropescale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  1701. hparams.rope_freq_scale_train = 1.0f/ropescale;
  1702. // sanity check for n_rot (optional)
  1703. {
  1704. hparams.n_rot = hparams.n_embd / hparams.n_head;
  1705. GGUF_GET_KEY(ctx, hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  1706. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  1707. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  1708. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  1709. }
  1710. }
  1711. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  1712. // gpt-j n_rot = rotary_dim
  1713. }
  1714. // arch-specific KVs
  1715. switch (model.arch) {
  1716. case LLM_ARCH_LLAMA:
  1717. {
  1718. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1719. switch (hparams.n_layer) {
  1720. case 26: model.type = e_model::MODEL_3B; break;
  1721. case 32: model.type = e_model::MODEL_7B; break;
  1722. case 40: model.type = e_model::MODEL_13B; break;
  1723. case 48: model.type = e_model::MODEL_34B; break;
  1724. case 60: model.type = e_model::MODEL_30B; break;
  1725. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  1726. default: model.type = e_model::MODEL_UNKNOWN;
  1727. }
  1728. } break;
  1729. case LLM_ARCH_FALCON:
  1730. {
  1731. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1732. switch (hparams.n_layer) {
  1733. case 32: model.type = e_model::MODEL_7B; break;
  1734. case 60: model.type = e_model::MODEL_40B; break;
  1735. default: model.type = e_model::MODEL_UNKNOWN;
  1736. }
  1737. } break;
  1738. case LLM_ARCH_BAICHUAN:
  1739. {
  1740. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1741. switch (hparams.n_layer) {
  1742. case 32: model.type = e_model::MODEL_7B; break;
  1743. case 40: model.type = e_model::MODEL_13B; break;
  1744. default: model.type = e_model::MODEL_UNKNOWN;
  1745. }
  1746. } break;
  1747. case LLM_ARCH_STARCODER:
  1748. {
  1749. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1750. switch (hparams.n_layer) {
  1751. case 24: model.type = e_model::MODEL_1B; break;
  1752. case 36: model.type = e_model::MODEL_3B; break;
  1753. case 42: model.type = e_model::MODEL_7B; break;
  1754. case 40: model.type = e_model::MODEL_15B; break;
  1755. default: model.type = e_model::MODEL_UNKNOWN;
  1756. }
  1757. } break;
  1758. case LLM_ARCH_PERSIMMON:
  1759. {
  1760. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1761. switch (hparams.n_layer) {
  1762. case 36: model.type = e_model::MODEL_8B; break;
  1763. default: model.type = e_model::MODEL_UNKNOWN;
  1764. }
  1765. } break;
  1766. case LLM_ARCH_REFACT:
  1767. {
  1768. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1769. switch (hparams.n_layer) {
  1770. case 32: model.type = e_model::MODEL_1B; break;
  1771. default: model.type = e_model::MODEL_UNKNOWN;
  1772. }
  1773. } break;
  1774. case LLM_ARCH_BLOOM:
  1775. {
  1776. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1777. switch (hparams.n_layer) {
  1778. case 24: model.type = e_model::MODEL_1B; break;
  1779. case 30:
  1780. switch (hparams.n_embd) {
  1781. case 2560: model.type = e_model::MODEL_3B; break;
  1782. case 4096: model.type = e_model::MODEL_7B; break;
  1783. } break;
  1784. }
  1785. } break;
  1786. case LLM_ARCH_MPT:
  1787. {
  1788. hparams.f_clamp_kqv = 0.0f;
  1789. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1790. GGUF_GET_KEY(ctx, hparams.f_clamp_kqv, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ATTENTION_CLAMP_KQV));
  1791. GGUF_GET_KEY(ctx, hparams.f_max_alibi_bias, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_MAX_ALIBI_BIAS));
  1792. switch (hparams.n_layer) {
  1793. case 32: model.type = e_model::MODEL_7B; break;
  1794. case 48: model.type = e_model::MODEL_30B; break;
  1795. default: model.type = e_model::MODEL_UNKNOWN;
  1796. }
  1797. } break;
  1798. default: (void)0;
  1799. }
  1800. model.ftype = ml.ftype;
  1801. }
  1802. // TODO: This should probably be in llama.h
  1803. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  1804. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  1805. static void llm_load_vocab(
  1806. llama_model_loader & ml,
  1807. llama_model & model) {
  1808. auto & vocab = model.vocab;
  1809. struct gguf_context * ctx = ml.ctx_gguf;
  1810. const auto kv = LLM_KV(model.arch);
  1811. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  1812. if (token_idx == -1) {
  1813. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1814. }
  1815. const float * scores = nullptr;
  1816. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  1817. if (score_idx != -1) {
  1818. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  1819. }
  1820. const int * toktypes = nullptr;
  1821. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  1822. if (toktype_idx != -1) {
  1823. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  1824. }
  1825. // determine vocab type
  1826. {
  1827. std::string tokenizer_name;
  1828. GGUF_GET_KEY(ctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  1829. if (tokenizer_name == "llama") {
  1830. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1831. // default special tokens
  1832. vocab.special_bos_id = 1;
  1833. vocab.special_eos_id = 2;
  1834. vocab.special_unk_id = 0;
  1835. vocab.special_sep_id = -1;
  1836. vocab.special_pad_id = -1;
  1837. } else if (tokenizer_name == "gpt2") {
  1838. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  1839. // read bpe merges and populate bpe ranks
  1840. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  1841. if (merges_keyidx == -1) {
  1842. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  1843. }
  1844. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  1845. for (int i = 0; i < n_merges; i++) {
  1846. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  1847. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  1848. std::string first;
  1849. std::string second;
  1850. const size_t pos = word.find(' ', 1);
  1851. if (pos != std::string::npos) {
  1852. first = word.substr(0, pos);
  1853. second = word.substr(pos + 1);
  1854. }
  1855. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  1856. }
  1857. // default special tokens
  1858. vocab.special_bos_id = 11;
  1859. vocab.special_eos_id = 11;
  1860. vocab.special_unk_id = -1;
  1861. vocab.special_sep_id = -1;
  1862. vocab.special_pad_id = -1;
  1863. } else {
  1864. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1865. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  1866. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1867. }
  1868. }
  1869. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  1870. vocab.id_to_token.resize(n_vocab);
  1871. for (uint32_t i = 0; i < n_vocab; i++) {
  1872. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  1873. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  1874. vocab.token_to_id[word] = i;
  1875. auto & token_data = vocab.id_to_token[i];
  1876. token_data.text = std::move(word);
  1877. token_data.score = scores ? scores[i] : 0.0f;
  1878. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  1879. }
  1880. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  1881. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  1882. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  1883. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  1884. } else {
  1885. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  1886. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  1887. vocab.linefeed_id = ids[0];
  1888. }
  1889. // special tokens
  1890. {
  1891. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  1892. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  1893. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  1894. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  1895. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  1896. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  1897. };
  1898. for (const auto & it : special_token_types) {
  1899. const std::string & key = kv(std::get<0>(it));
  1900. int32_t & id = std::get<1>(it), old_id = id;
  1901. GGUF_GET_KEY(ctx, id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, key);
  1902. // Must be >= -1 and < vocab size. Since the key is unsigned, -1
  1903. // can only come from the default value, so there's no point in
  1904. // validating that.
  1905. if (size_t(id + 1) > vocab.id_to_token.size()) {
  1906. LLAMA_LOG_WARN("%s: bad special token: '%s' = %d, using default id %d\n",
  1907. __func__, key.c_str(), id, old_id);
  1908. id = old_id;
  1909. }
  1910. }
  1911. }
  1912. // build special tokens cache
  1913. {
  1914. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  1915. // and will always be correctly labeled in 'added_tokens.json' etc.
  1916. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  1917. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  1918. // are special tokens.
  1919. // From testing, this appears to corelate 1:1 with special tokens.
  1920. //
  1921. // Counting special tokens and verifying in only one direction
  1922. // is sufficient to detect difference in those two sets.
  1923. //
  1924. uint32_t special_tokens_count_by_type = 0;
  1925. uint32_t special_tokens_count_from_verification = 0;
  1926. bool special_tokens_definition_mismatch = false;
  1927. for (const auto & t : vocab.token_to_id) {
  1928. const auto & token = t.first;
  1929. const auto & id = t.second;
  1930. // Count all non-normal tokens in the vocab while iterating
  1931. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  1932. special_tokens_count_by_type++;
  1933. }
  1934. // Skip single character tokens
  1935. if (token.length() > 1) {
  1936. bool is_tokenizable = false;
  1937. // Split token string representation in two, in all possible ways
  1938. // and check if both halves can be matched to a valid token
  1939. for (unsigned i = 1; i < token.length();) {
  1940. const auto left = token.substr(0, i);
  1941. const auto right = token.substr(i);
  1942. // check if we didnt partition in the middle of a utf sequence
  1943. auto utf = utf8_len(left.at(left.length() - 1));
  1944. if (utf == 1) {
  1945. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  1946. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  1947. is_tokenizable = true;
  1948. break;
  1949. }
  1950. i++;
  1951. } else {
  1952. // skip over the rest of multibyte utf sequence
  1953. i += utf - 1;
  1954. }
  1955. }
  1956. if (!is_tokenizable) {
  1957. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  1958. // it's faster to re-filter them here, since there are way less candidates now
  1959. // Calculate a total "utf" length of a token string representation
  1960. size_t utf8_str_len = 0;
  1961. for (unsigned i = 0; i < token.length();) {
  1962. utf8_str_len++;
  1963. i += utf8_len(token.at(i));
  1964. }
  1965. // And skip the ones which are one character
  1966. if (utf8_str_len > 1) {
  1967. // At this point what we have left are special tokens only
  1968. vocab.special_tokens_cache[token] = id;
  1969. // Count manually found special tokens
  1970. special_tokens_count_from_verification++;
  1971. // If this manually found special token is not marked as such, flag a mismatch
  1972. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  1973. special_tokens_definition_mismatch = true;
  1974. }
  1975. }
  1976. }
  1977. }
  1978. }
  1979. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  1980. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  1981. __func__,
  1982. special_tokens_count_from_verification, vocab.id_to_token.size(),
  1983. special_tokens_count_by_type, vocab.id_to_token.size()
  1984. );
  1985. } else {
  1986. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  1987. __func__,
  1988. special_tokens_count_from_verification, vocab.id_to_token.size()
  1989. );
  1990. }
  1991. }
  1992. }
  1993. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  1994. const auto & hparams = model.hparams;
  1995. const auto & vocab = model.vocab;
  1996. // hparams
  1997. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  1998. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  1999. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2000. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2001. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2002. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2003. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2004. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2005. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2006. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2007. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  2008. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2009. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2010. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2011. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2012. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2013. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2014. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2015. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2016. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2017. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2018. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2019. if (ml.n_bytes < GB) {
  2020. 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);
  2021. } else {
  2022. 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);
  2023. }
  2024. // general kv
  2025. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2026. // special tokens
  2027. 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() ); }
  2028. 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() ); }
  2029. 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() ); }
  2030. 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() ); }
  2031. 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() ); }
  2032. 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() ); }
  2033. }
  2034. static void llm_load_tensors(
  2035. llama_model_loader & ml,
  2036. llama_model & model,
  2037. int n_gpu_layers,
  2038. int main_gpu,
  2039. const float * tensor_split,
  2040. bool use_mlock,
  2041. llama_progress_callback progress_callback,
  2042. void * progress_callback_user_data) {
  2043. model.t_start_us = ggml_time_us();
  2044. auto & ctx = model.ctx;
  2045. auto & hparams = model.hparams;
  2046. model.n_gpu_layers = n_gpu_layers;
  2047. size_t ctx_size;
  2048. size_t mmapped_size;
  2049. ml.calc_sizes(ctx_size, mmapped_size);
  2050. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  2051. // create the ggml context
  2052. {
  2053. model.buf.resize(ctx_size);
  2054. if (use_mlock) {
  2055. model.mlock_buf.init (model.buf.data);
  2056. model.mlock_buf.grow_to(model.buf.size);
  2057. }
  2058. struct ggml_init_params params = {
  2059. /*.mem_size =*/ model.buf.size,
  2060. /*.mem_buffer =*/ model.buf.data,
  2061. /*.no_alloc =*/ ml.use_mmap,
  2062. };
  2063. model.ctx = ggml_init(params);
  2064. if (!model.ctx) {
  2065. throw std::runtime_error(format("ggml_init() failed"));
  2066. }
  2067. }
  2068. (void) main_gpu;
  2069. #ifdef GGML_USE_CUBLAS
  2070. LLAMA_LOG_INFO("%s: using " GGML_CUDA_NAME " for GPU acceleration\n", __func__);
  2071. ggml_cuda_set_main_device(main_gpu);
  2072. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  2073. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU_SPLIT
  2074. #elif defined(GGML_USE_CLBLAST)
  2075. LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
  2076. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  2077. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU
  2078. #else
  2079. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  2080. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_CPU
  2081. #endif
  2082. // prepare memory for the weights
  2083. size_t vram_weights = 0;
  2084. {
  2085. const int64_t n_embd = hparams.n_embd;
  2086. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2087. const int64_t n_layer = hparams.n_layer;
  2088. const int64_t n_vocab = hparams.n_vocab;
  2089. const auto tn = LLM_TN(model.arch);
  2090. switch (model.arch) {
  2091. case LLM_ARCH_LLAMA:
  2092. case LLM_ARCH_REFACT:
  2093. {
  2094. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2095. // output
  2096. {
  2097. ggml_backend_type backend_norm;
  2098. ggml_backend_type backend_output;
  2099. if (n_gpu_layers > int(n_layer)) {
  2100. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  2101. // on Windows however this is detrimental unless everything is on the GPU
  2102. #ifndef _WIN32
  2103. backend_norm = LLAMA_BACKEND_OFFLOAD;
  2104. #else
  2105. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2106. #endif // _WIN32
  2107. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  2108. } else {
  2109. backend_norm = GGML_BACKEND_CPU;
  2110. backend_output = GGML_BACKEND_CPU;
  2111. }
  2112. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2113. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2114. if (backend_norm == GGML_BACKEND_GPU) {
  2115. vram_weights += ggml_nbytes(model.output_norm);
  2116. }
  2117. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2118. vram_weights += ggml_nbytes(model.output);
  2119. }
  2120. }
  2121. const uint32_t n_ff = hparams.n_ff;
  2122. const int i_gpu_start = n_layer - n_gpu_layers;
  2123. model.layers.resize(n_layer);
  2124. for (uint32_t i = 0; i < n_layer; ++i) {
  2125. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  2126. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  2127. auto & layer = model.layers[i];
  2128. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2129. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  2130. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2131. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2132. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2133. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2134. layer.ffn_gate = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  2135. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2136. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2137. if (backend == GGML_BACKEND_GPU) {
  2138. vram_weights +=
  2139. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  2140. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  2141. ggml_nbytes(layer.ffn_gate) + ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  2142. }
  2143. }
  2144. } break;
  2145. case LLM_ARCH_BAICHUAN:
  2146. {
  2147. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2148. {
  2149. ggml_backend_type backend_norm;
  2150. ggml_backend_type backend_output;
  2151. if (n_gpu_layers > int(n_layer)) {
  2152. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  2153. // on Windows however this is detrimental unless everything is on the GPU
  2154. #ifndef _WIN32
  2155. backend_norm = LLAMA_BACKEND_OFFLOAD;
  2156. #else
  2157. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2158. #endif // _WIN32
  2159. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  2160. } else {
  2161. backend_norm = GGML_BACKEND_CPU;
  2162. backend_output = GGML_BACKEND_CPU;
  2163. }
  2164. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2165. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2166. if (backend_norm == GGML_BACKEND_GPU) {
  2167. vram_weights += ggml_nbytes(model.output_norm);
  2168. }
  2169. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2170. vram_weights += ggml_nbytes(model.output);
  2171. }
  2172. }
  2173. const uint32_t n_ff = hparams.n_ff;
  2174. const int i_gpu_start = n_layer - n_gpu_layers;
  2175. model.layers.resize(n_layer);
  2176. for (uint32_t i = 0; i < n_layer; ++i) {
  2177. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  2178. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  2179. auto & layer = model.layers[i];
  2180. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2181. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  2182. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2183. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  2184. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2185. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2186. layer.ffn_gate = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  2187. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2188. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2189. if (backend == GGML_BACKEND_GPU) {
  2190. vram_weights +=
  2191. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  2192. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  2193. ggml_nbytes(layer.ffn_gate) + ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  2194. }
  2195. }
  2196. } break;
  2197. case LLM_ARCH_FALCON:
  2198. {
  2199. // TODO: CPU-only for now
  2200. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2201. // output
  2202. {
  2203. ggml_backend_type backend_norm;
  2204. ggml_backend_type backend_output;
  2205. if (n_gpu_layers > int(n_layer)) {
  2206. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  2207. // on Windows however this is detrimental unless everything is on the GPU
  2208. #ifndef _WIN32
  2209. backend_norm = LLAMA_BACKEND_OFFLOAD;
  2210. #else
  2211. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2212. #endif // _WIN32
  2213. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  2214. } else {
  2215. backend_norm = GGML_BACKEND_CPU;
  2216. backend_output = GGML_BACKEND_CPU;
  2217. }
  2218. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2219. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2220. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2221. if (backend_norm == GGML_BACKEND_GPU) {
  2222. vram_weights += ggml_nbytes(model.output_norm);
  2223. vram_weights += ggml_nbytes(model.output_norm_b);
  2224. }
  2225. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2226. vram_weights += ggml_nbytes(model.output);
  2227. }
  2228. }
  2229. const uint32_t n_ff = hparams.n_ff;
  2230. const int i_gpu_start = n_layer - n_gpu_layers;
  2231. model.layers.resize(n_layer);
  2232. for (uint32_t i = 0; i < n_layer; ++i) {
  2233. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  2234. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  2235. auto & layer = model.layers[i];
  2236. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2237. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2238. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  2239. layer.attn_norm_2 = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, backend);
  2240. layer.attn_norm_2_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, backend);
  2241. if (backend == GGML_BACKEND_GPU) {
  2242. vram_weights += ggml_nbytes(layer.attn_norm_2);
  2243. vram_weights += ggml_nbytes(layer.attn_norm_2_b);
  2244. }
  2245. }
  2246. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2247. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2248. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2249. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2250. if (backend == GGML_BACKEND_GPU) {
  2251. vram_weights +=
  2252. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  2253. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.wo) +
  2254. ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_up);
  2255. }
  2256. }
  2257. } break;
  2258. case LLM_ARCH_STARCODER:
  2259. {
  2260. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2261. model.pos_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, GGML_BACKEND_CPU);
  2262. // output
  2263. {
  2264. ggml_backend_type backend_norm;
  2265. ggml_backend_type backend_output;
  2266. if (n_gpu_layers > int(n_layer)) {
  2267. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  2268. // on Windows however this is detrimental unless everything is on the GPU
  2269. #ifndef _WIN32
  2270. backend_norm = LLAMA_BACKEND_OFFLOAD;
  2271. #else
  2272. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2273. #endif // _WIN32
  2274. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  2275. } else {
  2276. backend_norm = GGML_BACKEND_CPU;
  2277. backend_output = GGML_BACKEND_CPU;
  2278. }
  2279. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2280. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2281. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2282. if (backend_norm == GGML_BACKEND_GPU) {
  2283. vram_weights += ggml_nbytes(model.output_norm);
  2284. vram_weights += ggml_nbytes(model.output_norm_b);
  2285. }
  2286. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2287. vram_weights += ggml_nbytes(model.output);
  2288. }
  2289. }
  2290. const uint32_t n_ff = hparams.n_ff;
  2291. const int i_gpu_start = n_layer - n_gpu_layers;
  2292. model.layers.resize(n_layer);
  2293. for (uint32_t i = 0; i < n_layer; ++i) {
  2294. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  2295. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  2296. auto & layer = model.layers[i];
  2297. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2298. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2299. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2300. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, backend);
  2301. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2302. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend);
  2303. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2304. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2305. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, backend_split);
  2306. layer.ffn_down_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, backend);
  2307. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2308. layer.ffn_up_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, backend);
  2309. if (backend == GGML_BACKEND_GPU) {
  2310. vram_weights +=
  2311. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  2312. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.bqkv) +
  2313. ggml_nbytes(layer.wo) + ggml_nbytes(layer.bo) +
  2314. ggml_nbytes(layer.ffn_norm) + ggml_nbytes(layer.ffn_norm_b) +
  2315. ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_down_b) +
  2316. ggml_nbytes(layer.ffn_up) + ggml_nbytes(layer.ffn_up_b);
  2317. }
  2318. }
  2319. } break;
  2320. case LLM_ARCH_PERSIMMON:
  2321. {
  2322. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2323. {
  2324. ggml_backend_type backend_norm;
  2325. ggml_backend_type backend_output;
  2326. if (n_gpu_layers > int(n_layer)) {
  2327. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  2328. // on Windows however this is detrimental unless everything is on the GPU
  2329. #ifndef _WIN32
  2330. backend_norm = LLAMA_BACKEND_OFFLOAD;
  2331. #else
  2332. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2333. #endif // _WIN32
  2334. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  2335. } else {
  2336. backend_norm = GGML_BACKEND_CPU;
  2337. backend_output = GGML_BACKEND_CPU;
  2338. }
  2339. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2340. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2341. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2342. if (backend_norm == GGML_BACKEND_GPU) {
  2343. vram_weights += ggml_nbytes(model.output_norm);
  2344. vram_weights += ggml_nbytes(model.output_norm_b);
  2345. }
  2346. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2347. vram_weights += ggml_nbytes(model.output);
  2348. }
  2349. }
  2350. const uint32_t n_ff = hparams.n_ff;
  2351. const int i_gpu_start = n_layer - n_gpu_layers;
  2352. model.layers.resize(n_layer);
  2353. for (uint32_t i = 0; i < n_layer; ++i) {
  2354. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2355. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT;
  2356. auto & layer = model.layers[i];
  2357. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2358. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2359. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2360. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, backend_split);
  2361. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2362. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend_split);
  2363. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, backend_split);
  2364. layer.ffn_down_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, backend_split);
  2365. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2366. layer.ffn_up_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, backend_split);
  2367. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2368. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2369. layer.attn_q_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64}, backend);
  2370. layer.attn_q_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64}, backend);
  2371. layer.attn_k_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64}, backend);
  2372. layer.attn_k_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64}, backend);
  2373. }
  2374. } break;
  2375. case LLM_ARCH_BLOOM:
  2376. {
  2377. // TODO: CPU-only for now
  2378. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2379. model.tok_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}, GGML_BACKEND_CPU);
  2380. model.tok_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}, GGML_BACKEND_CPU);
  2381. // output
  2382. {
  2383. ggml_backend_type backend_norm;
  2384. ggml_backend_type backend_output;
  2385. if (n_gpu_layers > int(n_layer)) {
  2386. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  2387. // on Windows however this is detrimental unless everything is on the GPU
  2388. #ifndef _WIN32
  2389. backend_norm = LLAMA_BACKEND_OFFLOAD;
  2390. #else
  2391. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2392. #endif // _WIN32
  2393. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  2394. } else {
  2395. backend_norm = GGML_BACKEND_CPU;
  2396. backend_output = GGML_BACKEND_CPU;
  2397. }
  2398. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2399. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  2400. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2401. if (backend_norm == GGML_BACKEND_GPU) {
  2402. vram_weights += ggml_nbytes(model.output_norm);
  2403. vram_weights += ggml_nbytes(model.output_norm_b);
  2404. }
  2405. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2406. vram_weights += ggml_nbytes(model.output);
  2407. }
  2408. }
  2409. const uint32_t n_ff = hparams.n_ff;
  2410. const int i_gpu_start = n_layer - n_gpu_layers;
  2411. model.layers.resize(n_layer);
  2412. for (uint32_t i = 0; i < n_layer; ++i) {
  2413. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  2414. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  2415. auto & layer = model.layers[i];
  2416. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2417. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  2418. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2419. layer.bqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, backend_split);
  2420. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2421. layer.bo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, backend_split);
  2422. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2423. layer.ffn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, backend);
  2424. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, backend_split);
  2425. layer.ffn_down_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, backend_split);
  2426. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2427. layer.ffn_up_b = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, backend_split);
  2428. if (backend == GGML_BACKEND_GPU) {
  2429. vram_weights +=
  2430. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  2431. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.bqkv) +
  2432. ggml_nbytes(layer.wo) + ggml_nbytes(layer.bo) +
  2433. ggml_nbytes(layer.ffn_norm) + ggml_nbytes(layer.ffn_norm_b) +
  2434. ggml_nbytes(layer.ffn_up) + ggml_nbytes(layer.ffn_up_b) +
  2435. ggml_nbytes(layer.ffn_down) + ggml_nbytes(layer.ffn_down_b);
  2436. }
  2437. }
  2438. } break;
  2439. case LLM_ARCH_MPT:
  2440. {
  2441. model.tok_embd = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  2442. // output
  2443. {
  2444. ggml_backend_type backend_norm;
  2445. ggml_backend_type backend_output;
  2446. if (n_gpu_layers > int(n_layer)) {
  2447. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  2448. // on Windows however this is detrimental unless everything is on the GPU
  2449. #ifndef _WIN32
  2450. backend_norm = LLAMA_BACKEND_OFFLOAD;
  2451. #else
  2452. backend_norm = n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  2453. #endif // _WIN32
  2454. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  2455. } else {
  2456. backend_norm = GGML_BACKEND_CPU;
  2457. backend_output = GGML_BACKEND_CPU;
  2458. }
  2459. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  2460. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  2461. if (backend_norm == GGML_BACKEND_GPU) {
  2462. vram_weights += ggml_nbytes(model.output_norm);
  2463. }
  2464. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  2465. vram_weights += ggml_nbytes(model.output);
  2466. }
  2467. }
  2468. const uint32_t n_ff = hparams.n_ff;
  2469. const int i_gpu_start = n_layer - n_gpu_layers;
  2470. model.layers.resize(n_layer);
  2471. for (uint32_t i = 0; i < n_layer; ++i) {
  2472. const ggml_backend_type backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  2473. const ggml_backend_type backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  2474. auto & layer = model.layers[i];
  2475. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  2476. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  2477. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  2478. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  2479. layer.ffn_down = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  2480. layer.ffn_up = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  2481. if (backend == GGML_BACKEND_GPU) {
  2482. vram_weights +=
  2483. ggml_nbytes(layer.attn_norm) +
  2484. ggml_nbytes(layer.wqkv) +
  2485. ggml_nbytes(layer.wo) +
  2486. ggml_nbytes(layer.ffn_norm) +
  2487. ggml_nbytes(layer.ffn_down) +
  2488. ggml_nbytes(layer.ffn_up);
  2489. }
  2490. }
  2491. } break;
  2492. default:
  2493. throw std::runtime_error("unknown architecture");
  2494. }
  2495. }
  2496. ml.done_getting_tensors();
  2497. // print memory requirements
  2498. {
  2499. // this is the total memory required to run the inference
  2500. size_t mem_required =
  2501. ctx_size +
  2502. mmapped_size - vram_weights; // weights in VRAM not in memory
  2503. LLAMA_LOG_INFO("%s: mem required = %7.2f MB\n", __func__, mem_required / 1024.0 / 1024.0);
  2504. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  2505. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  2506. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  2507. if (n_gpu_layers > (int) hparams.n_layer) {
  2508. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  2509. }
  2510. #ifdef GGML_USE_CUBLAS
  2511. const int max_backend_supported_layers = hparams.n_layer + 3;
  2512. const int max_offloadable_layers = hparams.n_layer + 3;
  2513. #elif GGML_USE_CLBLAST
  2514. const int max_backend_supported_layers = hparams.n_layer + 1;
  2515. const int max_offloadable_layers = hparams.n_layer + 1;
  2516. #endif // GGML_USE_CUBLAS
  2517. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  2518. LLAMA_LOG_INFO("%s: VRAM used: %.2f MB\n", __func__, vram_weights / 1024.0 / 1024.0);
  2519. #else
  2520. (void) n_gpu_layers;
  2521. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  2522. }
  2523. // populate `tensors_by_name`
  2524. for (int i = 0; i < ml.n_tensors; ++i) {
  2525. struct ggml_tensor * cur = ggml_get_tensor(ctx, ml.get_tensor_name(i));
  2526. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  2527. }
  2528. (void) tensor_split;
  2529. #ifdef GGML_USE_CUBLAS
  2530. {
  2531. ggml_cuda_set_tensor_split(tensor_split);
  2532. }
  2533. #endif
  2534. ml.load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  2535. if (progress_callback) {
  2536. progress_callback(1.0f, progress_callback_user_data);
  2537. }
  2538. model.mapping = std::move(ml.mapping);
  2539. // loading time will be recalculate after the first eval, so
  2540. // we take page faults deferred by mmap() into consideration
  2541. model.t_load_us = ggml_time_us() - model.t_start_us;
  2542. }
  2543. static bool llama_model_load(
  2544. const std::string & fname,
  2545. llama_model & model,
  2546. int n_gpu_layers,
  2547. int main_gpu,
  2548. const float * tensor_split,
  2549. bool use_mmap,
  2550. bool use_mlock,
  2551. bool vocab_only,
  2552. llama_progress_callback progress_callback,
  2553. void *progress_callback_user_data) {
  2554. try {
  2555. llama_model_loader ml(fname, use_mmap);
  2556. model.hparams.vocab_only = vocab_only;
  2557. llm_load_arch (ml, model);
  2558. llm_load_hparams(ml, model);
  2559. llm_load_vocab (ml, model);
  2560. llm_load_print_meta(ml, model);
  2561. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  2562. throw std::runtime_error("vocab size mismatch");
  2563. }
  2564. if (vocab_only) {
  2565. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  2566. return true;
  2567. }
  2568. llm_load_tensors(
  2569. ml, model, n_gpu_layers,
  2570. main_gpu, tensor_split,
  2571. use_mlock, progress_callback, progress_callback_user_data);
  2572. } catch (const std::exception & err) {
  2573. LLAMA_LOG_ERROR("error loading model: %s\n", err.what());
  2574. return false;
  2575. }
  2576. return true;
  2577. }
  2578. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  2579. enum llm_rope_type {
  2580. LLM_ROPE,
  2581. LLM_ROPE_NEOX,
  2582. LLM_ROPE_GLM,
  2583. };
  2584. static struct ggml_tensor * llm_build_inp_embd(
  2585. struct ggml_context * ctx,
  2586. const llama_batch & batch,
  2587. struct ggml_tensor * tok_embd,
  2588. int64_t n_embd,
  2589. int32_t n_tokens,
  2590. const llm_build_cb & cb) {
  2591. struct ggml_tensor * inpL;
  2592. if (batch.token) {
  2593. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_tokens);
  2594. cb(inp_tokens, "inp_tokens", -1);
  2595. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens);
  2596. } else {
  2597. #ifdef GGML_USE_MPI
  2598. GGML_ASSERT(false && "not implemented");
  2599. #endif
  2600. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_tokens);
  2601. }
  2602. return inpL;
  2603. }
  2604. // Persimmon: n_rot = n_embd_head/2
  2605. // Other: n_rot = n_embd_head
  2606. static void llm_build_k_shift(
  2607. const llama_context & lctx,
  2608. struct ggml_context * ctx,
  2609. struct ggml_cgraph * graph,
  2610. int64_t n_rot,
  2611. llm_rope_type type,
  2612. const llm_build_cb & cb) {
  2613. const auto & model = lctx.model;
  2614. const auto & kv_self = lctx.kv_self;
  2615. const auto & cparams = lctx.cparams;
  2616. const auto & hparams = model.hparams;
  2617. const int64_t n_layer = hparams.n_layer;
  2618. const int64_t n_head_kv = hparams.n_head_kv;
  2619. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2620. const int64_t n_embd_head = hparams.n_embd_head();
  2621. const int64_t n_ctx = lctx.cparams.n_ctx;
  2622. const float freq_base = cparams.rope_freq_base;
  2623. const float freq_scale = cparams.rope_freq_scale;
  2624. GGML_ASSERT(n_embd_head % n_rot == 0);
  2625. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_ctx);
  2626. cb(K_shift, "K_shift", -1);
  2627. int rope_type = 0;
  2628. switch (type) {
  2629. case LLM_ROPE: rope_type = 0; break;
  2630. case LLM_ROPE_NEOX: rope_type = 2; break;
  2631. case LLM_ROPE_GLM: rope_type = 4; break;
  2632. }
  2633. for (int il = 0; il < n_layer; ++il) {
  2634. struct ggml_tensor * tmp =
  2635. // we rotate only the first n_rot dimensions
  2636. ggml_rope_custom_inplace(ctx,
  2637. ggml_view_3d(ctx, kv_self.k,
  2638. n_rot, n_head_kv, n_ctx,
  2639. ggml_element_size(kv_self.k)*n_embd_head,
  2640. ggml_element_size(kv_self.k)*n_embd_gqa,
  2641. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il),
  2642. K_shift, n_rot, rope_type, 0, freq_base, freq_scale);
  2643. cb(tmp, "K_shifted", il);
  2644. ggml_build_forward_expand(graph, tmp);
  2645. }
  2646. }
  2647. static void llm_build_kv_store(
  2648. const llama_context & lctx,
  2649. struct ggml_context * ctx,
  2650. struct ggml_cgraph * graph,
  2651. struct ggml_tensor * k_cur,
  2652. struct ggml_tensor * v_cur,
  2653. int32_t n_tokens,
  2654. int32_t kv_head,
  2655. const llm_build_cb & cb,
  2656. int64_t il) {
  2657. const auto & model = lctx.model;
  2658. const auto & kv_self = lctx.kv_self;
  2659. const auto & cparams = lctx.cparams;
  2660. const auto & hparams = model.hparams;
  2661. const int64_t n_ctx = cparams.n_ctx;
  2662. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2663. // compute the transposed [n_tokens, n_embd] V matrix
  2664. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_gqa, n_tokens));
  2665. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  2666. cb(v_cur_t, "v_cur_t", il);
  2667. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv_self.k, n_tokens*n_embd_gqa,
  2668. (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + kv_head));
  2669. cb(k_cache_view, "k_cache_view", il);
  2670. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv_self.v, n_tokens, n_embd_gqa,
  2671. ( n_ctx)*ggml_element_size(kv_self.v),
  2672. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + kv_head*ggml_element_size(kv_self.v));
  2673. cb(v_cache_view, "v_cache_view", il);
  2674. // important: storing RoPE-ed version of K in the KV cache!
  2675. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  2676. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  2677. }
  2678. enum llm_norm_type {
  2679. LLM_NORM,
  2680. LLM_NORM_RMS,
  2681. };
  2682. static struct ggml_tensor * llm_build_norm(
  2683. struct ggml_context * ctx,
  2684. struct ggml_tensor * cur,
  2685. struct ggml_tensor * mw,
  2686. struct ggml_tensor * mb,
  2687. llm_norm_type type,
  2688. float eps,
  2689. const llm_build_cb & cb,
  2690. int il) {
  2691. switch (type) {
  2692. case LLM_NORM: cur = ggml_norm (ctx, cur, eps); break;
  2693. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, eps); break;
  2694. }
  2695. if (mw || mb) {
  2696. cb(cur, "norm", il);
  2697. }
  2698. if (mw) {
  2699. cur = ggml_mul(ctx, cur, mw);
  2700. if (mb) {
  2701. cb(cur, "norm_w", il);
  2702. }
  2703. }
  2704. if (mb) {
  2705. cur = ggml_add(ctx, cur, mb);
  2706. }
  2707. return cur;
  2708. }
  2709. enum llm_ffn_op_type {
  2710. LLM_FFN_SILU,
  2711. LLM_FFN_GELU,
  2712. LLM_FFN_RELU,
  2713. LLM_FFN_RELU_SQR,
  2714. };
  2715. enum llm_ffn_gate_type {
  2716. LLM_FFN_SEQ,
  2717. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  2718. };
  2719. static struct ggml_tensor * llm_build_ffn(
  2720. struct ggml_context * ctx,
  2721. struct ggml_tensor * cur,
  2722. struct ggml_tensor * up,
  2723. struct ggml_tensor * up_b,
  2724. struct ggml_tensor * gate,
  2725. struct ggml_tensor * gate_b,
  2726. struct ggml_tensor * down,
  2727. struct ggml_tensor * down_b,
  2728. llm_ffn_op_type type_op,
  2729. llm_ffn_gate_type type_gate,
  2730. const llm_build_cb & cb,
  2731. int il) {
  2732. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  2733. cb(tmp, "ffn_up", il);
  2734. if (up_b) {
  2735. tmp = ggml_add(ctx, tmp, up_b);
  2736. cb(tmp, "ffn_up_b", il);
  2737. }
  2738. if (gate) {
  2739. switch (type_gate) {
  2740. case LLM_FFN_SEQ:
  2741. {
  2742. cur = ggml_mul_mat(ctx, gate, tmp);
  2743. cb(cur, "ffn_gate", il);
  2744. } break;
  2745. case LLM_FFN_PAR:
  2746. {
  2747. cur = ggml_mul_mat(ctx, gate, cur);
  2748. cb(cur, "ffn_gate", il);
  2749. } break;
  2750. }
  2751. if (gate_b) {
  2752. cur = ggml_add(ctx, cur, gate_b);
  2753. cb(cur, "ffn_gate_b", il);
  2754. }
  2755. } else {
  2756. cur = tmp;
  2757. }
  2758. switch (type_op) {
  2759. case LLM_FFN_SILU:
  2760. {
  2761. cur = ggml_silu(ctx, cur);
  2762. cb(cur, "ffn_silu", il);
  2763. } break;
  2764. case LLM_FFN_GELU:
  2765. {
  2766. cur = ggml_gelu(ctx, cur);
  2767. cb(cur, "ffn_gelu", il);
  2768. } break;
  2769. case LLM_FFN_RELU:
  2770. {
  2771. cur = ggml_relu(ctx, cur);
  2772. cb(cur, "ffn_relu", il);
  2773. } break;
  2774. case LLM_FFN_RELU_SQR:
  2775. {
  2776. cur = ggml_relu(ctx, cur);
  2777. cb(cur, "ffn_relu", il);
  2778. cur = ggml_sqr(ctx, cur);
  2779. cb(cur, "ffn_sqr(relu)", il);
  2780. } break;
  2781. }
  2782. if (type_gate == LLM_FFN_PAR) {
  2783. cur = ggml_mul(ctx, cur, tmp);
  2784. cb(cur, "ffn_gate_par", il);
  2785. }
  2786. cur = ggml_mul_mat(ctx, down, cur);
  2787. if (down_b) {
  2788. cb(cur, "ffn_down", il);
  2789. }
  2790. if (down_b) {
  2791. cur = ggml_add(ctx, cur, down_b);
  2792. }
  2793. return cur;
  2794. }
  2795. // if max_alibi_bias > 0 then apply ALiBi
  2796. static struct ggml_tensor * llm_build_kqv(
  2797. const llama_context & lctx,
  2798. struct ggml_context * ctx,
  2799. struct ggml_tensor * cur,
  2800. struct ggml_tensor * wo,
  2801. struct ggml_tensor * wo_b,
  2802. struct ggml_tensor * q_cur,
  2803. struct ggml_tensor * kq_scale,
  2804. struct ggml_tensor * kq_mask,
  2805. int32_t n_tokens,
  2806. int32_t n_kv,
  2807. float alibi_bias_max,
  2808. const llm_build_cb & cb,
  2809. int il) {
  2810. const auto & model = lctx.model;
  2811. const auto & kv_self = lctx.kv_self;
  2812. const auto & cparams = lctx.cparams;
  2813. const auto & hparams = model.hparams;
  2814. const int64_t n_ctx = cparams.n_ctx;
  2815. const int64_t n_embd = hparams.n_embd;
  2816. const int64_t n_head = hparams.n_head;
  2817. const int64_t n_head_kv = hparams.n_head_kv;
  2818. const int64_t n_embd_head = hparams.n_embd_head();
  2819. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2820. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  2821. cb(q, "q", il);
  2822. struct ggml_tensor * k =
  2823. ggml_view_3d(ctx, kv_self.k,
  2824. n_embd_head, n_kv, n_head_kv,
  2825. ggml_element_size(kv_self.k)*n_embd_gqa,
  2826. ggml_element_size(kv_self.k)*n_embd_head,
  2827. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  2828. cb(k, "k", il);
  2829. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  2830. cb(kq, "kq", il);
  2831. kq = ggml_scale(ctx, kq, kq_scale);
  2832. cb(kq, "kq_scaled", il);
  2833. if (alibi_bias_max > 0.0f) {
  2834. // TODO: n_head or n_head_kv
  2835. // TODO: K-shift is likely not working
  2836. // TODO: change to ggml_add
  2837. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, alibi_bias_max);
  2838. cb(kq, "kq_scaled_alibi", il);
  2839. }
  2840. kq = ggml_add(ctx, kq, kq_mask);
  2841. cb(kq, "kq_masked", il);
  2842. kq = ggml_soft_max(ctx, kq);
  2843. cb(kq, "kq_soft_max", il);
  2844. // split cached v into n_head heads
  2845. struct ggml_tensor * v =
  2846. ggml_view_3d(ctx, kv_self.v,
  2847. n_kv, n_embd_head, n_head_kv,
  2848. ggml_element_size(kv_self.v)*n_ctx,
  2849. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  2850. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  2851. cb(v, "v", il);
  2852. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  2853. cb(kqv, "kqv", il);
  2854. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  2855. cb(kqv_merged, "kqv_merged", il);
  2856. cur = ggml_cont_2d(ctx, kqv_merged, n_embd, n_tokens);
  2857. cb(cur, "kqv_merged_cont", il);
  2858. cur = ggml_mul_mat(ctx, wo, cur);
  2859. if (wo_b) {
  2860. cb(cur, "kqv_wo", il);
  2861. }
  2862. if (wo_b) {
  2863. cur = ggml_add(ctx, cur, wo_b);
  2864. }
  2865. return cur;
  2866. }
  2867. static struct ggml_cgraph * llm_build_llama(
  2868. llama_context & lctx,
  2869. const llama_batch & batch,
  2870. const llm_build_cb & cb,
  2871. bool worst_case) {
  2872. const auto & model = lctx.model;
  2873. const auto & hparams = model.hparams;
  2874. const auto & cparams = lctx.cparams;
  2875. const auto & kv_self = lctx.kv_self;
  2876. GGML_ASSERT(!!kv_self.ctx);
  2877. const int64_t n_embd = hparams.n_embd;
  2878. const int64_t n_layer = hparams.n_layer;
  2879. const int64_t n_ctx = cparams.n_ctx;
  2880. const int64_t n_head = hparams.n_head;
  2881. const int64_t n_head_kv = hparams.n_head_kv;
  2882. const int64_t n_embd_head = hparams.n_embd_head();
  2883. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2884. const float freq_base = cparams.rope_freq_base;
  2885. const float freq_scale = cparams.rope_freq_scale;
  2886. const float norm_rms_eps = hparams.f_norm_rms_eps;
  2887. const int32_t n_tokens = batch.n_tokens;
  2888. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  2889. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  2890. const bool do_rope_shift = worst_case || kv_self.has_shift;
  2891. //printf("n_kv = %d\n", n_kv);
  2892. auto & buf_compute = lctx.buf_compute;
  2893. struct ggml_init_params params = {
  2894. /*.mem_size =*/ buf_compute.size,
  2895. /*.mem_buffer =*/ buf_compute.data,
  2896. /*.no_alloc =*/ true,
  2897. };
  2898. struct ggml_context * ctx0 = ggml_init(params);
  2899. ggml_cgraph * gf = ggml_new_graph(ctx0);
  2900. struct ggml_tensor * cur;
  2901. struct ggml_tensor * inpL;
  2902. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  2903. cb(inpL, "inp_embd", -1);
  2904. // inp_pos - contains the positions
  2905. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  2906. cb(inp_pos, "inp_pos", -1);
  2907. // KQ_scale
  2908. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  2909. cb(KQ_scale, "KQ_scale", -1);
  2910. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2911. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  2912. cb(KQ_mask, "KQ_mask", -1);
  2913. // shift the entire K-cache if needed
  2914. if (do_rope_shift) {
  2915. llm_build_k_shift(lctx, ctx0, gf, n_embd_head, LLM_ROPE, cb);
  2916. }
  2917. for (int il = 0; il < n_layer; ++il) {
  2918. struct ggml_tensor * inpSA = inpL;
  2919. // norm
  2920. cur = llm_build_norm(ctx0, inpL,
  2921. model.layers[il].attn_norm, NULL,
  2922. LLM_NORM_RMS, norm_rms_eps, cb, il);
  2923. cb(cur, "attn_norm", il);
  2924. // self-attention
  2925. {
  2926. // compute Q and K and RoPE them
  2927. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  2928. cb(Qcur, "Qcur", il);
  2929. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  2930. cb(Kcur, "Kcur", il);
  2931. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  2932. cb(Vcur, "Vcur", il);
  2933. Qcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  2934. cb(Qcur, "Qcur", il);
  2935. Kcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  2936. cb(Kcur, "Kcur", il);
  2937. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  2938. cur = llm_build_kqv(lctx, ctx0, cur,
  2939. model.layers[il].wo, NULL,
  2940. Qcur, KQ_scale, KQ_mask, n_tokens, n_kv, -1.0f, cb, il);
  2941. cb(cur, "kqv_out", il);
  2942. }
  2943. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  2944. cb(ffn_inp, "ffn_inp", il);
  2945. // feed-forward network
  2946. {
  2947. cur = llm_build_norm(ctx0, ffn_inp,
  2948. model.layers[il].ffn_norm, NULL,
  2949. LLM_NORM_RMS, norm_rms_eps, cb, il);
  2950. cb(cur, "ffn_norm", il);
  2951. cur = llm_build_ffn(ctx0, cur,
  2952. model.layers[il].ffn_up, NULL,
  2953. model.layers[il].ffn_gate, NULL,
  2954. model.layers[il].ffn_down, NULL,
  2955. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2956. cb(cur, "ffn_out", il);
  2957. }
  2958. cur = ggml_add(ctx0, cur, ffn_inp);
  2959. cb(cur, "l_out", il);
  2960. // input for next layer
  2961. inpL = cur;
  2962. }
  2963. cur = inpL;
  2964. cur = llm_build_norm(ctx0, cur,
  2965. model.output_norm, NULL,
  2966. LLM_NORM_RMS, norm_rms_eps, cb, -1);
  2967. cb(cur, "result_norm", -1);
  2968. // lm_head
  2969. cur = ggml_mul_mat(ctx0, model.output, cur);
  2970. cb(cur, "result_output", -1);
  2971. ggml_build_forward_expand(gf, cur);
  2972. ggml_free(ctx0);
  2973. return gf;
  2974. }
  2975. static struct ggml_cgraph * llm_build_baichaun(
  2976. llama_context & lctx,
  2977. const llama_batch & batch,
  2978. const llm_build_cb & cb,
  2979. bool worst_case) {
  2980. const auto & model = lctx.model;
  2981. const auto & hparams = model.hparams;
  2982. const auto & cparams = lctx.cparams;
  2983. const auto & kv_self = lctx.kv_self;
  2984. GGML_ASSERT(!!kv_self.ctx);
  2985. const int64_t n_embd = hparams.n_embd;
  2986. const int64_t n_layer = hparams.n_layer;
  2987. const int64_t n_ctx = cparams.n_ctx;
  2988. const int64_t n_head = hparams.n_head;
  2989. const int64_t n_head_kv = hparams.n_head_kv;
  2990. const int64_t n_embd_head = hparams.n_embd_head();
  2991. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2992. const float freq_base = cparams.rope_freq_base;
  2993. const float freq_scale = cparams.rope_freq_scale;
  2994. const float norm_rms_eps = hparams.f_norm_rms_eps;
  2995. const int32_t n_tokens = batch.n_tokens;
  2996. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  2997. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  2998. const bool do_rope_shift = worst_case || kv_self.has_shift;
  2999. auto & buf_compute = lctx.buf_compute;
  3000. struct ggml_init_params params = {
  3001. /*.mem_size =*/ buf_compute.size,
  3002. /*.mem_buffer =*/ buf_compute.data,
  3003. /*.no_alloc =*/ true,
  3004. };
  3005. struct ggml_context * ctx0 = ggml_init(params);
  3006. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3007. struct ggml_tensor * cur;
  3008. struct ggml_tensor * inpL;
  3009. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  3010. cb(inpL, "inp_embd", -1);
  3011. // inp_pos - contains the positions
  3012. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3013. cb(inp_pos, "inp_pos", -1);
  3014. // KQ_scale
  3015. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3016. cb(KQ_scale, "KQ_scale", -1);
  3017. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3018. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3019. cb(KQ_mask, "KQ_mask", -1);
  3020. // shift the entire K-cache if needed
  3021. if (do_rope_shift) {
  3022. llm_build_k_shift(lctx, ctx0, gf, n_embd_head, LLM_ROPE, cb);
  3023. }
  3024. for (int il = 0; il < n_layer; ++il) {
  3025. struct ggml_tensor * inpSA = inpL;
  3026. cur = llm_build_norm(ctx0, inpL,
  3027. model.layers[il].attn_norm, NULL,
  3028. LLM_NORM_RMS, norm_rms_eps, cb, il);
  3029. cb(cur, "attn_norm", il);
  3030. // self-attention
  3031. {
  3032. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3033. cb(Qcur, "Qcur", il);
  3034. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3035. cb(Kcur, "Kcur", il);
  3036. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3037. cb(Vcur, "Vcur", il);
  3038. switch (model.type) {
  3039. case MODEL_7B:
  3040. Qcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  3041. Kcur = ggml_rope_custom(ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, n_embd_head, 0, 0, freq_base, freq_scale);
  3042. break;
  3043. case MODEL_13B:
  3044. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  3045. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  3046. break;
  3047. default:
  3048. GGML_ASSERT(false);
  3049. }
  3050. cb(Qcur, "Qcur", il);
  3051. cb(Kcur, "Kcur", il);
  3052. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  3053. // apply ALiBi for 13B model
  3054. const float alibi_bias_max = model.type == MODEL_13B ? 8.0f : -1.0f;
  3055. cur = llm_build_kqv(lctx, ctx0, cur,
  3056. model.layers[il].wo, NULL,
  3057. Qcur, KQ_scale, KQ_mask, n_tokens, n_kv, alibi_bias_max, cb, il);
  3058. cb(cur, "kqv_out", il);
  3059. }
  3060. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3061. cb(ffn_inp, "ffn_inp", il);
  3062. // feed-forward network
  3063. {
  3064. cur = llm_build_norm(ctx0, ffn_inp,
  3065. model.layers[il].ffn_norm, NULL,
  3066. LLM_NORM_RMS, norm_rms_eps, cb, il);
  3067. cb(cur, "ffn_norm", il);
  3068. cur = llm_build_ffn(ctx0, cur,
  3069. model.layers[il].ffn_up, NULL,
  3070. model.layers[il].ffn_gate, NULL,
  3071. model.layers[il].ffn_down, NULL,
  3072. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3073. cb(cur, "ffn_out", il);
  3074. }
  3075. cur = ggml_add(ctx0, cur, ffn_inp);
  3076. cb(cur, "l_out", il);
  3077. // input for next layer
  3078. inpL = cur;
  3079. }
  3080. cur = inpL;
  3081. cur = llm_build_norm(ctx0, cur,
  3082. model.output_norm, NULL,
  3083. LLM_NORM_RMS, norm_rms_eps, cb, -1);
  3084. cb(cur, "result_norm", -1);
  3085. // lm_head
  3086. cur = ggml_mul_mat(ctx0, model.output, cur);
  3087. cb(cur, "result_output", -1);
  3088. ggml_build_forward_expand(gf, cur);
  3089. ggml_free(ctx0);
  3090. return gf;
  3091. }
  3092. static struct ggml_cgraph * llm_build_falcon(
  3093. llama_context & lctx,
  3094. const llama_batch & batch,
  3095. const llm_build_cb & cb,
  3096. bool worst_case) {
  3097. const auto & model = lctx.model;
  3098. const auto & hparams = model.hparams;
  3099. const auto & cparams = lctx.cparams;
  3100. const auto & kv_self = lctx.kv_self;
  3101. GGML_ASSERT(!!kv_self.ctx);
  3102. const int64_t n_embd = hparams.n_embd;
  3103. const int64_t n_layer = hparams.n_layer;
  3104. const int64_t n_ctx = cparams.n_ctx;
  3105. const int64_t n_head = hparams.n_head;
  3106. const int64_t n_head_kv = hparams.n_head_kv;
  3107. const int64_t n_embd_head = hparams.n_embd_head();
  3108. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3109. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3110. const float freq_base = cparams.rope_freq_base;
  3111. const float freq_scale = cparams.rope_freq_scale;
  3112. const float norm_eps = hparams.f_norm_eps;
  3113. const int32_t n_tokens = batch.n_tokens;
  3114. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  3115. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  3116. const bool do_rope_shift = worst_case || kv_self.has_shift;
  3117. //printf("kv_head = %d, n_kv = %d, n_tokens = %d, n_ctx = %d, is_measure = %d, has_shift = %d\n",
  3118. // kv_head, n_kv, n_tokens, n_ctx, ggml_allocr_is_measure(lctx.alloc), kv_self.has_shift);
  3119. auto & buf_compute = lctx.buf_compute;
  3120. struct ggml_init_params params = {
  3121. /*.mem_size =*/ buf_compute.size,
  3122. /*.mem_buffer =*/ buf_compute.data,
  3123. /*.no_alloc =*/ true,
  3124. };
  3125. struct ggml_context * ctx0 = ggml_init(params);
  3126. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3127. struct ggml_tensor * cur;
  3128. struct ggml_tensor * inpL;
  3129. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  3130. cb(inpL, "inp_embd", -1);
  3131. // inp_pos - contains the positions
  3132. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3133. cb(inp_pos, "inp_pos", -1);
  3134. // KQ_scale
  3135. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3136. cb(KQ_scale, "KQ_scale", -1);
  3137. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3138. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3139. cb(KQ_mask, "KQ_mask", -1);
  3140. // shift the entire K-cache if needed
  3141. if (do_rope_shift) {
  3142. llm_build_k_shift(lctx, ctx0, gf, n_embd_head, LLM_ROPE_NEOX, cb);
  3143. }
  3144. for (int il = 0; il < n_layer; ++il) {
  3145. struct ggml_tensor * attn_norm;
  3146. attn_norm = llm_build_norm(ctx0, inpL,
  3147. model.layers[il].attn_norm,
  3148. model.layers[il].attn_norm_b,
  3149. LLM_NORM, norm_eps, cb, il);
  3150. cb(attn_norm, "attn_norm", il);
  3151. // self-attention
  3152. {
  3153. if (model.layers[il].attn_norm_2) {
  3154. // Falcon-40B
  3155. cur = llm_build_norm(ctx0, attn_norm,
  3156. model.layers[il].attn_norm_2,
  3157. model.layers[il].attn_norm_2_b,
  3158. LLM_NORM, norm_eps, cb, il);
  3159. cb(cur, "attn_norm_2", il);
  3160. } else {
  3161. cur = attn_norm;
  3162. }
  3163. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3164. cb(cur, "wqkv", il);
  3165. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3166. 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)));
  3167. 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)));
  3168. cb(Qcur, "Qcur", il);
  3169. cb(Kcur, "Kcur", il);
  3170. cb(Vcur, "Vcur", il);
  3171. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3172. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  3173. // using mode = 2 for neox mode
  3174. Qcur = ggml_rope_custom(ctx0, Qcur, inp_pos, n_embd_head, 2, 0, freq_base, freq_scale);
  3175. cb(Qcur, "Qcur", il);
  3176. Kcur = ggml_rope_custom(ctx0, Kcur, inp_pos, n_embd_head, 2, 0, freq_base, freq_scale);
  3177. cb(Kcur, "Kcur", il);
  3178. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  3179. cur = llm_build_kqv(lctx, ctx0, attn_norm,
  3180. model.layers[il].wo, NULL,
  3181. Qcur, KQ_scale, KQ_mask, n_tokens, n_kv, -1.0f, cb, il);
  3182. cb(cur, "kqv_out", il);
  3183. }
  3184. struct ggml_tensor * ffn_inp = cur;
  3185. // feed forward
  3186. {
  3187. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  3188. model.layers[il].ffn_up, NULL,
  3189. NULL, NULL,
  3190. model.layers[il].ffn_down, NULL,
  3191. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3192. cb(cur, "ffn_out", il);
  3193. }
  3194. cur = ggml_add(ctx0, cur, ffn_inp);
  3195. cb(cur, "l_out", il);
  3196. cur = ggml_add(ctx0, cur, inpL);
  3197. cb(cur, "l_out", il);
  3198. // input for next layer
  3199. inpL = cur;
  3200. }
  3201. cur = inpL;
  3202. // norm
  3203. cur = llm_build_norm(ctx0, cur,
  3204. model.output_norm,
  3205. model.output_norm_b,
  3206. LLM_NORM, norm_eps, cb, -1);
  3207. cb(cur, "result_norm", -1);
  3208. cur = ggml_mul_mat(ctx0, model.output, cur);
  3209. cb(cur, "result_output", -1);
  3210. ggml_build_forward_expand(gf, cur);
  3211. ggml_free(ctx0);
  3212. return gf;
  3213. }
  3214. static struct ggml_cgraph * llm_build_starcoder(
  3215. llama_context & lctx,
  3216. const llama_batch & batch,
  3217. const llm_build_cb & cb,
  3218. bool worst_case) {
  3219. const auto & model = lctx.model;
  3220. const auto & hparams = model.hparams;
  3221. const auto & cparams = lctx.cparams;
  3222. const auto & kv_self = lctx.kv_self;
  3223. GGML_ASSERT(!!kv_self.ctx);
  3224. const int64_t n_embd = hparams.n_embd;
  3225. const int64_t n_layer = hparams.n_layer;
  3226. const int64_t n_ctx = cparams.n_ctx;
  3227. const int64_t n_head = hparams.n_head;
  3228. const int64_t n_embd_head = hparams.n_embd_head();
  3229. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3230. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3231. const float norm_eps = hparams.f_norm_eps;
  3232. const int32_t n_tokens = batch.n_tokens;
  3233. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  3234. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  3235. auto & buf_compute = lctx.buf_compute;
  3236. struct ggml_init_params params = {
  3237. /*.mem_size =*/ buf_compute.size,
  3238. /*.mem_buffer =*/ buf_compute.data,
  3239. /*.no_alloc =*/ true,
  3240. };
  3241. struct ggml_context * ctx0 = ggml_init(params);
  3242. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3243. struct ggml_tensor * cur;
  3244. struct ggml_tensor * pos;
  3245. struct ggml_tensor * inpL;
  3246. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  3247. cb(inpL, "inp_embd", -1);
  3248. // inp_pos - contains the positions
  3249. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3250. cb(inp_pos, "inp_pos", -1);
  3251. // KQ_scale
  3252. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3253. cb(KQ_scale, "KQ_scale", -1);
  3254. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3255. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3256. cb(KQ_mask, "KQ_mask", -1);
  3257. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  3258. cb(pos, "pos_embd", -1);
  3259. inpL = ggml_add(ctx0, inpL, pos);
  3260. cb(inpL, "inpL", -1);
  3261. for (int il = 0; il < n_layer; ++il) {
  3262. cur = llm_build_norm(ctx0, inpL,
  3263. model.layers[il].attn_norm,
  3264. model.layers[il].attn_norm_b,
  3265. LLM_NORM, norm_eps, cb, il);
  3266. cb(cur, "attn_norm", il);
  3267. // self-attention
  3268. {
  3269. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3270. cb(cur, "wqkv", il);
  3271. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3272. cb(cur, "bqkv", il);
  3273. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3274. 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)));
  3275. 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)));
  3276. cb(Qcur, "Qcur", il);
  3277. cb(Kcur, "Kcur", il);
  3278. cb(Vcur, "Vcur", il);
  3279. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3280. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  3281. cur = llm_build_kqv(lctx, ctx0, cur,
  3282. model.layers[il].wo, model.layers[il].bo,
  3283. Qcur, KQ_scale, KQ_mask, n_tokens, n_kv, -1.0f, cb, il);
  3284. cb(cur, "kqv_out", il);
  3285. }
  3286. // add the input
  3287. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  3288. cb(ffn_inp, "ffn_inp", il);
  3289. // FF
  3290. {
  3291. cur = llm_build_norm(ctx0, ffn_inp,
  3292. model.layers[il].ffn_norm,
  3293. model.layers[il].ffn_norm_b,
  3294. LLM_NORM, norm_eps, cb, il);
  3295. cb(cur, "ffn_norm", il);
  3296. cur = llm_build_ffn(ctx0, cur,
  3297. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  3298. NULL, NULL,
  3299. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  3300. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3301. cb(cur, "ffn_out", il);
  3302. }
  3303. inpL = ggml_add(ctx0, cur, ffn_inp);
  3304. cb(inpL, "l_out", il);
  3305. }
  3306. cur = llm_build_norm(ctx0, inpL,
  3307. model.output_norm,
  3308. model.output_norm_b,
  3309. LLM_NORM, norm_eps, cb, -1);
  3310. cb(cur, "result_norm", -1);
  3311. cur = ggml_mul_mat(ctx0, model.output, cur);
  3312. cb(cur, "result_output", -1);
  3313. ggml_build_forward_expand(gf, cur);
  3314. ggml_free(ctx0);
  3315. return gf;
  3316. }
  3317. static struct ggml_cgraph * llm_build_persimmon(
  3318. llama_context & lctx,
  3319. const llama_batch & batch,
  3320. const llm_build_cb & cb,
  3321. bool worst_case) {
  3322. const auto & model = lctx.model;
  3323. const auto & hparams = model.hparams;
  3324. const auto & kv_self = lctx.kv_self;
  3325. GGML_ASSERT(!!kv_self.ctx);
  3326. const auto & cparams = lctx.cparams;
  3327. const int64_t n_embd = hparams.n_embd;
  3328. const int64_t n_layer = hparams.n_layer;
  3329. const int64_t n_ctx = cparams.n_ctx;
  3330. const int64_t n_head_kv = hparams.n_head_kv;
  3331. const int64_t n_head = hparams.n_head;
  3332. const int64_t n_embd_head = hparams.n_embd_head();
  3333. const int64_t n_rot = n_embd_head / 2;
  3334. const float freq_base = cparams.rope_freq_base;
  3335. const float freq_scale = cparams.rope_freq_scale;
  3336. const float norm_eps = hparams.f_norm_eps;
  3337. const int32_t n_tokens = batch.n_tokens;
  3338. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  3339. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  3340. const bool do_rope_shift = worst_case || kv_self.has_shift;
  3341. auto & buf_compute = lctx.buf_compute;
  3342. struct ggml_init_params params = {
  3343. /*.mem_size =*/ buf_compute.size,
  3344. /*.mem_buffer =*/ buf_compute.data,
  3345. /*.no_alloc =*/ true,
  3346. };
  3347. struct ggml_context * ctx0 = ggml_init(params);
  3348. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3349. struct ggml_tensor * cur;
  3350. struct ggml_tensor * inpL;
  3351. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  3352. cb(inpL, "imp_embd", -1);
  3353. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3354. cb(inp_pos, "inp_pos", -1);
  3355. // KQ_scale
  3356. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3357. cb(KQ_scale, "KQ_scale", -1);
  3358. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3359. cb(KQ_mask, "KQ_mask", -1);
  3360. if (do_rope_shift) {
  3361. llm_build_k_shift(lctx, ctx0, gf, n_rot, LLM_ROPE_NEOX, cb);
  3362. }
  3363. for (int il = 0; il < n_layer; ++il) {
  3364. struct ggml_tensor * residual = inpL;
  3365. cur = llm_build_norm(ctx0, inpL,
  3366. model.layers[il].attn_norm,
  3367. model.layers[il].attn_norm_b,
  3368. LLM_NORM, norm_eps, cb, il);
  3369. cb(cur, "attn_norm", il);
  3370. // self attention
  3371. {
  3372. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3373. cb(cur, "wqkv", il);
  3374. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3375. cb(cur, "bqkv", il);
  3376. // split qkv
  3377. GGML_ASSERT(n_head_kv == n_head);
  3378. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  3379. cb(tmpqkv, "tmpqkv", il);
  3380. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  3381. cb(tmpqkv_perm, "tmpqkv", il);
  3382. struct ggml_tensor * tmpq = ggml_view_3d(
  3383. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  3384. ggml_element_size(tmpqkv_perm) * n_embd_head,
  3385. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  3386. 0
  3387. );
  3388. cb(tmpq, "tmpq", il);
  3389. struct ggml_tensor * tmpk = ggml_view_3d(
  3390. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  3391. ggml_element_size(tmpqkv_perm) * n_embd_head,
  3392. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  3393. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  3394. );
  3395. cb(tmpk, "tmpk", il);
  3396. // Q/K Layernorm
  3397. tmpq = llm_build_norm(ctx0, tmpq,
  3398. model.layers[il].attn_q_norm,
  3399. model.layers[il].attn_q_norm_b,
  3400. LLM_NORM, norm_eps, cb, il);
  3401. cb(tmpq, "tmpq", il);
  3402. tmpk = llm_build_norm(ctx0, tmpk,
  3403. model.layers[il].attn_k_norm,
  3404. model.layers[il].attn_k_norm_b,
  3405. LLM_NORM, norm_eps, cb, il);
  3406. cb(tmpk, "tmpk", il);
  3407. // RoPE the first n_rot of q/k, pass the other half, and concat.
  3408. struct ggml_tensor * qrot = ggml_view_3d(
  3409. ctx0, tmpq, n_rot, n_head, n_tokens,
  3410. ggml_element_size(tmpq) * n_embd_head,
  3411. ggml_element_size(tmpq) * n_embd_head * n_head,
  3412. 0
  3413. );
  3414. cb(qrot, "qrot", il);
  3415. struct ggml_tensor * krot = ggml_view_3d(
  3416. ctx0, tmpk, n_rot, n_head, n_tokens,
  3417. ggml_element_size(tmpk) * n_embd_head,
  3418. ggml_element_size(tmpk) * n_embd_head * n_head,
  3419. 0
  3420. );
  3421. cb(krot, "krot", il);
  3422. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  3423. struct ggml_tensor * qpass = ggml_view_3d(
  3424. ctx0, tmpq, n_rot, n_head, n_tokens,
  3425. ggml_element_size(tmpq) * n_embd_head,
  3426. ggml_element_size(tmpq) * n_embd_head * n_head,
  3427. ggml_element_size(tmpq) * n_rot
  3428. );
  3429. cb(qpass, "qpass", il);
  3430. struct ggml_tensor * kpass = ggml_view_3d(
  3431. ctx0, tmpk, n_rot, n_head, n_tokens,
  3432. ggml_element_size(tmpk) * n_embd_head,
  3433. ggml_element_size(tmpk) * n_embd_head * n_head,
  3434. ggml_element_size(tmpk) * n_rot
  3435. );
  3436. cb(kpass, "kpass", il);
  3437. struct ggml_tensor * qrotated = ggml_rope_custom(
  3438. ctx0, qrot, inp_pos, n_rot, 2, 0, freq_base, freq_scale
  3439. );
  3440. cb(qrotated, "qrotated", il);
  3441. struct ggml_tensor * krotated = ggml_rope_custom(
  3442. ctx0, krot, inp_pos, n_rot, 2, 0, freq_base, freq_scale
  3443. );
  3444. cb(krotated, "krotated", il);
  3445. // ggml currently only supports concatenation on dim=2
  3446. // so we need to permute qrot, qpass, concat, then permute back.
  3447. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  3448. cb(qrotated, "qrotated", il);
  3449. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  3450. cb(krotated, "krotated", il);
  3451. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  3452. cb(qpass, "qpass", il);
  3453. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  3454. cb(kpass, "kpass", il);
  3455. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  3456. cb(Qcur, "Qcur", il);
  3457. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  3458. cb(Kcur, "Kcur", il);
  3459. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 1, 2, 0, 3));
  3460. cb(Q, "Q", il);
  3461. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  3462. cb(Kcur, "Kcur", il);
  3463. struct ggml_tensor * Vcur = ggml_view_3d(
  3464. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  3465. ggml_element_size(tmpqkv_perm) * n_embd_head,
  3466. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  3467. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  3468. );
  3469. cb(Vcur, "Vcur", il);
  3470. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  3471. // TODO: not tested, could be broken
  3472. cur = llm_build_kqv(lctx, ctx0, Q,
  3473. model.layers[il].wo, model.layers[il].bo,
  3474. Q, KQ_scale, KQ_mask, n_tokens, n_kv, -1.0f, cb, il);
  3475. cb(cur, "kqv_out", il);
  3476. }
  3477. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  3478. cb(ffn_inp, "ffn_inp", il);
  3479. // feed-forward network
  3480. {
  3481. cur = llm_build_norm(ctx0, ffn_inp,
  3482. model.layers[il].ffn_norm,
  3483. model.layers[il].ffn_norm_b,
  3484. LLM_NORM, norm_eps, cb, il);
  3485. cb(cur, "ffn_norm", il);
  3486. cur = llm_build_ffn(ctx0, cur,
  3487. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  3488. NULL, NULL,
  3489. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  3490. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  3491. cb(cur, "ffn_out", il);
  3492. }
  3493. cur = ggml_add(ctx0, cur, ffn_inp);
  3494. cb(cur, "l_out", il);
  3495. inpL = cur;
  3496. }
  3497. cur = inpL;
  3498. cur = llm_build_norm(ctx0, cur,
  3499. model.output_norm,
  3500. model.output_norm_b,
  3501. LLM_NORM, norm_eps, cb, -1);
  3502. cb(cur, "result_norm", -1);
  3503. cur = ggml_mul_mat(ctx0, model.output, cur);
  3504. cb(cur, "result_output", -1);
  3505. ggml_build_forward_expand(gf, cur);
  3506. ggml_free(ctx0);
  3507. return gf;
  3508. }
  3509. static struct ggml_cgraph * llm_build_refact(
  3510. llama_context & lctx,
  3511. const llama_batch & batch,
  3512. const llm_build_cb & cb,
  3513. bool worst_case) {
  3514. const auto & model = lctx.model;
  3515. const auto & hparams = model.hparams;
  3516. const auto & cparams = lctx.cparams;
  3517. const auto & kv_self = lctx.kv_self;
  3518. GGML_ASSERT(!!kv_self.ctx);
  3519. const int64_t n_embd = hparams.n_embd;
  3520. const int64_t n_layer = hparams.n_layer;
  3521. const int64_t n_ctx = cparams.n_ctx;
  3522. const int64_t n_head = hparams.n_head;
  3523. const int64_t n_head_kv = hparams.n_head_kv;
  3524. const int64_t n_embd_head = hparams.n_embd_head();
  3525. const float norm_rms_eps = hparams.f_norm_rms_eps;
  3526. const int32_t n_tokens = batch.n_tokens;
  3527. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  3528. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  3529. auto & buf_compute = lctx.buf_compute;
  3530. struct ggml_init_params params = {
  3531. /*.mem_size =*/ buf_compute.size,
  3532. /*.mem_buffer =*/ buf_compute.data,
  3533. /*.no_alloc =*/ true,
  3534. };
  3535. struct ggml_context * ctx0 = ggml_init(params);
  3536. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3537. struct ggml_tensor * cur;
  3538. struct ggml_tensor * inpL;
  3539. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  3540. cb(inpL, "inp_embd", -1);
  3541. // KQ_scale
  3542. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3543. cb(KQ_scale, "KQ_scale", -1);
  3544. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3545. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3546. cb(KQ_mask, "KQ_mask", -1);
  3547. for (int il = 0; il < n_layer; ++il) {
  3548. struct ggml_tensor * inpSA = inpL;
  3549. cur = llm_build_norm(ctx0, inpL,
  3550. model.layers[il].attn_norm, NULL,
  3551. LLM_NORM_RMS, norm_rms_eps, cb, il);
  3552. cb(cur, "attn_norm", il);
  3553. // self-attention
  3554. {
  3555. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3556. cb(Qcur, "Qcur", il);
  3557. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3558. cb(Kcur, "Kcur", il);
  3559. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3560. cb(Vcur, "Vcur", il);
  3561. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  3562. cb(Kcur, "Kcur", il);
  3563. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3564. cb(Qcur, "Qcur", il);
  3565. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  3566. cur = llm_build_kqv(lctx, ctx0, Qcur,
  3567. model.layers[il].wo, NULL,
  3568. Qcur, KQ_scale, KQ_mask, n_tokens, n_kv, 8.0f, cb, il);
  3569. cb(cur, "kqv_out", il);
  3570. }
  3571. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3572. cb(ffn_inp, "ffn_inp", il);
  3573. // feed-forward network
  3574. {
  3575. cur = llm_build_norm(ctx0, ffn_inp,
  3576. model.layers[il].ffn_norm, NULL,
  3577. LLM_NORM_RMS, norm_rms_eps, cb, il);
  3578. cb(cur, "ffn_norm", il);
  3579. cur = llm_build_ffn(ctx0, cur,
  3580. model.layers[il].ffn_up, NULL,
  3581. model.layers[il].ffn_gate, NULL,
  3582. model.layers[il].ffn_down, NULL,
  3583. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3584. cb(cur, "ffn_out", il);
  3585. }
  3586. cur = ggml_add(ctx0, cur, ffn_inp);
  3587. cb(cur, "l_out", il);
  3588. // input for next layer
  3589. inpL = cur;
  3590. }
  3591. cur = inpL;
  3592. cur = llm_build_norm(ctx0, cur,
  3593. model.output_norm, NULL,
  3594. LLM_NORM_RMS, norm_rms_eps, cb, -1);
  3595. cb(cur, "result_norm", -1);
  3596. // lm_head
  3597. cur = ggml_mul_mat(ctx0, model.output, cur);
  3598. cb(cur, "result_output", -1);
  3599. ggml_build_forward_expand(gf, cur);
  3600. ggml_free(ctx0);
  3601. return gf;
  3602. }
  3603. static struct ggml_cgraph * llm_build_bloom(
  3604. llama_context & lctx,
  3605. const llama_batch & batch,
  3606. const llm_build_cb & cb,
  3607. bool worst_case) {
  3608. const auto & model = lctx.model;
  3609. const auto & hparams = model.hparams;
  3610. const auto & cparams = lctx.cparams;
  3611. const auto & kv_self = lctx.kv_self;
  3612. GGML_ASSERT(!!kv_self.ctx);
  3613. const int64_t n_embd = hparams.n_embd;
  3614. const int64_t n_layer = hparams.n_layer;
  3615. const int64_t n_ctx = cparams.n_ctx;
  3616. const int64_t n_head = hparams.n_head;
  3617. const int64_t n_embd_head = hparams.n_embd_head();
  3618. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3619. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3620. const float norm_eps = hparams.f_norm_eps;
  3621. const int32_t n_tokens = batch.n_tokens;
  3622. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  3623. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  3624. auto & buf_compute = lctx.buf_compute;
  3625. struct ggml_init_params params = {
  3626. /*.mem_size =*/ buf_compute.size,
  3627. /*.mem_buffer =*/ buf_compute.data,
  3628. /*.no_alloc =*/ false,
  3629. };
  3630. params.no_alloc = true;
  3631. struct ggml_context * ctx0 = ggml_init(params);
  3632. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3633. struct ggml_tensor * cur;
  3634. struct ggml_tensor * inpL;
  3635. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  3636. cb(inpL, "inp_embd", -1);
  3637. // KQ_scale
  3638. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3639. cb(KQ_scale, "KQ_scale", -1);
  3640. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3641. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3642. cb(KQ_mask, "KQ_mask", -1);
  3643. inpL = llm_build_norm(ctx0, inpL,
  3644. model.tok_norm,
  3645. model.tok_norm_b,
  3646. LLM_NORM, norm_eps, cb, -1);
  3647. cb(inpL, "inp_norm", -1);
  3648. for (int il = 0; il < n_layer; ++il) {
  3649. cur = llm_build_norm(ctx0, inpL,
  3650. model.layers[il].attn_norm,
  3651. model.layers[il].attn_norm_b,
  3652. LLM_NORM, norm_eps, cb, il);
  3653. cb(cur, "attn_norm", il);
  3654. // self-attention
  3655. {
  3656. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3657. cb(cur, "wqkv", il);
  3658. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3659. cb(cur, "bqkv", il);
  3660. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3661. 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)));
  3662. 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)));
  3663. cb(Qcur, "Qcur", il);
  3664. cb(Kcur, "Kcur", il);
  3665. cb(Vcur, "Vcur", il);
  3666. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3667. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  3668. cur = llm_build_kqv(lctx, ctx0, Qcur,
  3669. model.layers[il].wo, model.layers[il].bo,
  3670. Qcur, KQ_scale, KQ_mask, n_tokens, n_kv, 8.0f, cb, il);
  3671. cb(cur, "kqv_out", il);
  3672. }
  3673. // Add the input
  3674. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  3675. cb(ffn_inp, "ffn_inp", il);
  3676. // FF
  3677. {
  3678. cur = llm_build_norm(ctx0, ffn_inp,
  3679. model.layers[il].ffn_norm,
  3680. model.layers[il].ffn_norm_b,
  3681. LLM_NORM, norm_eps, cb, il);
  3682. cb(cur, "ffn_norm", il);
  3683. cur = llm_build_ffn(ctx0, cur,
  3684. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  3685. NULL, NULL,
  3686. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  3687. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3688. cb(cur, "ffn_out", il);
  3689. }
  3690. inpL = ggml_add(ctx0, cur, ffn_inp);
  3691. cb(inpL, "l_out", il);
  3692. }
  3693. cur = llm_build_norm(ctx0, inpL,
  3694. model.output_norm,
  3695. model.output_norm_b,
  3696. LLM_NORM, norm_eps, cb, -1);
  3697. cb(cur, "result_norm", -1);
  3698. cur = ggml_mul_mat(ctx0, model.output, cur);
  3699. cb(cur, "result_output", -1);
  3700. ggml_build_forward_expand(gf, cur);
  3701. ggml_free(ctx0);
  3702. return gf;
  3703. }
  3704. static struct ggml_cgraph * llm_build_mpt(
  3705. llama_context & lctx,
  3706. const llama_batch & batch,
  3707. const llm_build_cb & cb,
  3708. bool worst_case) {
  3709. const auto & model = lctx.model;
  3710. const auto & hparams = model.hparams;
  3711. const auto & cparams = lctx.cparams;
  3712. const auto & kv_self = lctx.kv_self;
  3713. GGML_ASSERT(!!kv_self.ctx);
  3714. const int64_t n_embd = hparams.n_embd;
  3715. const int64_t n_layer = hparams.n_layer;
  3716. const int64_t n_ctx = cparams.n_ctx;
  3717. const int64_t n_head = hparams.n_head;
  3718. const int64_t n_embd_head = hparams.n_embd_head();
  3719. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  3720. const float norm_eps = hparams.f_norm_eps;
  3721. const float clamp_kqv = hparams.f_clamp_kqv;
  3722. const float max_alibi_bias = hparams.f_max_alibi_bias;
  3723. const int32_t n_tokens = batch.n_tokens;
  3724. const int32_t n_kv = worst_case ? n_ctx : kv_self.n;
  3725. const int32_t kv_head = worst_case ? n_ctx - n_tokens : kv_self.head;
  3726. auto & buf_compute = lctx.buf_compute;
  3727. struct ggml_init_params params = {
  3728. /*.mem_size =*/ buf_compute.size,
  3729. /*.mem_buffer =*/ buf_compute.data,
  3730. /*.no_alloc =*/ false,
  3731. };
  3732. params.no_alloc = true;
  3733. struct ggml_context * ctx0 = ggml_init(params);
  3734. ggml_cgraph * gf = ggml_new_graph(ctx0);
  3735. struct ggml_tensor * cur;
  3736. struct ggml_tensor * inpL;
  3737. inpL = llm_build_inp_embd(ctx0, batch, model.tok_embd, n_embd, n_tokens, cb);
  3738. cb(inpL, "inp_embd", -1);
  3739. // KQ_scale
  3740. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  3741. cb(KQ_scale, "KQ_scale", -1);
  3742. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3743. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3744. cb(KQ_mask, "KQ_mask", -1);
  3745. for (int il = 0; il < n_layer; ++il) {
  3746. struct ggml_tensor * attn_norm;
  3747. attn_norm = llm_build_norm(ctx0, inpL,
  3748. model.layers[il].attn_norm,
  3749. NULL,
  3750. LLM_NORM, norm_eps, cb, il);
  3751. cb(attn_norm, "attn_norm", il);
  3752. // self-attention
  3753. {
  3754. cur = attn_norm;
  3755. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3756. cb(cur, "wqkv", il);
  3757. if (clamp_kqv > 0.0f) {
  3758. cur = ggml_clamp(ctx0, cur, -clamp_kqv, clamp_kqv);
  3759. cb(cur, "wqkv_clamped", il);
  3760. }
  3761. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3762. 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)));
  3763. 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)));
  3764. cb(Qcur, "Qcur", il);
  3765. cb(Kcur, "Kcur", il);
  3766. cb(Vcur, "Vcur", il);
  3767. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3768. llm_build_kv_store(lctx, ctx0, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  3769. cur = llm_build_kqv(lctx, ctx0, Qcur,
  3770. model.layers[il].wo, NULL,
  3771. Qcur, KQ_scale, KQ_mask, n_tokens, n_kv, max_alibi_bias, cb, il);
  3772. cb(cur, "kqv_out", il);
  3773. }
  3774. // Add the input
  3775. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  3776. cb(ffn_inp, "ffn_inp", il);
  3777. // feed forward
  3778. {
  3779. cur = llm_build_norm(ctx0, ffn_inp,
  3780. model.layers[il].ffn_norm,
  3781. NULL,
  3782. LLM_NORM, norm_eps, cb, il);
  3783. cb(cur, "ffn_norm", il);
  3784. cur = llm_build_ffn(ctx0, cur,
  3785. model.layers[il].ffn_up, NULL,
  3786. NULL, NULL,
  3787. model.layers[il].ffn_down, NULL,
  3788. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3789. cb(cur, "ffn_out", il);
  3790. }
  3791. cur = ggml_add(ctx0, cur, ffn_inp);
  3792. cb(cur, "l_out", il);
  3793. // input for next layer
  3794. inpL = cur;
  3795. }
  3796. cur = inpL;
  3797. cur = llm_build_norm(ctx0, cur,
  3798. model.output_norm,
  3799. NULL,
  3800. LLM_NORM, norm_eps, cb, -1);
  3801. cb(cur, "result_norm", -1);
  3802. cur = ggml_mul_mat(ctx0, model.output, cur);
  3803. cb(cur, "result_output", -1);
  3804. ggml_build_forward_expand(gf, cur);
  3805. ggml_free(ctx0);
  3806. return gf;
  3807. }
  3808. //
  3809. // tensor offloading helpers
  3810. //
  3811. // TODO: will be removed with backend v2
  3812. enum llm_offload_func_e {
  3813. OFFLOAD_FUNC_NOP,
  3814. OFFLOAD_FUNC,
  3815. OFFLOAD_FUNC_KQ,
  3816. OFFLOAD_FUNC_V,
  3817. OFFLOAD_FUNC_NR,
  3818. OFFLOAD_FUNC_EMB,
  3819. OFFLOAD_FUNC_OUT,
  3820. };
  3821. // TODO: will be removed with backend v2
  3822. struct llm_offload_trie {
  3823. struct node {
  3824. ~node() {
  3825. for (int i = 0; i < 256; ++i) {
  3826. if (children[i]) {
  3827. delete children[i];
  3828. }
  3829. }
  3830. }
  3831. node * children[256] = { nullptr };
  3832. llm_offload_func_e func = OFFLOAD_FUNC_NOP;
  3833. };
  3834. llm_offload_trie() {
  3835. root = new node;
  3836. }
  3837. llm_offload_trie(const std::unordered_map<const char *, llm_offload_func_e> & map) {
  3838. root = new node;
  3839. for (const auto & kv : map) {
  3840. add(kv.first, kv.second);
  3841. }
  3842. }
  3843. ~llm_offload_trie() {
  3844. delete root;
  3845. }
  3846. void add(const char * name, llm_offload_func_e func) {
  3847. node * cur = root;
  3848. for (int i = 0; ; ++i) {
  3849. const uint8_t c = name[i];
  3850. if (!c) {
  3851. break;
  3852. }
  3853. if (!cur->children[c]) {
  3854. cur->children[c] = new node;
  3855. }
  3856. cur = cur->children[c];
  3857. }
  3858. cur->func = func;
  3859. }
  3860. llm_offload_func_e find(const char * name) const {
  3861. const node * cur = root;
  3862. for (int i = 0; ; ++i) {
  3863. const uint8_t c = name[i];
  3864. if (!c) {
  3865. break;
  3866. }
  3867. if (!cur->children[c]) {
  3868. return OFFLOAD_FUNC_NOP;
  3869. }
  3870. cur = cur->children[c];
  3871. }
  3872. return cur->func;
  3873. }
  3874. node * root = nullptr;
  3875. };
  3876. // TODO: will be removed with backend v2
  3877. static const std::unordered_map<const char *, llm_offload_func_e> k_offload_map = {
  3878. //{ "inp_tokens", OFFLOAD_FUNC_NR }, // TODO: missing K-quants get_rows kernel
  3879. //{ "inp_embd", OFFLOAD_FUNC_NR }, // TODO: missing K-quants get_rows kernel
  3880. { "pos_embd", OFFLOAD_FUNC_NR },
  3881. { "inp_pos", OFFLOAD_FUNC_KQ }, // this is often used for KQ ops (e.g. rope)
  3882. { "KQ_scale", OFFLOAD_FUNC_KQ },
  3883. { "KQ_mask", OFFLOAD_FUNC_KQ },
  3884. { "K_shift", OFFLOAD_FUNC_KQ },
  3885. { "K_shifted", OFFLOAD_FUNC_KQ },
  3886. { "inp_norm", OFFLOAD_FUNC_NR },
  3887. { "inp_norm_w", OFFLOAD_FUNC_NR },
  3888. { "inp_norm_wb", OFFLOAD_FUNC_NR },
  3889. { "norm", OFFLOAD_FUNC },
  3890. { "norm_w", OFFLOAD_FUNC },
  3891. { "norm_wb", OFFLOAD_FUNC },
  3892. { "attn_norm", OFFLOAD_FUNC },
  3893. { "attn_norm_2", OFFLOAD_FUNC },
  3894. { "wqkv", OFFLOAD_FUNC_KQ },
  3895. { "bqkv", OFFLOAD_FUNC_KQ },
  3896. { "wqkv_clamped", OFFLOAD_FUNC_KQ },
  3897. { "tmpk", OFFLOAD_FUNC_KQ },
  3898. { "tmpq", OFFLOAD_FUNC_KQ },
  3899. { "tmpv", OFFLOAD_FUNC_V },
  3900. { "Kcur", OFFLOAD_FUNC_KQ },
  3901. { "Qcur", OFFLOAD_FUNC_KQ },
  3902. { "Vcur", OFFLOAD_FUNC_V },
  3903. { "krot", OFFLOAD_FUNC_KQ },
  3904. { "qrot", OFFLOAD_FUNC_KQ },
  3905. { "kpass", OFFLOAD_FUNC_KQ },
  3906. { "qpass", OFFLOAD_FUNC_KQ },
  3907. { "krotated", OFFLOAD_FUNC_KQ },
  3908. { "qrotated", OFFLOAD_FUNC_KQ },
  3909. { "q", OFFLOAD_FUNC_KQ },
  3910. { "k", OFFLOAD_FUNC_KQ },
  3911. { "kq", OFFLOAD_FUNC_KQ },
  3912. { "kq_scaled", OFFLOAD_FUNC_KQ },
  3913. { "kq_scaled_alibi", OFFLOAD_FUNC_KQ },
  3914. { "kq_masked", OFFLOAD_FUNC_KQ },
  3915. { "kq_soft_max", OFFLOAD_FUNC_V },
  3916. { "v", OFFLOAD_FUNC_V },
  3917. { "kqv", OFFLOAD_FUNC_V },
  3918. { "kqv_merged", OFFLOAD_FUNC_V },
  3919. { "kqv_merged_cont", OFFLOAD_FUNC_V },
  3920. { "kqv_wo", OFFLOAD_FUNC_V },
  3921. { "kqv_out", OFFLOAD_FUNC_V },
  3922. { "ffn_inp", OFFLOAD_FUNC },
  3923. { "ffn_norm", OFFLOAD_FUNC },
  3924. { "ffn_up", OFFLOAD_FUNC },
  3925. { "ffn_up_b", OFFLOAD_FUNC },
  3926. { "ffn_gate", OFFLOAD_FUNC },
  3927. { "ffn_gate_b", OFFLOAD_FUNC },
  3928. { "ffn_gate_par", OFFLOAD_FUNC },
  3929. { "ffn_down", OFFLOAD_FUNC },
  3930. { "ffn_down_b", OFFLOAD_FUNC },
  3931. { "ffn_out", OFFLOAD_FUNC },
  3932. { "ffn_silu", OFFLOAD_FUNC },
  3933. { "ffn_gelu", OFFLOAD_FUNC },
  3934. { "ffn_relu", OFFLOAD_FUNC },
  3935. { "ffn_sqr(relu)", OFFLOAD_FUNC },
  3936. { "l_out", OFFLOAD_FUNC },
  3937. { "result_norm", OFFLOAD_FUNC_EMB },
  3938. { "result_output", OFFLOAD_FUNC_OUT },
  3939. };
  3940. static llm_offload_trie k_offload_func_trie(k_offload_map);
  3941. static struct ggml_cgraph * llama_build_graph(
  3942. llama_context & lctx,
  3943. const llama_batch & batch) {
  3944. const auto & model = lctx.model;
  3945. // check if we should build the worst-case graph (for memory measurement)
  3946. const bool worst_case = ggml_allocr_is_measure(lctx.alloc);
  3947. // keep track of the input that has already been allocated
  3948. bool alloc_inp_tokens = false;
  3949. bool alloc_inp_embd = false;
  3950. bool alloc_inp_pos = false;
  3951. bool alloc_inp_KQ_scale = false;
  3952. bool alloc_inp_KQ_mask = false;
  3953. bool alloc_inp_K_shift = false;
  3954. #ifdef GGML_USE_CUBLAS
  3955. const bool do_offload = true;
  3956. #else
  3957. const bool do_offload = true; // TODO: set to false after finishing refactoring
  3958. #endif
  3959. int n_non_view = 0; // number of non-view tensors that have been processed by the callback
  3960. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  3961. // TODO: will be removed with backend v2
  3962. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  3963. if (il >= 0) {
  3964. ggml_format_name(cur, "%s-%d", name, il);
  3965. } else {
  3966. ggml_set_name(cur, name);
  3967. }
  3968. //
  3969. // allocate input tensors and set input data
  3970. //
  3971. // TODO: will be removed with backend v2
  3972. if (!alloc_inp_tokens && strcmp(name, "inp_tokens") == 0) {
  3973. ggml_allocr_alloc(lctx.alloc, cur);
  3974. if (!ggml_allocr_is_measure(lctx.alloc) && batch.token) {
  3975. const int64_t n_tokens = cur->ne[0];
  3976. memcpy(cur->data, batch.token, n_tokens*ggml_element_size(cur));
  3977. }
  3978. alloc_inp_tokens = true;
  3979. }
  3980. if (!alloc_inp_embd && strcmp(name, "inp_embd") == 0) {
  3981. ggml_allocr_alloc(lctx.alloc, cur);
  3982. if (!ggml_allocr_is_measure(lctx.alloc) && batch.embd) {
  3983. const int64_t n_embd = cur->ne[0];
  3984. const int64_t n_tokens = cur->ne[1];
  3985. memcpy(cur->data, batch.embd, n_tokens*n_embd*ggml_element_size(cur));
  3986. }
  3987. alloc_inp_embd = true;
  3988. }
  3989. if (!alloc_inp_pos && strcmp(name, "inp_pos") == 0) {
  3990. ggml_allocr_alloc(lctx.alloc, cur);
  3991. if (!ggml_allocr_is_measure(lctx.alloc) && batch.pos) {
  3992. const int64_t n_tokens = cur->ne[0];
  3993. int32_t * data = (int32_t *) cur->data;
  3994. for (int i = 0; i < n_tokens; ++i) {
  3995. data[i] = batch.pos[i];
  3996. }
  3997. }
  3998. alloc_inp_pos = true;
  3999. }
  4000. if (!alloc_inp_KQ_scale && strcmp(name, "KQ_scale") == 0) {
  4001. ggml_allocr_alloc(lctx.alloc, cur);
  4002. if (!ggml_allocr_is_measure(lctx.alloc)) {
  4003. const int64_t n_embd_head = model.hparams.n_embd_head();
  4004. ggml_set_f32(cur, 1.0f/sqrtf(float(n_embd_head)));
  4005. }
  4006. alloc_inp_KQ_scale = true;
  4007. }
  4008. if (!alloc_inp_KQ_mask && strcmp(name, "KQ_mask") == 0) {
  4009. ggml_allocr_alloc(lctx.alloc, cur);
  4010. if (!ggml_allocr_is_measure(lctx.alloc)) {
  4011. const int64_t n_kv = cur->ne[0];
  4012. const int64_t n_tokens = cur->ne[1];
  4013. float * data = (float *) cur->data;
  4014. memset(data, 0, ggml_nbytes(cur));
  4015. for (int h = 0; h < 1; ++h) {
  4016. for (int j = 0; j < n_tokens; ++j) {
  4017. const llama_pos pos = batch.pos[j];
  4018. const llama_seq_id seq_id = batch.seq_id[j][0];
  4019. for (int i = 0; i < n_kv; ++i) {
  4020. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  4021. data[h*(n_kv*n_tokens) + j*n_kv + i] = -INFINITY;
  4022. }
  4023. }
  4024. }
  4025. }
  4026. }
  4027. alloc_inp_KQ_mask = true;
  4028. }
  4029. if (!alloc_inp_K_shift && strcmp(name, "K_shift") == 0) {
  4030. ggml_allocr_alloc(lctx.alloc, cur);
  4031. if (!ggml_allocr_is_measure(lctx.alloc)) {
  4032. const int64_t n_ctx = cur->ne[0];
  4033. int32_t * data = (int32_t *) cur->data;
  4034. for (int i = 0; i < n_ctx; ++i) {
  4035. data[i] = lctx.kv_self.cells[i].delta;
  4036. }
  4037. }
  4038. alloc_inp_K_shift = true;
  4039. }
  4040. // view tensors are not processed further
  4041. if (cur->view_src != nullptr) {
  4042. return;
  4043. }
  4044. if (cur->op != GGML_OP_NONE) {
  4045. n_non_view++;
  4046. }
  4047. //
  4048. // offload layers
  4049. //
  4050. // TODO: will be removed with backend v2
  4051. //#define LLAMA_OFFLOAD_DEBUG
  4052. if (!do_offload) {
  4053. return;
  4054. }
  4055. const int n_layer = model.hparams.n_layer;
  4056. const int n_gpu_layers = model.n_gpu_layers;
  4057. const int i_gpu_start = n_layer - n_gpu_layers;
  4058. // should we offload the final norm? yes if we are not computing embeddings
  4059. const bool offload_emb = lctx.embedding.empty();
  4060. static const std::unordered_map<llm_offload_func_e, std::string, std::hash<int>> k_offload_func_name = {
  4061. { OFFLOAD_FUNC_NOP, "CPU" },
  4062. { OFFLOAD_FUNC_OUT, "CPU" },
  4063. #ifdef GGML_USE_CUBLAS
  4064. { OFFLOAD_FUNC, "GPU (CUDA)" },
  4065. { OFFLOAD_FUNC_KQ, "GPU (CUDA) KQ" },
  4066. { OFFLOAD_FUNC_V, "GPU (CUDA) V" },
  4067. { OFFLOAD_FUNC_NR, "GPU (CUDA) NR" },
  4068. { OFFLOAD_FUNC_EMB, "GPU (CUDA) EMB" },
  4069. #else
  4070. { OFFLOAD_FUNC, "CPU" },
  4071. { OFFLOAD_FUNC_KQ, "CPU" },
  4072. { OFFLOAD_FUNC_V, "CPU" },
  4073. { OFFLOAD_FUNC_NR, "CPU" },
  4074. { OFFLOAD_FUNC_EMB, "CPU" },
  4075. #endif // GGML_USE_CUBLAS
  4076. };
  4077. // check the global map for what offload function to use for this tensor
  4078. llm_offload_func_e func_e = k_offload_func_trie.find(name);
  4079. if (func_e == OFFLOAD_FUNC_NOP) {
  4080. #ifdef LLAMA_OFFLOAD_DEBUG
  4081. // if a tensor hasn't been offloaded, we warn the user
  4082. if (worst_case) {
  4083. LLAMA_LOG_WARN("%s: %32s: not offloaded (ref: %s)\n", __func__,
  4084. cur->name, "https://github.com/ggerganov/llama.cpp/pull/3837");
  4085. }
  4086. #endif
  4087. return;
  4088. }
  4089. // count the number of layers and respect the provided n_gpu_layers
  4090. switch (func_e) {
  4091. case OFFLOAD_FUNC_NOP:
  4092. case OFFLOAD_FUNC_OUT:
  4093. break;
  4094. case OFFLOAD_FUNC:
  4095. if (n_gpu_layers < n_layer) {
  4096. if (il < i_gpu_start) {
  4097. func_e = OFFLOAD_FUNC_NOP;
  4098. }
  4099. }
  4100. break;
  4101. case OFFLOAD_FUNC_NR:
  4102. if (n_gpu_layers <= n_layer + 0) {
  4103. func_e = OFFLOAD_FUNC_NOP;
  4104. }
  4105. break;
  4106. case OFFLOAD_FUNC_V:
  4107. if (n_gpu_layers <= n_layer + 1) {
  4108. func_e = OFFLOAD_FUNC_NOP;
  4109. }
  4110. break;
  4111. case OFFLOAD_FUNC_KQ:
  4112. if (n_gpu_layers <= n_layer + 2) {
  4113. func_e = OFFLOAD_FUNC_NOP;
  4114. }
  4115. break;
  4116. case OFFLOAD_FUNC_EMB:
  4117. if (!offload_emb || n_gpu_layers < n_layer) {
  4118. func_e = OFFLOAD_FUNC_NOP;
  4119. }
  4120. break;
  4121. default: GGML_ASSERT(false);
  4122. }
  4123. offload_func_t func = ggml_offload_nop;
  4124. // this is needed for compatibility with Metal for example
  4125. #ifdef GGML_USE_CUBLAS
  4126. static offload_func_t ggml_offload_gpu = ggml_cuda_assign_buffers_no_alloc;
  4127. #else
  4128. static offload_func_t ggml_offload_gpu = ggml_offload_nop;
  4129. #endif
  4130. switch (func_e) {
  4131. case OFFLOAD_FUNC_NOP:
  4132. case OFFLOAD_FUNC_OUT: func = ggml_offload_nop; break;
  4133. case OFFLOAD_FUNC:
  4134. case OFFLOAD_FUNC_KQ:
  4135. case OFFLOAD_FUNC_V:
  4136. case OFFLOAD_FUNC_NR:
  4137. case OFFLOAD_FUNC_EMB: func = ggml_offload_gpu; break;
  4138. default: GGML_ASSERT(false);
  4139. }
  4140. // apply offload function to the tensor
  4141. func(cur);
  4142. #ifdef LLAMA_OFFLOAD_DEBUG
  4143. if (worst_case) {
  4144. LLAMA_LOG_INFO("%s: %32s: %s\n", __func__, cur->name, k_offload_func_name.at(func_e).c_str());
  4145. }
  4146. #endif
  4147. };
  4148. struct ggml_cgraph * result = NULL;
  4149. switch (model.arch) {
  4150. case LLM_ARCH_LLAMA:
  4151. {
  4152. result = llm_build_llama(lctx, batch, cb, worst_case);
  4153. } break;
  4154. case LLM_ARCH_BAICHUAN:
  4155. {
  4156. result = llm_build_baichaun(lctx, batch, cb, worst_case);
  4157. } break;
  4158. case LLM_ARCH_FALCON:
  4159. {
  4160. result = llm_build_falcon(lctx, batch, cb, worst_case);
  4161. } break;
  4162. case LLM_ARCH_STARCODER:
  4163. {
  4164. result = llm_build_starcoder(lctx, batch, cb, worst_case);
  4165. } break;
  4166. case LLM_ARCH_PERSIMMON:
  4167. {
  4168. result = llm_build_persimmon(lctx, batch, cb, worst_case);
  4169. } break;
  4170. case LLM_ARCH_REFACT:
  4171. {
  4172. result = llm_build_refact(lctx, batch, cb, worst_case);
  4173. } break;
  4174. case LLM_ARCH_BLOOM:
  4175. {
  4176. result = llm_build_bloom(lctx, batch, cb, worst_case);
  4177. } break;
  4178. case LLM_ARCH_MPT:
  4179. {
  4180. result = llm_build_mpt(lctx, batch, cb, worst_case);
  4181. } break;
  4182. default:
  4183. GGML_ASSERT(false);
  4184. }
  4185. if (worst_case) {
  4186. int n_non_view_total = 0;
  4187. for (int i = 0; i < result->n_nodes; ++i) {
  4188. if (result->nodes[i]->view_src == nullptr) {
  4189. n_non_view_total++;
  4190. }
  4191. }
  4192. LLAMA_LOG_INFO("%s: non-view tensors processed: %d/%d\n", __func__, n_non_view, n_non_view_total);
  4193. if (n_non_view != n_non_view_total) {
  4194. LLAMA_LOG_WARN("%s: ****************************************************************\n", __func__);
  4195. LLAMA_LOG_WARN("%s: not all non-view tensors have been processed with a callback\n", __func__);
  4196. LLAMA_LOG_WARN("%s: this can indicate an inefficiency in the graph implementation\n", __func__);
  4197. LLAMA_LOG_WARN("%s: build with LLAMA_OFFLOAD_DEBUG for more info\n", __func__);
  4198. LLAMA_LOG_WARN("%s: ref: https://github.com/ggerganov/llama.cpp/pull/3837\n", __func__);
  4199. LLAMA_LOG_WARN("%s: ****************************************************************\n", __func__);
  4200. }
  4201. }
  4202. return result;
  4203. }
  4204. // decode a batch of tokens by evaluating the transformer
  4205. //
  4206. // - lctx: llama context
  4207. // - batch: batch to evaluate
  4208. //
  4209. // return 0 on success
  4210. // return positive int on warning
  4211. // return negative int on error
  4212. //
  4213. static int llama_decode_internal(
  4214. llama_context & lctx,
  4215. llama_batch batch) {
  4216. const uint32_t n_tokens = batch.n_tokens;
  4217. if (n_tokens == 0) {
  4218. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  4219. return -1;
  4220. }
  4221. const auto & model = lctx.model;
  4222. const auto & hparams = model.hparams;
  4223. const auto & cparams = lctx.cparams;
  4224. const auto n_batch = cparams.n_batch;
  4225. GGML_ASSERT(n_tokens <= n_batch);
  4226. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  4227. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  4228. const int64_t t_start_us = ggml_time_us();
  4229. #ifdef GGML_USE_MPI
  4230. // TODO: needs fix after #3228
  4231. GGML_ASSERT(false && "not implemented");
  4232. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  4233. #endif
  4234. GGML_ASSERT(n_threads > 0);
  4235. auto & kv_self = lctx.kv_self;
  4236. GGML_ASSERT(!!kv_self.ctx);
  4237. const int64_t n_embd = hparams.n_embd;
  4238. const int64_t n_vocab = hparams.n_vocab;
  4239. // helpers for smoother batch API transistion
  4240. // after deprecating the llama_eval calls, these will be removed
  4241. std::vector<llama_pos> pos;
  4242. std::vector<int32_t> n_seq_id;
  4243. std::vector<llama_seq_id *> seq_id_arr;
  4244. std::vector<std::vector<llama_seq_id>> seq_id;
  4245. if (batch.pos == nullptr) {
  4246. pos.resize(n_tokens);
  4247. for (uint32_t i = 0; i < n_tokens; i++) {
  4248. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  4249. }
  4250. batch.pos = pos.data();
  4251. }
  4252. if (batch.seq_id == nullptr) {
  4253. n_seq_id.resize(n_tokens);
  4254. seq_id.resize(n_tokens);
  4255. seq_id_arr.resize(n_tokens);
  4256. for (uint32_t i = 0; i < n_tokens; i++) {
  4257. n_seq_id[i] = 1;
  4258. seq_id[i].resize(1);
  4259. seq_id[i][0] = batch.all_seq_id;
  4260. seq_id_arr[i] = seq_id[i].data();
  4261. }
  4262. batch.n_seq_id = n_seq_id.data();
  4263. batch.seq_id = seq_id_arr.data();
  4264. }
  4265. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  4266. return 1;
  4267. }
  4268. // a heuristic, to avoid attending the full cache if it is not yet utilized
  4269. // after enough generations, the benefit from this heuristic disappears
  4270. // if we start defragmenting the cache, the benefit from this will be more important
  4271. //kv_self.n = std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)); // TODO: this might be better for CUDA?
  4272. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, llama_kv_cache_cell_max(kv_self)));
  4273. //printf("kv_self.n = %d\n", kv_self.n);
  4274. ggml_allocr_reset(lctx.alloc);
  4275. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  4276. ggml_allocr_alloc_graph(lctx.alloc, gf);
  4277. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  4278. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  4279. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  4280. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  4281. #ifdef GGML_USE_CUBLAS
  4282. for (int i = 0; i < gf->n_leafs; i++) {
  4283. ggml_tensor * node = gf->leafs[i];
  4284. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  4285. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  4286. ggml_cuda_copy_to_device(node);
  4287. }
  4288. }
  4289. for (int i = 0; i < gf->n_nodes; i++) {
  4290. ggml_tensor * node = gf->nodes[i];
  4291. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  4292. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  4293. }
  4294. }
  4295. // HACK: ggml-alloc may change the tensor backend when reusing a parent, so force output to be on the CPU here if needed
  4296. if (!lctx.embedding.empty()) {
  4297. embeddings->backend = GGML_BACKEND_CPU;
  4298. }
  4299. res->backend = GGML_BACKEND_CPU;
  4300. #endif
  4301. // 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);
  4302. // for big prompts, if BLAS is enabled, it is better to use only one thread
  4303. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  4304. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  4305. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  4306. // with the BLAS calls. need a better solution
  4307. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  4308. n_threads = std::min(4, n_threads);
  4309. }
  4310. // If all tensors can be run on the GPU then using more than 1 thread is detrimental.
  4311. const bool full_offload_supported =
  4312. model.arch == LLM_ARCH_LLAMA ||
  4313. model.arch == LLM_ARCH_BAICHUAN ||
  4314. model.arch == LLM_ARCH_FALCON ||
  4315. model.arch == LLM_ARCH_REFACT ||
  4316. model.arch == LLM_ARCH_MPT;
  4317. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 3;
  4318. if (ggml_cpu_has_cublas() && full_offload_supported && fully_offloaded) {
  4319. n_threads = 1;
  4320. }
  4321. #if GGML_USE_MPI
  4322. const int64_t n_layer = hparams.n_layer;
  4323. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  4324. #endif
  4325. #ifdef GGML_USE_METAL
  4326. if (lctx.ctx_metal) {
  4327. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  4328. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  4329. } else {
  4330. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  4331. }
  4332. #else
  4333. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  4334. #endif
  4335. #if GGML_USE_MPI
  4336. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  4337. #endif
  4338. // update the kv ring buffer
  4339. {
  4340. if (kv_self.has_shift) {
  4341. kv_self.has_shift = false;
  4342. for (uint32_t i = 0; i < kv_self.size; ++i) {
  4343. kv_self.cells[i].delta = 0;
  4344. }
  4345. }
  4346. kv_self.head += n_tokens;
  4347. // Ensure kv cache head points to a valid index.
  4348. if (kv_self.head >= kv_self.size) {
  4349. kv_self.head = 0;
  4350. }
  4351. }
  4352. #ifdef GGML_PERF
  4353. // print timing information per ggml operation (for debugging purposes)
  4354. // requires GGML_PERF to be defined
  4355. ggml_graph_print(gf);
  4356. #endif
  4357. // plot the computation graph in dot format (for debugging purposes)
  4358. //if (n_past%100 == 0) {
  4359. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  4360. //}
  4361. // extract logits
  4362. // TODO: do not compute and extract logits if only embeddings are needed
  4363. // need to update the graphs to skip "result_output"
  4364. {
  4365. auto & logits_out = lctx.logits;
  4366. if (batch.logits) {
  4367. logits_out.resize(n_vocab * n_tokens);
  4368. for (uint32_t i = 0; i < n_tokens; i++) {
  4369. if (batch.logits[i] == 0) {
  4370. continue;
  4371. }
  4372. memcpy(logits_out.data() + (n_vocab*i), (float *) ggml_get_data(res) + (n_vocab*i), sizeof(float)*n_vocab);
  4373. }
  4374. } else if (lctx.logits_all) {
  4375. logits_out.resize(n_vocab * n_tokens);
  4376. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*n_tokens);
  4377. } else {
  4378. logits_out.resize(n_vocab);
  4379. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(n_tokens - 1)), sizeof(float)*n_vocab);
  4380. }
  4381. }
  4382. // extract embeddings
  4383. if (!lctx.embedding.empty()) {
  4384. auto & embedding_out = lctx.embedding;
  4385. embedding_out.resize(n_embd);
  4386. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(n_tokens - 1)), sizeof(float)*n_embd);
  4387. }
  4388. // measure the performance only for the single-token evals
  4389. if (n_tokens == 1) {
  4390. lctx.t_eval_us += ggml_time_us() - t_start_us;
  4391. lctx.n_eval++;
  4392. }
  4393. else if (n_tokens > 1) {
  4394. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  4395. lctx.n_p_eval += n_tokens;
  4396. }
  4397. // get a more accurate load time, upon first eval
  4398. // TODO: fix this
  4399. if (!lctx.has_evaluated_once) {
  4400. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  4401. lctx.has_evaluated_once = true;
  4402. }
  4403. return 0;
  4404. }
  4405. //
  4406. // tokenizer
  4407. //
  4408. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  4409. return vocab.type;
  4410. }
  4411. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  4412. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  4413. }
  4414. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  4415. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  4416. }
  4417. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  4418. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  4419. }
  4420. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  4421. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  4422. }
  4423. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  4424. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  4425. }
  4426. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  4427. GGML_ASSERT(llama_is_byte_token(vocab, id));
  4428. const auto& token_data = vocab.id_to_token.at(id);
  4429. switch (llama_vocab_get_type(vocab)) {
  4430. case LLAMA_VOCAB_TYPE_SPM: {
  4431. auto buf = token_data.text.substr(3, 2);
  4432. return strtol(buf.c_str(), NULL, 16);
  4433. }
  4434. case LLAMA_VOCAB_TYPE_BPE: {
  4435. GGML_ASSERT(false);
  4436. return unicode_to_bytes_bpe(token_data.text);
  4437. }
  4438. default:
  4439. GGML_ASSERT(false);
  4440. }
  4441. }
  4442. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  4443. static const char * hex = "0123456789ABCDEF";
  4444. switch (llama_vocab_get_type(vocab)) {
  4445. case LLAMA_VOCAB_TYPE_SPM: {
  4446. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  4447. return vocab.token_to_id.at(buf);
  4448. }
  4449. case LLAMA_VOCAB_TYPE_BPE: {
  4450. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  4451. }
  4452. default:
  4453. GGML_ASSERT(false);
  4454. }
  4455. }
  4456. static void llama_escape_whitespace(std::string & text) {
  4457. replace_all(text, " ", "\xe2\x96\x81");
  4458. }
  4459. static void llama_unescape_whitespace(std::string & word) {
  4460. replace_all(word, "\xe2\x96\x81", " ");
  4461. }
  4462. struct llm_symbol {
  4463. using index = int;
  4464. index prev;
  4465. index next;
  4466. const char * text;
  4467. size_t n;
  4468. };
  4469. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  4470. // SPM tokenizer
  4471. // original implementation:
  4472. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  4473. struct llm_bigram_spm {
  4474. struct comparator {
  4475. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  4476. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  4477. }
  4478. };
  4479. using queue_storage = std::vector<llm_bigram_spm>;
  4480. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  4481. llm_symbol::index left;
  4482. llm_symbol::index right;
  4483. float score;
  4484. size_t size;
  4485. };
  4486. struct llm_tokenizer_spm {
  4487. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  4488. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  4489. // split string into utf8 chars
  4490. int index = 0;
  4491. size_t offs = 0;
  4492. while (offs < text.size()) {
  4493. llm_symbol sym;
  4494. size_t len = utf8_len(text[offs]);
  4495. sym.text = text.c_str() + offs;
  4496. sym.n = std::min(len, text.size() - offs);
  4497. offs += sym.n;
  4498. sym.prev = index - 1;
  4499. sym.next = offs == text.size() ? -1 : index + 1;
  4500. index++;
  4501. symbols.emplace_back(sym);
  4502. }
  4503. // seed the work queue with all possible 2-character tokens.
  4504. for (size_t i = 1; i < symbols.size(); ++i) {
  4505. try_add_bigram(i - 1, i);
  4506. }
  4507. // keep substituting the highest frequency pairs for as long as we can.
  4508. while (!work_queue.empty()) {
  4509. auto bigram = work_queue.top();
  4510. work_queue.pop();
  4511. auto & left_sym = symbols[bigram.left];
  4512. auto & right_sym = symbols[bigram.right];
  4513. // if one of the symbols already got merged, skip it.
  4514. if (left_sym.n == 0 || right_sym.n == 0 ||
  4515. left_sym.n + right_sym.n != bigram.size) {
  4516. continue;
  4517. }
  4518. // merge the right sym into the left one
  4519. left_sym.n += right_sym.n;
  4520. right_sym.n = 0;
  4521. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  4522. // remove the right sym from the chain
  4523. left_sym.next = right_sym.next;
  4524. if (right_sym.next >= 0) {
  4525. symbols[right_sym.next].prev = bigram.left;
  4526. }
  4527. // find more substitutions
  4528. try_add_bigram(left_sym.prev, bigram.left);
  4529. try_add_bigram(bigram.left, left_sym.next);
  4530. }
  4531. for (int i = 0; i != -1; i = symbols[i].next) {
  4532. auto & symbol = symbols[i];
  4533. resegment(symbol, output);
  4534. }
  4535. }
  4536. private:
  4537. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  4538. auto text = std::string(symbol.text, symbol.n);
  4539. auto token = vocab.token_to_id.find(text);
  4540. // Do we need to support is_unused?
  4541. if (token != vocab.token_to_id.end()) {
  4542. output.push_back((*token).second);
  4543. return;
  4544. }
  4545. const auto p = rev_merge.find(text);
  4546. if (p == rev_merge.end()) {
  4547. // output any symbols that did not form tokens as bytes.
  4548. for (int j = 0; j < (int)symbol.n; ++j) {
  4549. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  4550. output.push_back(token_id);
  4551. }
  4552. return;
  4553. }
  4554. resegment(symbols[p->second.first], output);
  4555. resegment(symbols[p->second.second], output);
  4556. }
  4557. void try_add_bigram(int left, int right) {
  4558. if (left == -1 || right == -1) {
  4559. return;
  4560. }
  4561. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  4562. auto token = vocab.token_to_id.find(text);
  4563. if (token == vocab.token_to_id.end()) {
  4564. return;
  4565. }
  4566. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  4567. return;
  4568. }
  4569. const auto & tok_data = vocab.id_to_token[(*token).second];
  4570. llm_bigram_spm bigram;
  4571. bigram.left = left;
  4572. bigram.right = right;
  4573. bigram.score = tok_data.score;
  4574. bigram.size = text.size();
  4575. work_queue.push(bigram);
  4576. // Do we need to support is_unused?
  4577. rev_merge[text] = std::make_pair(left, right);
  4578. }
  4579. const llama_vocab & vocab;
  4580. std::vector<llm_symbol> symbols;
  4581. llm_bigram_spm::queue work_queue;
  4582. std::map<std::string, std::pair<int, int>> rev_merge;
  4583. };
  4584. // BPE tokenizer
  4585. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  4586. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  4587. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  4588. struct llm_bigram_bpe {
  4589. struct comparator {
  4590. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  4591. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  4592. }
  4593. };
  4594. using queue_storage = std::vector<llm_bigram_bpe>;
  4595. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  4596. llm_symbol::index left;
  4597. llm_symbol::index right;
  4598. std::string text;
  4599. int rank;
  4600. size_t size;
  4601. };
  4602. struct llm_tokenizer_bpe {
  4603. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  4604. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  4605. int final_prev_index = -1;
  4606. auto word_collection = bpe_gpt2_preprocess(text);
  4607. symbols_final.clear();
  4608. for (auto & word : word_collection) {
  4609. work_queue = llm_bigram_bpe::queue();
  4610. symbols.clear();
  4611. int index = 0;
  4612. size_t offset = 0;
  4613. while (offset < word.size()) {
  4614. llm_symbol sym;
  4615. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  4616. sym.text = word.c_str() + offset;
  4617. sym.n = char_len;
  4618. offset += sym.n;
  4619. sym.prev = index - 1;
  4620. sym.next = offset == word.size() ? -1 : index + 1;
  4621. index++;
  4622. symbols.emplace_back(sym);
  4623. }
  4624. for (size_t i = 1; i < symbols.size(); ++i) {
  4625. add_new_bigram(i - 1, i);
  4626. }
  4627. // build token(s)
  4628. while (!work_queue.empty()) {
  4629. auto bigram = work_queue.top();
  4630. work_queue.pop();
  4631. auto & left_symbol = symbols[bigram.left];
  4632. auto & right_symbol = symbols[bigram.right];
  4633. if (left_symbol.n == 0 || right_symbol.n == 0) {
  4634. continue;
  4635. }
  4636. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  4637. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  4638. if (left_token + right_token != bigram.text) {
  4639. continue; // Skip this bigram if it's outdated
  4640. }
  4641. // merge the right sym into the left one
  4642. left_symbol.n += right_symbol.n;
  4643. right_symbol.n = 0;
  4644. // remove the right sym from the chain
  4645. left_symbol.next = right_symbol.next;
  4646. if (right_symbol.next >= 0) {
  4647. symbols[right_symbol.next].prev = bigram.left;
  4648. }
  4649. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  4650. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  4651. }
  4652. // add the fnished tokens to the final list keeping correct order for next and prev
  4653. for (auto & sym : symbols) {
  4654. if (sym.n > 0) {
  4655. sym.prev = final_prev_index;
  4656. sym.next = -1;
  4657. if (final_prev_index != -1) {
  4658. symbols_final[final_prev_index].next = symbols_final.size();
  4659. }
  4660. symbols_final.emplace_back(sym);
  4661. final_prev_index = symbols_final.size() - 1;
  4662. }
  4663. }
  4664. }
  4665. symbols = symbols_final;
  4666. if (!symbols.empty()) {
  4667. for (int i = 0; i != -1; i = symbols[i].next) {
  4668. auto & symbol = symbols[i];
  4669. if (symbol.n == 0) {
  4670. continue;
  4671. }
  4672. const std::string str = std::string(symbol.text, symbol.n);
  4673. const auto token = vocab.token_to_id.find(str);
  4674. if (token == vocab.token_to_id.end()) {
  4675. for (auto j = str.begin(); j != str.end(); ++j) {
  4676. std::string byte_str(1, *j);
  4677. auto token_multibyte = vocab.token_to_id.find(byte_str);
  4678. if (token_multibyte == vocab.token_to_id.end()) {
  4679. throw std::runtime_error("ERROR: byte not found in vocab");
  4680. }
  4681. output.push_back((*token_multibyte).second);
  4682. }
  4683. } else {
  4684. output.push_back((*token).second);
  4685. }
  4686. }
  4687. }
  4688. }
  4689. private:
  4690. void add_new_bigram(int left, int right) {
  4691. if (left == -1 || right == -1) {
  4692. return;
  4693. }
  4694. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  4695. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  4696. int rank_found = -1;
  4697. rank_found = vocab.find_bpe_rank(left_token, right_token);
  4698. if (rank_found < 0) {
  4699. return;
  4700. }
  4701. llm_bigram_bpe bigram;
  4702. bigram.left = left;
  4703. bigram.right = right;
  4704. bigram.text = left_token + right_token;
  4705. bigram.size = left_token.size() + right_token.size();
  4706. bigram.rank = rank_found;
  4707. work_queue.push(bigram);
  4708. }
  4709. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  4710. std::vector<std::string> bpe_words;
  4711. std::vector<std::string> bpe_encoded_words;
  4712. std::string token = "";
  4713. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  4714. bool collecting_numeric = false;
  4715. bool collecting_letter = false;
  4716. bool collecting_special = false;
  4717. bool collecting_whitespace_lookahead = false;
  4718. bool collecting = false;
  4719. std::vector<std::string> text_utf;
  4720. text_utf.reserve(text.size());
  4721. bpe_words.reserve(text.size());
  4722. bpe_encoded_words.reserve(text.size());
  4723. auto cps = codepoints_from_utf8(text);
  4724. for (size_t i = 0; i < cps.size(); ++i)
  4725. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  4726. for (int i = 0; i < (int)text_utf.size(); i++) {
  4727. const std::string & utf_char = text_utf[i];
  4728. bool split_condition = false;
  4729. int bytes_remain = text_utf.size() - i;
  4730. // forward backward lookups
  4731. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  4732. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  4733. // handling contractions
  4734. if (!split_condition && bytes_remain >= 2) {
  4735. // 's|'t|'m|'d
  4736. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  4737. split_condition = true;
  4738. }
  4739. if (split_condition) {
  4740. if (token.size()) {
  4741. bpe_words.emplace_back(token); // push previous content as token
  4742. }
  4743. token = utf_char + utf_char_next;
  4744. bpe_words.emplace_back(token);
  4745. token = "";
  4746. i++;
  4747. continue;
  4748. }
  4749. }
  4750. if (!split_condition && bytes_remain >= 3) {
  4751. // 're|'ve|'ll
  4752. if (utf_char == "\'" && (
  4753. (utf_char_next == "r" && utf_char_next_next == "e") ||
  4754. (utf_char_next == "v" && utf_char_next_next == "e") ||
  4755. (utf_char_next == "l" && utf_char_next_next == "l"))
  4756. ) {
  4757. split_condition = true;
  4758. }
  4759. if (split_condition) {
  4760. // current token + next token can be defined
  4761. if (token.size()) {
  4762. bpe_words.emplace_back(token); // push previous content as token
  4763. }
  4764. token = utf_char + utf_char_next + utf_char_next_next;
  4765. bpe_words.emplace_back(token); // the contraction
  4766. token = "";
  4767. i += 2;
  4768. continue;
  4769. }
  4770. }
  4771. if (!split_condition && !collecting) {
  4772. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  4773. collecting_letter = true;
  4774. collecting = true;
  4775. }
  4776. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  4777. collecting_numeric = true;
  4778. collecting = true;
  4779. }
  4780. else if (
  4781. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  4782. (!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)
  4783. ) {
  4784. collecting_special = true;
  4785. collecting = true;
  4786. }
  4787. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  4788. collecting_whitespace_lookahead = true;
  4789. collecting = true;
  4790. }
  4791. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  4792. split_condition = true;
  4793. }
  4794. }
  4795. else if (!split_condition && collecting) {
  4796. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  4797. split_condition = true;
  4798. }
  4799. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  4800. split_condition = true;
  4801. }
  4802. 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)) {
  4803. split_condition = true;
  4804. }
  4805. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  4806. split_condition = true;
  4807. }
  4808. }
  4809. if (utf_char_next == "") {
  4810. split_condition = true; // final
  4811. token += utf_char;
  4812. }
  4813. if (split_condition) {
  4814. if (token.size()) {
  4815. bpe_words.emplace_back(token);
  4816. }
  4817. token = utf_char;
  4818. collecting = false;
  4819. collecting_letter = false;
  4820. collecting_numeric = false;
  4821. collecting_special = false;
  4822. collecting_whitespace_lookahead = false;
  4823. }
  4824. else {
  4825. token += utf_char;
  4826. }
  4827. }
  4828. for (std::string & word : bpe_words) {
  4829. std::string encoded_token = "";
  4830. for (char & c : word) {
  4831. encoded_token += bytes_to_unicode_bpe(c);
  4832. }
  4833. bpe_encoded_words.emplace_back(encoded_token);
  4834. }
  4835. return bpe_encoded_words;
  4836. }
  4837. const llama_vocab & vocab;
  4838. std::vector<llm_symbol> symbols;
  4839. std::vector<llm_symbol> symbols_final;
  4840. llm_bigram_bpe::queue work_queue;
  4841. };
  4842. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  4843. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  4844. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  4845. } FRAGMENT_BUFFER_VARIANT_TYPE;
  4846. struct fragment_buffer_variant{
  4847. fragment_buffer_variant(llama_vocab::id _token)
  4848. :
  4849. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  4850. token(_token),
  4851. raw_text(_dummy),
  4852. offset(0),
  4853. length(0){}
  4854. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  4855. :
  4856. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  4857. token((llama_vocab::id)-1),
  4858. raw_text(_raw_text),
  4859. offset(_offset),
  4860. length(_length){
  4861. GGML_ASSERT( _offset >= 0 );
  4862. GGML_ASSERT( _length >= 1 );
  4863. GGML_ASSERT( offset + length <= raw_text.length() );
  4864. }
  4865. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  4866. const llama_vocab::id token;
  4867. const std::string _dummy;
  4868. const std::string & raw_text;
  4869. const uint64_t offset;
  4870. const uint64_t length;
  4871. };
  4872. // #define PRETOKENIZERDEBUG
  4873. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  4874. {
  4875. // for each special token
  4876. for (const auto & st: vocab.special_tokens_cache) {
  4877. const auto & special_token = st.first;
  4878. const auto & special_id = st.second;
  4879. // for each text fragment
  4880. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  4881. while (it != buffer.end()) {
  4882. auto & fragment = (*it);
  4883. // if a fragment is text ( not yet processed )
  4884. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  4885. auto * raw_text = &(fragment.raw_text);
  4886. auto raw_text_base_offset = fragment.offset;
  4887. auto raw_text_base_length = fragment.length;
  4888. // loop over the text
  4889. while (true) {
  4890. // find the first occurence of a given special token in this fragment
  4891. // passing offset argument only limit the "search area" but match coordinates
  4892. // are still relative to the source full raw_text
  4893. auto match = raw_text->find(special_token, raw_text_base_offset);
  4894. // no occurences found, stop processing this fragment for a given special token
  4895. if (match == std::string::npos) break;
  4896. // check if match is within bounds of offset <-> length
  4897. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  4898. #ifdef PRETOKENIZERDEBUG
  4899. fprintf(stderr, "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());
  4900. #endif
  4901. auto source = std::distance(buffer.begin(), it);
  4902. // if match is further than base offset
  4903. // then we have some text to the left of it
  4904. if (match > raw_text_base_offset) {
  4905. // left
  4906. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  4907. const int64_t left_reminder_length = match - raw_text_base_offset;
  4908. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  4909. #ifdef PRETOKENIZERDEBUG
  4910. fprintf(stderr, "FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  4911. #endif
  4912. it++;
  4913. }
  4914. // special token
  4915. buffer.emplace_after(it, special_id);
  4916. it++;
  4917. // right
  4918. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  4919. const int64_t right_reminder_offset = match + special_token.length();
  4920. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  4921. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  4922. #ifdef PRETOKENIZERDEBUG
  4923. fprintf(stderr, "FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  4924. #endif
  4925. it++;
  4926. if (source == 0) {
  4927. buffer.erase_after(buffer.before_begin());
  4928. } else {
  4929. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  4930. }
  4931. // repeat for the right side
  4932. raw_text_base_offset = right_reminder_offset;
  4933. raw_text_base_length = right_reminder_length;
  4934. #ifdef PRETOKENIZERDEBUG
  4935. fprintf(stderr, "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());
  4936. #endif
  4937. } else {
  4938. if (source == 0) {
  4939. buffer.erase_after(buffer.before_begin());
  4940. } else {
  4941. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  4942. }
  4943. break;
  4944. }
  4945. }
  4946. }
  4947. it++;
  4948. }
  4949. }
  4950. }
  4951. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  4952. std::vector<llama_vocab::id> output;
  4953. // OG tokenizer behavior:
  4954. //
  4955. // tokenizer.encode('', add_bos=True) returns [1]
  4956. // tokenizer.encode('', add_bos=False) returns []
  4957. if (bos && vocab.special_bos_id != -1) {
  4958. output.push_back(vocab.special_bos_id);
  4959. }
  4960. if (raw_text.empty()) {
  4961. return output;
  4962. }
  4963. std::forward_list<fragment_buffer_variant> fragment_buffer;
  4964. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  4965. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  4966. switch (vocab.type) {
  4967. case LLAMA_VOCAB_TYPE_SPM:
  4968. {
  4969. for (const auto & fragment: fragment_buffer)
  4970. {
  4971. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  4972. {
  4973. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  4974. // TODO: It's likely possible to get rid of this string copy entirely
  4975. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  4976. // and passing 'add space prefix' as bool argument
  4977. //
  4978. auto raw_text = (special ? "" : " ") + fragment.raw_text.substr(fragment.offset, fragment.length);
  4979. #ifdef PRETOKENIZERDEBUG
  4980. fprintf(stderr,"TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  4981. #endif
  4982. llm_tokenizer_spm tokenizer(vocab);
  4983. llama_escape_whitespace(raw_text);
  4984. tokenizer.tokenize(raw_text, output);
  4985. }
  4986. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  4987. {
  4988. output.push_back(fragment.token);
  4989. }
  4990. }
  4991. } break;
  4992. case LLAMA_VOCAB_TYPE_BPE:
  4993. {
  4994. for (const auto & fragment: fragment_buffer)
  4995. {
  4996. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  4997. {
  4998. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  4999. #ifdef PRETOKENIZERDEBUG
  5000. fprintf(stderr,"TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  5001. #endif
  5002. llm_tokenizer_bpe tokenizer(vocab);
  5003. tokenizer.tokenize(raw_text, output);
  5004. }
  5005. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  5006. {
  5007. output.push_back(fragment.token);
  5008. }
  5009. }
  5010. } break;
  5011. }
  5012. return output;
  5013. }
  5014. //
  5015. // grammar - internal
  5016. //
  5017. struct llama_partial_utf8 {
  5018. uint32_t value; // bit value so far (unshifted)
  5019. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  5020. };
  5021. struct llama_grammar {
  5022. const std::vector<std::vector<llama_grammar_element>> rules;
  5023. std::vector<std::vector<const llama_grammar_element *>> stacks;
  5024. // buffer for partially generated UTF-8 sequence from accepted tokens
  5025. llama_partial_utf8 partial_utf8;
  5026. };
  5027. struct llama_grammar_candidate {
  5028. size_t index;
  5029. const uint32_t * code_points;
  5030. llama_partial_utf8 partial_utf8;
  5031. };
  5032. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  5033. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  5034. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  5035. const char * src,
  5036. llama_partial_utf8 partial_start) {
  5037. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  5038. const char * pos = src;
  5039. std::vector<uint32_t> code_points;
  5040. uint32_t value = partial_start.value;
  5041. int n_remain = partial_start.n_remain;
  5042. // continue previous decode, if applicable
  5043. while (*pos != 0 && n_remain > 0) {
  5044. uint8_t next_byte = static_cast<uint8_t>(*pos);
  5045. if ((next_byte >> 6) != 2) {
  5046. // invalid sequence, abort
  5047. code_points.push_back(0);
  5048. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  5049. }
  5050. value = (value << 6) + (next_byte & 0x3F);
  5051. ++pos;
  5052. --n_remain;
  5053. }
  5054. if (partial_start.n_remain > 0 && n_remain == 0) {
  5055. code_points.push_back(value);
  5056. }
  5057. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  5058. while (*pos != 0) {
  5059. uint8_t first_byte = static_cast<uint8_t>(*pos);
  5060. uint8_t highbits = first_byte >> 4;
  5061. n_remain = lookup[highbits] - 1;
  5062. if (n_remain < 0) {
  5063. // invalid sequence, abort
  5064. code_points.clear();
  5065. code_points.push_back(0);
  5066. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  5067. }
  5068. uint8_t mask = (1 << (7 - n_remain)) - 1;
  5069. value = first_byte & mask;
  5070. ++pos;
  5071. while (*pos != 0 && n_remain > 0) {
  5072. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  5073. ++pos;
  5074. --n_remain;
  5075. }
  5076. if (n_remain == 0) {
  5077. code_points.push_back(value);
  5078. }
  5079. }
  5080. code_points.push_back(0);
  5081. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  5082. }
  5083. // returns true iff pos points to the end of one of the definitions of a rule
  5084. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  5085. switch (pos->type) {
  5086. case LLAMA_GRETYPE_END: return true; // NOLINT
  5087. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  5088. default: return false;
  5089. }
  5090. }
  5091. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  5092. // asserts that pos is pointing to a char range element
  5093. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  5094. const llama_grammar_element * pos,
  5095. const uint32_t chr) {
  5096. bool found = false;
  5097. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  5098. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  5099. do {
  5100. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  5101. // inclusive range, e.g. [a-z]
  5102. found = found || (pos->value <= chr && chr <= pos[1].value);
  5103. pos += 2;
  5104. } else {
  5105. // exact char match, e.g. [a] or "a"
  5106. found = found || pos->value == chr;
  5107. pos += 1;
  5108. }
  5109. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  5110. return std::make_pair(found == is_positive_char, pos);
  5111. }
  5112. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  5113. // range at pos (regular or inverse range)
  5114. // asserts that pos is pointing to a char range element
  5115. static bool llama_grammar_match_partial_char(
  5116. const llama_grammar_element * pos,
  5117. const llama_partial_utf8 partial_utf8) {
  5118. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  5119. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  5120. uint32_t partial_value = partial_utf8.value;
  5121. int n_remain = partial_utf8.n_remain;
  5122. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  5123. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  5124. return false;
  5125. }
  5126. // range of possible code points this partial UTF-8 sequence could complete to
  5127. uint32_t low = partial_value << (n_remain * 6);
  5128. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  5129. if (low == 0) {
  5130. if (n_remain == 2) {
  5131. low = 1 << 11;
  5132. } else if (n_remain == 3) {
  5133. low = 1 << 16;
  5134. }
  5135. }
  5136. do {
  5137. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  5138. // inclusive range, e.g. [a-z]
  5139. if (pos->value <= high && low <= pos[1].value) {
  5140. return is_positive_char;
  5141. }
  5142. pos += 2;
  5143. } else {
  5144. // exact char match, e.g. [a] or "a"
  5145. if (low <= pos->value && pos->value <= high) {
  5146. return is_positive_char;
  5147. }
  5148. pos += 1;
  5149. }
  5150. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  5151. return !is_positive_char;
  5152. }
  5153. // transforms a grammar pushdown stack into N possible stacks, all ending
  5154. // at a character range (terminal element)
  5155. static void llama_grammar_advance_stack(
  5156. const std::vector<std::vector<llama_grammar_element>> & rules,
  5157. const std::vector<const llama_grammar_element *> & stack,
  5158. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  5159. if (stack.empty()) {
  5160. new_stacks.emplace_back(stack);
  5161. return;
  5162. }
  5163. const llama_grammar_element * pos = stack.back();
  5164. switch (pos->type) {
  5165. case LLAMA_GRETYPE_RULE_REF: {
  5166. const size_t rule_id = static_cast<size_t>(pos->value);
  5167. const llama_grammar_element * subpos = rules[rule_id].data();
  5168. do {
  5169. // init new stack without the top (pos)
  5170. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  5171. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  5172. // if this rule ref is followed by another element, add that to stack
  5173. new_stack.push_back(pos + 1);
  5174. }
  5175. if (!llama_grammar_is_end_of_sequence(subpos)) {
  5176. // if alternate is nonempty, add to stack
  5177. new_stack.push_back(subpos);
  5178. }
  5179. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  5180. while (!llama_grammar_is_end_of_sequence(subpos)) {
  5181. // scan to end of alternate def
  5182. subpos++;
  5183. }
  5184. if (subpos->type == LLAMA_GRETYPE_ALT) {
  5185. // there's another alternate def of this rule to process
  5186. subpos++;
  5187. } else {
  5188. break;
  5189. }
  5190. } while (true);
  5191. break;
  5192. }
  5193. case LLAMA_GRETYPE_CHAR:
  5194. case LLAMA_GRETYPE_CHAR_NOT:
  5195. new_stacks.emplace_back(stack);
  5196. break;
  5197. default:
  5198. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  5199. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  5200. // those
  5201. GGML_ASSERT(false);
  5202. }
  5203. }
  5204. // takes a set of possible pushdown stacks on a grammar, which are required to
  5205. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  5206. // produces the N possible stacks if the given char is accepted at those
  5207. // positions
  5208. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  5209. const std::vector<std::vector<llama_grammar_element>> & rules,
  5210. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  5211. const uint32_t chr) {
  5212. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  5213. for (const auto & stack : stacks) {
  5214. if (stack.empty()) {
  5215. continue;
  5216. }
  5217. auto match = llama_grammar_match_char(stack.back(), chr);
  5218. if (match.first) {
  5219. const llama_grammar_element * pos = match.second;
  5220. // update top of stack to next element, if any
  5221. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  5222. if (!llama_grammar_is_end_of_sequence(pos)) {
  5223. new_stack.push_back(pos);
  5224. }
  5225. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  5226. }
  5227. }
  5228. return new_stacks;
  5229. }
  5230. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  5231. const std::vector<std::vector<llama_grammar_element>> & rules,
  5232. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  5233. const std::vector<llama_grammar_candidate> & candidates);
  5234. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  5235. const std::vector<std::vector<llama_grammar_element>> & rules,
  5236. const std::vector<const llama_grammar_element *> & stack,
  5237. const std::vector<llama_grammar_candidate> & candidates) {
  5238. std::vector<llama_grammar_candidate> rejects;
  5239. if (stack.empty()) {
  5240. for (const auto & tok : candidates) {
  5241. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  5242. rejects.push_back(tok);
  5243. }
  5244. }
  5245. return rejects;
  5246. }
  5247. const llama_grammar_element * stack_pos = stack.back();
  5248. std::vector<llama_grammar_candidate> next_candidates;
  5249. for (const auto & tok : candidates) {
  5250. if (*tok.code_points == 0) {
  5251. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  5252. // that cannot satisfy this position in grammar
  5253. if (tok.partial_utf8.n_remain != 0 &&
  5254. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  5255. rejects.push_back(tok);
  5256. }
  5257. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  5258. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  5259. } else {
  5260. rejects.push_back(tok);
  5261. }
  5262. }
  5263. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  5264. // update top of stack to next element, if any
  5265. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  5266. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  5267. stack_after.push_back(stack_pos_after);
  5268. }
  5269. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  5270. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  5271. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  5272. for (const auto & tok : next_rejects) {
  5273. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  5274. }
  5275. return rejects;
  5276. }
  5277. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  5278. const std::vector<std::vector<llama_grammar_element>> & rules,
  5279. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  5280. const std::vector<llama_grammar_candidate> & candidates) {
  5281. GGML_ASSERT(!stacks.empty()); // REVIEW
  5282. if (candidates.empty()) {
  5283. return std::vector<llama_grammar_candidate>();
  5284. }
  5285. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  5286. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  5287. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  5288. }
  5289. return rejects;
  5290. }
  5291. //
  5292. // grammar - external
  5293. //
  5294. struct llama_grammar * llama_grammar_init(
  5295. const llama_grammar_element ** rules,
  5296. size_t n_rules,
  5297. size_t start_rule_index) {
  5298. const llama_grammar_element * pos;
  5299. // copy rule definitions into vectors
  5300. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  5301. for (size_t i = 0; i < n_rules; i++) {
  5302. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  5303. vec_rules[i].push_back(*pos);
  5304. }
  5305. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  5306. }
  5307. // loop over alternates of start rule to build initial stacks
  5308. std::vector<std::vector<const llama_grammar_element *>> stacks;
  5309. pos = rules[start_rule_index];
  5310. do {
  5311. std::vector<const llama_grammar_element *> stack;
  5312. if (!llama_grammar_is_end_of_sequence(pos)) {
  5313. // if alternate is nonempty, add to stack
  5314. stack.push_back(pos);
  5315. }
  5316. llama_grammar_advance_stack(vec_rules, stack, stacks);
  5317. while (!llama_grammar_is_end_of_sequence(pos)) {
  5318. // scan to end of alternate def
  5319. pos++;
  5320. }
  5321. if (pos->type == LLAMA_GRETYPE_ALT) {
  5322. // there's another alternate def of this rule to process
  5323. pos++;
  5324. } else {
  5325. break;
  5326. }
  5327. } while (true);
  5328. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  5329. }
  5330. void llama_grammar_free(struct llama_grammar * grammar) {
  5331. delete grammar;
  5332. }
  5333. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  5334. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  5335. // redirect elements in stacks to point to new rules
  5336. for (size_t is = 0; is < result->stacks.size(); is++) {
  5337. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  5338. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  5339. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  5340. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  5341. result->stacks[is][ie] = &result->rules[ir0][ir1];
  5342. }
  5343. }
  5344. }
  5345. }
  5346. }
  5347. return result;
  5348. }
  5349. //
  5350. // sampling
  5351. //
  5352. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  5353. if (seed == LLAMA_DEFAULT_SEED) {
  5354. seed = time(NULL);
  5355. }
  5356. ctx->rng.seed(seed);
  5357. }
  5358. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  5359. GGML_ASSERT(candidates->size > 0);
  5360. const int64_t t_start_sample_us = ggml_time_us();
  5361. // Sort the logits in descending order
  5362. if (!candidates->sorted) {
  5363. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  5364. return a.logit > b.logit;
  5365. });
  5366. candidates->sorted = true;
  5367. }
  5368. float max_l = candidates->data[0].logit;
  5369. float cum_sum = 0.0f;
  5370. for (size_t i = 0; i < candidates->size; ++i) {
  5371. float p = expf(candidates->data[i].logit - max_l);
  5372. candidates->data[i].p = p;
  5373. cum_sum += p;
  5374. }
  5375. for (size_t i = 0; i < candidates->size; ++i) {
  5376. candidates->data[i].p /= cum_sum;
  5377. }
  5378. if (ctx) {
  5379. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5380. }
  5381. }
  5382. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  5383. const int64_t t_start_sample_us = ggml_time_us();
  5384. k = std::max(k, (int) min_keep);
  5385. k = std::min(k, (int) candidates->size);
  5386. // Sort scores in descending order
  5387. if (!candidates->sorted) {
  5388. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  5389. return a.logit > b.logit;
  5390. };
  5391. if (k == (int) candidates->size) {
  5392. std::sort(candidates->data, candidates->data + candidates->size, comp);
  5393. } else {
  5394. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  5395. }
  5396. candidates->sorted = true;
  5397. }
  5398. candidates->size = k;
  5399. if (ctx) {
  5400. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5401. }
  5402. }
  5403. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  5404. if (p >= 1.0f) {
  5405. return;
  5406. }
  5407. llama_sample_softmax(ctx, candidates);
  5408. const int64_t t_start_sample_us = ggml_time_us();
  5409. // Compute the cumulative probabilities
  5410. float cum_sum = 0.0f;
  5411. size_t last_idx = candidates->size;
  5412. for (size_t i = 0; i < candidates->size; ++i) {
  5413. cum_sum += candidates->data[i].p;
  5414. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  5415. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  5416. if (cum_sum >= p && i + 1 >= min_keep) {
  5417. last_idx = i + 1;
  5418. break;
  5419. }
  5420. }
  5421. // Resize the output vector to keep only the top-p tokens
  5422. candidates->size = last_idx;
  5423. if (ctx) {
  5424. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5425. }
  5426. }
  5427. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  5428. if (p <= 0.0f || !candidates->size) {
  5429. return;
  5430. }
  5431. llama_sample_softmax(ctx, candidates);
  5432. const int64_t t_start_sample_us = ggml_time_us();
  5433. float scale = candidates->data[0].p; // scale by max prob
  5434. size_t i = 1; // first token always matches
  5435. for (; i < candidates->size; ++i) {
  5436. if (candidates->data[i].p < p * scale && i >= min_keep) {
  5437. break; // prob too small
  5438. }
  5439. }
  5440. // Resize the output vector to keep only the matching tokens
  5441. candidates->size = i;
  5442. if (ctx) {
  5443. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5444. }
  5445. }
  5446. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  5447. if (z >= 1.0f || candidates->size <= 2) {
  5448. return;
  5449. }
  5450. llama_sample_softmax(nullptr, candidates);
  5451. const int64_t t_start_sample_us = ggml_time_us();
  5452. // Compute the first and second derivatives
  5453. std::vector<float> first_derivatives(candidates->size - 1);
  5454. std::vector<float> second_derivatives(candidates->size - 2);
  5455. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  5456. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  5457. }
  5458. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  5459. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  5460. }
  5461. // Calculate absolute value of second derivatives
  5462. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  5463. second_derivatives[i] = std::abs(second_derivatives[i]);
  5464. }
  5465. // Normalize the second derivatives
  5466. {
  5467. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  5468. if (second_derivatives_sum > 1e-6f) {
  5469. for (float & value : second_derivatives) {
  5470. value /= second_derivatives_sum;
  5471. }
  5472. } else {
  5473. for (float & value : second_derivatives) {
  5474. value = 1.0f / second_derivatives.size();
  5475. }
  5476. }
  5477. }
  5478. float cum_sum = 0.0f;
  5479. size_t last_idx = candidates->size;
  5480. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  5481. cum_sum += second_derivatives[i];
  5482. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  5483. if (cum_sum > z && i >= min_keep) {
  5484. last_idx = i;
  5485. break;
  5486. }
  5487. }
  5488. // Resize the output vector to keep only the tokens above the tail location
  5489. candidates->size = last_idx;
  5490. if (ctx) {
  5491. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5492. }
  5493. }
  5494. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  5495. // Reference implementation:
  5496. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  5497. if (p >= 1.0f) {
  5498. return;
  5499. }
  5500. // Compute the softmax of logits and calculate entropy
  5501. llama_sample_softmax(nullptr, candidates);
  5502. const int64_t t_start_sample_us = ggml_time_us();
  5503. float entropy = 0.0f;
  5504. for (size_t i = 0; i < candidates->size; ++i) {
  5505. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  5506. }
  5507. // Compute the absolute difference between negative log probability and entropy for each candidate
  5508. std::vector<float> shifted_scores;
  5509. for (size_t i = 0; i < candidates->size; ++i) {
  5510. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  5511. shifted_scores.push_back(shifted_score);
  5512. }
  5513. // Sort tokens based on the shifted_scores and their corresponding indices
  5514. std::vector<size_t> indices(candidates->size);
  5515. std::iota(indices.begin(), indices.end(), 0);
  5516. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  5517. return shifted_scores[a] < shifted_scores[b];
  5518. });
  5519. // Compute the cumulative probabilities
  5520. float cum_sum = 0.0f;
  5521. size_t last_idx = indices.size();
  5522. for (size_t i = 0; i < indices.size(); ++i) {
  5523. size_t idx = indices[i];
  5524. cum_sum += candidates->data[idx].p;
  5525. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  5526. if (cum_sum > p && i >= min_keep - 1) {
  5527. last_idx = i + 1;
  5528. break;
  5529. }
  5530. }
  5531. // Resize the output vector to keep only the locally typical tokens
  5532. std::vector<llama_token_data> new_candidates;
  5533. for (size_t i = 0; i < last_idx; ++i) {
  5534. size_t idx = indices[i];
  5535. new_candidates.push_back(candidates->data[idx]);
  5536. }
  5537. // Replace the data in candidates with the new_candidates data
  5538. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  5539. candidates->size = new_candidates.size();
  5540. if (ctx) {
  5541. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5542. }
  5543. }
  5544. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  5545. const int64_t t_start_sample_us = ggml_time_us();
  5546. for (size_t i = 0; i < candidates_p->size; ++i) {
  5547. candidates_p->data[i].logit /= temp;
  5548. }
  5549. if (ctx) {
  5550. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5551. }
  5552. }
  5553. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  5554. llama_sample_temp(ctx, candidates_p, temp);
  5555. }
  5556. void llama_sample_repetition_penalties(
  5557. struct llama_context * ctx,
  5558. llama_token_data_array * candidates,
  5559. const llama_token * last_tokens,
  5560. size_t penalty_last_n,
  5561. float penalty_repeat,
  5562. float penalty_freq,
  5563. float penalty_present) {
  5564. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  5565. return;
  5566. }
  5567. const int64_t t_start_sample_us = ggml_time_us();
  5568. // Create a frequency map to count occurrences of each token in last_tokens
  5569. std::unordered_map<llama_token, int> token_count;
  5570. for (size_t i = 0; i < penalty_last_n; ++i) {
  5571. token_count[last_tokens[i]]++;
  5572. }
  5573. // Apply frequency and presence penalties to the candidates
  5574. for (size_t i = 0; i < candidates->size; ++i) {
  5575. const auto token_iter = token_count.find(candidates->data[i].id);
  5576. if (token_iter == token_count.end()) {
  5577. continue;
  5578. }
  5579. const int count = token_iter->second;
  5580. // 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.
  5581. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  5582. if (candidates->data[i].logit <= 0) {
  5583. candidates->data[i].logit *= penalty_repeat;
  5584. } else {
  5585. candidates->data[i].logit /= penalty_repeat;
  5586. }
  5587. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  5588. }
  5589. candidates->sorted = false;
  5590. if (ctx) {
  5591. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5592. }
  5593. }
  5594. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  5595. GGML_ASSERT(ctx);
  5596. const int64_t t_start_sample_us = ggml_time_us();
  5597. bool allow_eos = false;
  5598. for (const auto & stack : grammar->stacks) {
  5599. if (stack.empty()) {
  5600. allow_eos = true;
  5601. break;
  5602. }
  5603. }
  5604. const llama_token eos = llama_token_eos(&ctx->model);
  5605. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  5606. std::vector<llama_grammar_candidate> candidates_grammar;
  5607. for (size_t i = 0; i < candidates->size; ++i) {
  5608. const llama_token id = candidates->data[i].id;
  5609. const std::string piece = llama_token_to_piece(ctx, id);
  5610. if (id == eos) {
  5611. if (!allow_eos) {
  5612. candidates->data[i].logit = -INFINITY;
  5613. }
  5614. } else if (piece.empty() || piece[0] == 0) {
  5615. candidates->data[i].logit = -INFINITY;
  5616. } else {
  5617. candidates_decoded.push_back(decode_utf8(piece.c_str(), grammar->partial_utf8));
  5618. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  5619. }
  5620. }
  5621. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  5622. for (const auto & reject : rejects) {
  5623. candidates->data[reject.index].logit = -INFINITY;
  5624. }
  5625. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5626. }
  5627. static void llama_log_softmax(float * array, size_t size) {
  5628. float max_l = *std::max_element(array, array + size);
  5629. float sum = 0.f;
  5630. for (size_t i = 0; i < size; ++i) {
  5631. float p = expf(array[i] - max_l);
  5632. sum += p;
  5633. array[i] = p;
  5634. }
  5635. for (size_t i = 0; i < size; ++i) {
  5636. array[i] = logf(array[i] / sum);
  5637. }
  5638. }
  5639. void llama_sample_classifier_free_guidance(
  5640. struct llama_context * ctx,
  5641. llama_token_data_array * candidates,
  5642. struct llama_context * guidance_ctx,
  5643. float scale) {
  5644. int64_t t_start_sample_us = ggml_time_us();
  5645. GGML_ASSERT(ctx);
  5646. auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  5647. GGML_ASSERT(n_vocab == (int)candidates->size);
  5648. GGML_ASSERT(!candidates->sorted);
  5649. std::vector<float> logits_base;
  5650. logits_base.reserve(candidates->size);
  5651. for (size_t i = 0; i < candidates->size; ++i) {
  5652. logits_base.push_back(candidates->data[i].logit);
  5653. }
  5654. llama_log_softmax(logits_base.data(), candidates->size);
  5655. float* logits_guidance = llama_get_logits(guidance_ctx);
  5656. llama_log_softmax(logits_guidance, n_vocab);
  5657. for (int i = 0; i < n_vocab; ++i) {
  5658. float logit_guidance = logits_guidance[i];
  5659. float logit_base = logits_base[i];
  5660. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  5661. }
  5662. if (ctx) {
  5663. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5664. }
  5665. }
  5666. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  5667. GGML_ASSERT(ctx);
  5668. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  5669. int64_t t_start_sample_us;
  5670. t_start_sample_us = ggml_time_us();
  5671. llama_sample_softmax(nullptr, candidates);
  5672. // Estimate s_hat using the most probable m tokens
  5673. float s_hat = 0.0;
  5674. float sum_ti_bi = 0.0;
  5675. float sum_ti_sq = 0.0;
  5676. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  5677. float t_i = logf(float(i + 2) / float(i + 1));
  5678. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  5679. sum_ti_bi += t_i * b_i;
  5680. sum_ti_sq += t_i * t_i;
  5681. }
  5682. s_hat = sum_ti_bi / sum_ti_sq;
  5683. // Compute k from the estimated s_hat and target surprise value
  5684. float epsilon_hat = s_hat - 1;
  5685. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  5686. // Sample the next word X using top-k sampling
  5687. llama_sample_top_k(nullptr, candidates, int(k), 1);
  5688. if (ctx) {
  5689. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5690. }
  5691. llama_token X = llama_sample_token(ctx, candidates);
  5692. t_start_sample_us = ggml_time_us();
  5693. // Compute error as the difference between observed surprise and target surprise value
  5694. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  5695. return candidate.id == X;
  5696. }));
  5697. float observed_surprise = -log2f(candidates->data[X_idx].p);
  5698. float e = observed_surprise - tau;
  5699. // Update mu using the learning rate and error
  5700. *mu = *mu - eta * e;
  5701. if (ctx) {
  5702. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5703. }
  5704. return X;
  5705. }
  5706. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  5707. int64_t t_start_sample_us;
  5708. t_start_sample_us = ggml_time_us();
  5709. llama_sample_softmax(ctx, candidates);
  5710. // Truncate the words with surprise values greater than mu
  5711. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  5712. return -log2f(candidate.p) > *mu;
  5713. }));
  5714. if (candidates->size == 0) {
  5715. candidates->size = 1;
  5716. }
  5717. if (ctx) {
  5718. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5719. }
  5720. // Normalize the probabilities of the remaining words
  5721. llama_sample_softmax(ctx, candidates);
  5722. // Sample the next word X from the remaining words
  5723. llama_token X = llama_sample_token(ctx, candidates);
  5724. t_start_sample_us = ggml_time_us();
  5725. // Compute error as the difference between observed surprise and target surprise value
  5726. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  5727. return candidate.id == X;
  5728. }));
  5729. float observed_surprise = -log2f(candidates->data[X_idx].p);
  5730. float e = observed_surprise - tau;
  5731. // Update mu using the learning rate and error
  5732. *mu = *mu - eta * e;
  5733. if (ctx) {
  5734. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5735. }
  5736. return X;
  5737. }
  5738. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  5739. const int64_t t_start_sample_us = ggml_time_us();
  5740. // Find max element
  5741. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  5742. return a.logit < b.logit;
  5743. });
  5744. llama_token result = max_iter->id;
  5745. if (ctx) {
  5746. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5747. ctx->n_sample++;
  5748. }
  5749. return result;
  5750. }
  5751. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  5752. GGML_ASSERT(ctx);
  5753. const int64_t t_start_sample_us = ggml_time_us();
  5754. llama_sample_softmax(nullptr, candidates);
  5755. std::vector<float> probs;
  5756. probs.reserve(candidates->size);
  5757. for (size_t i = 0; i < candidates->size; ++i) {
  5758. probs.push_back(candidates->data[i].p);
  5759. }
  5760. std::discrete_distribution<> dist(probs.begin(), probs.end());
  5761. auto & rng = ctx->rng;
  5762. int idx = dist(rng);
  5763. llama_token result = candidates->data[idx].id;
  5764. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5765. ctx->n_sample++;
  5766. return result;
  5767. }
  5768. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  5769. const int64_t t_start_sample_us = ggml_time_us();
  5770. if (token == llama_token_eos(&ctx->model)) {
  5771. for (const auto & stack : grammar->stacks) {
  5772. if (stack.empty()) {
  5773. return;
  5774. }
  5775. }
  5776. GGML_ASSERT(false);
  5777. }
  5778. const std::string piece = llama_token_to_piece(ctx, token);
  5779. // Note terminating 0 in decoded string
  5780. const auto decoded = decode_utf8(piece.c_str(), grammar->partial_utf8);
  5781. const auto & code_points = decoded.first;
  5782. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  5783. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  5784. }
  5785. grammar->partial_utf8 = decoded.second;
  5786. GGML_ASSERT(!grammar->stacks.empty());
  5787. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  5788. }
  5789. //
  5790. // Beam search
  5791. //
  5792. struct llama_beam {
  5793. std::vector<llama_token> tokens;
  5794. float p; // Cumulative beam probability (renormalized relative to all beams)
  5795. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  5796. // Sort beams by probability. In case of ties, prefer beams at eob.
  5797. bool operator<(const llama_beam & rhs) const {
  5798. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  5799. }
  5800. // Shift off first n tokens and discard them.
  5801. void shift_tokens(const size_t n) {
  5802. if (n) {
  5803. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  5804. tokens.resize(tokens.size() - n);
  5805. }
  5806. }
  5807. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  5808. };
  5809. // A struct for calculating logit-related info.
  5810. struct llama_logit_info {
  5811. const float * const logits;
  5812. const int n_vocab;
  5813. const float max_l;
  5814. const float normalizer;
  5815. struct sum_exp {
  5816. float max_l;
  5817. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  5818. };
  5819. llama_logit_info(llama_context * ctx)
  5820. : logits(llama_get_logits(ctx))
  5821. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  5822. , max_l(*std::max_element(logits, logits + n_vocab))
  5823. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  5824. { }
  5825. llama_token_data get_token_data(const llama_token token_id) const {
  5826. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  5827. return {token_id, logits[token_id], p};
  5828. }
  5829. // Return top k token_data by logit.
  5830. std::vector<llama_token_data> top_k(size_t k) {
  5831. std::vector<llama_token_data> min_heap; // min-heap by logit
  5832. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  5833. min_heap.reserve(k_min);
  5834. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  5835. min_heap.push_back(get_token_data(token_id));
  5836. }
  5837. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  5838. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  5839. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  5840. if (min_heap.front().logit < logits[token_id]) {
  5841. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  5842. min_heap.back().id = token_id;
  5843. min_heap.back().logit = logits[token_id];
  5844. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  5845. }
  5846. }
  5847. return min_heap;
  5848. }
  5849. float probability_from_logit(float logit) const {
  5850. return normalizer * std::exp(logit - max_l);
  5851. }
  5852. };
  5853. struct llama_beam_search_data {
  5854. llama_context * ctx;
  5855. size_t n_beams;
  5856. int n_past;
  5857. int n_predict;
  5858. std::vector<llama_beam> beams;
  5859. std::vector<llama_beam> next_beams;
  5860. // Re-calculated on each loop iteration
  5861. size_t common_prefix_length;
  5862. // Used to communicate to/from callback on beams state.
  5863. std::vector<llama_beam_view> beam_views;
  5864. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  5865. : ctx(ctx)
  5866. , n_beams(n_beams)
  5867. , n_past(n_past)
  5868. , n_predict(n_predict)
  5869. , beam_views(n_beams) {
  5870. beams.reserve(n_beams);
  5871. next_beams.reserve(n_beams);
  5872. }
  5873. // Collapse beams to a single beam given by index.
  5874. void collapse_beams(const size_t beam_idx) {
  5875. if (0u < beam_idx) {
  5876. std::swap(beams[0], beams[beam_idx]);
  5877. }
  5878. beams.resize(1);
  5879. }
  5880. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  5881. // The repetative patterns below reflect the 2 stages of heaps:
  5882. // * Gather elements until the vector is full, then call std::make_heap() on it.
  5883. // * If the heap is full and a new element is found that should be included, pop the
  5884. // least element to the back(), replace it with the new, then push it into the heap.
  5885. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  5886. // Min-heaps use a greater-than comparator.
  5887. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  5888. if (beam.eob) {
  5889. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  5890. if (next_beams.size() < n_beams) {
  5891. next_beams.push_back(std::move(beam));
  5892. if (next_beams.size() == n_beams) {
  5893. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  5894. }
  5895. } else if (next_beams.front().p < beam.p) {
  5896. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  5897. next_beams.back() = std::move(beam);
  5898. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  5899. }
  5900. } else {
  5901. // beam is not at end-of-sentence, so branch with next top_k tokens.
  5902. if (!beam.tokens.empty()) {
  5903. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  5904. }
  5905. llama_logit_info logit_info(ctx);
  5906. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  5907. size_t i=0;
  5908. if (next_beams.size() < n_beams) {
  5909. for (; next_beams.size() < n_beams ; ++i) {
  5910. llama_beam next_beam = beam;
  5911. next_beam.tokens.push_back(next_tokens[i].id);
  5912. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  5913. next_beams.push_back(std::move(next_beam));
  5914. }
  5915. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  5916. } else {
  5917. for (; next_beams.front().p == 0.0f ; ++i) {
  5918. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  5919. next_beams.back() = beam;
  5920. next_beams.back().tokens.push_back(next_tokens[i].id);
  5921. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  5922. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  5923. }
  5924. }
  5925. for (; i < n_beams ; ++i) {
  5926. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  5927. if (next_beams.front().p < next_p) {
  5928. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  5929. next_beams.back() = beam;
  5930. next_beams.back().tokens.push_back(next_tokens[i].id);
  5931. next_beams.back().p = next_p;
  5932. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  5933. }
  5934. }
  5935. }
  5936. }
  5937. // Find common_prefix_length based on beams.
  5938. // Requires beams is not empty.
  5939. size_t find_common_prefix_length() {
  5940. size_t common_prefix_length = beams[0].tokens.size();
  5941. for (size_t i = 1 ; i < beams.size() ; ++i) {
  5942. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  5943. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  5944. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  5945. common_prefix_length = j;
  5946. break;
  5947. }
  5948. }
  5949. }
  5950. return common_prefix_length;
  5951. }
  5952. // Construct beams_state to send back to caller via the callback function.
  5953. // Side effect: set common_prefix_length = find_common_prefix_length();
  5954. llama_beams_state get_beams_state(const bool last_call) {
  5955. for (size_t i = 0 ; i < beams.size() ; ++i) {
  5956. beam_views[i] = beams[i].view();
  5957. }
  5958. common_prefix_length = find_common_prefix_length();
  5959. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  5960. }
  5961. // Loop:
  5962. // * while i < n_predict, AND
  5963. // * any of the beams have not yet reached end-of-beam (eob), AND
  5964. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  5965. // (since all other beam probabilities can only decrease)
  5966. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  5967. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  5968. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  5969. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  5970. !beams[top_beam_index()].eob ; ++i) {
  5971. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  5972. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  5973. if (common_prefix_length) {
  5974. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  5975. n_past += common_prefix_length;
  5976. }
  5977. // Zero-out next_beam probabilities to place them last in following min-heap.
  5978. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  5979. for (llama_beam & beam : beams) {
  5980. beam.shift_tokens(common_prefix_length);
  5981. fill_next_beams_by_top_probabilities(beam);
  5982. }
  5983. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  5984. beams.swap(next_beams);
  5985. renormalize_beam_probabilities(beams);
  5986. }
  5987. collapse_beams(top_beam_index());
  5988. callback(callback_data, get_beams_state(true));
  5989. }
  5990. // As beams grow, the cumulative probabilities decrease.
  5991. // Renormalize them to avoid floating point underflow.
  5992. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  5993. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  5994. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  5995. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  5996. }
  5997. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  5998. size_t top_beam_index() {
  5999. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  6000. }
  6001. // Copy (p,eob) for each beam which may have been changed by the callback.
  6002. void update_beams_from_beam_views() {
  6003. for (size_t i = 0 ; i < beams.size() ; ++i) {
  6004. beams[i].p = beam_views[i].p;
  6005. beams[i].eob = beam_views[i].eob;
  6006. }
  6007. }
  6008. };
  6009. void llama_beam_search(llama_context * ctx,
  6010. llama_beam_search_callback_fn_t callback, void * callback_data,
  6011. size_t n_beams, int n_past, int n_predict) {
  6012. assert(ctx);
  6013. const int64_t t_start_sample_us = ggml_time_us();
  6014. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  6015. beam_search_data.loop(callback, callback_data);
  6016. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6017. ctx->n_sample++;
  6018. }
  6019. //
  6020. // quantization
  6021. //
  6022. template <typename T>
  6023. struct no_init {
  6024. T value;
  6025. no_init() { /* do nothing */ }
  6026. };
  6027. struct quantize_state_internal {
  6028. const llama_model & model;
  6029. const llama_model_quantize_params * params;
  6030. int n_attention_wv = 0;
  6031. int n_feed_forward_w2 = 0;
  6032. int i_attention_wv = 0;
  6033. int i_feed_forward_w2 = 0;
  6034. int n_k_quantized = 0;
  6035. int n_fallback = 0;
  6036. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  6037. : model(model)
  6038. , params(params)
  6039. {}
  6040. };
  6041. static void llama_convert_tensor_internal(
  6042. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  6043. const size_t nelements, const int nthread
  6044. ) {
  6045. if (output.size() < nelements) {
  6046. output.resize(nelements);
  6047. }
  6048. float * f32_output = (float *) output.data();
  6049. ggml_type_traits_t qtype;
  6050. if (ggml_is_quantized(tensor->type)) {
  6051. qtype = ggml_internal_get_type_traits(tensor->type);
  6052. if (qtype.to_float == NULL) {
  6053. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  6054. }
  6055. } else if (tensor->type != GGML_TYPE_F16) {
  6056. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  6057. }
  6058. if (nthread < 2) {
  6059. if (tensor->type == GGML_TYPE_F16) {
  6060. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  6061. } else if (ggml_is_quantized(tensor->type)) {
  6062. qtype.to_float(tensor->data, f32_output, nelements);
  6063. } else {
  6064. GGML_ASSERT(false); // unreachable
  6065. }
  6066. return;
  6067. }
  6068. auto block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  6069. auto block_size_bytes = ggml_type_size(tensor->type);
  6070. GGML_ASSERT(nelements % block_size == 0);
  6071. auto nblocks = nelements / block_size;
  6072. auto blocks_per_thread = nblocks / nthread;
  6073. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  6074. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  6075. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  6076. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  6077. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  6078. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  6079. if (typ == GGML_TYPE_F16) {
  6080. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  6081. } else {
  6082. qtype.to_float(inbuf, outbuf, nels);
  6083. }
  6084. };
  6085. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  6086. in_buff_offs += thr_block_bytes;
  6087. out_buff_offs += thr_elems;
  6088. }
  6089. for (auto & w : workers) { w.join(); }
  6090. workers.clear();
  6091. }
  6092. static ggml_type get_k_quant_type(
  6093. quantize_state_internal & qs,
  6094. ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype
  6095. ) {
  6096. const std::string name = ggml_get_name(tensor);
  6097. // TODO: avoid hardcoded tensor names - use the TN_* constants
  6098. const llm_arch arch = qs.model.arch;
  6099. const auto tn = LLM_TN(arch);
  6100. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  6101. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  6102. };
  6103. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  6104. int nx = tensor->ne[0];
  6105. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  6106. new_type = GGML_TYPE_Q8_0;
  6107. }
  6108. else if (new_type != GGML_TYPE_Q8_0) {
  6109. new_type = GGML_TYPE_Q6_K;
  6110. }
  6111. } else if (name.find("attn_v.weight") != std::string::npos) {
  6112. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  6113. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  6114. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  6115. }
  6116. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  6117. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  6118. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  6119. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  6120. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  6121. (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;
  6122. if (qs.model.type == MODEL_70B) {
  6123. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  6124. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  6125. // nearly negligible increase in model size by quantizing this tensor with more bits:
  6126. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  6127. }
  6128. ++qs.i_attention_wv;
  6129. } else if (name.find("ffn_down.weight") != std::string::npos) {
  6130. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  6131. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  6132. new_type = qs.i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K
  6133. : arch != LLM_ARCH_FALCON || use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2) ? GGML_TYPE_Q4_K
  6134. : GGML_TYPE_Q3_K;
  6135. }
  6136. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  6137. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  6138. }
  6139. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  6140. if (arch == LLM_ARCH_FALCON) {
  6141. new_type = qs.i_feed_forward_w2 < 2 ? GGML_TYPE_Q6_K :
  6142. use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  6143. } else {
  6144. if (use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  6145. }
  6146. }
  6147. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  6148. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && qs.i_feed_forward_w2 < 4) {
  6149. new_type = GGML_TYPE_Q5_K;
  6150. }
  6151. ++qs.i_feed_forward_w2;
  6152. } else if (name.find("attn_output.weight") != std::string::npos) {
  6153. if (arch != LLM_ARCH_FALCON) {
  6154. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  6155. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  6156. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  6157. } else {
  6158. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  6159. }
  6160. }
  6161. else if (name.find("attn_qkv.weight") != std::string::npos) {
  6162. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  6163. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  6164. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  6165. }
  6166. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  6167. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  6168. }
  6169. // This can be used to reduce the size of the Q5_K_S model.
  6170. // The associated PPL increase is fully in line with the size reduction
  6171. //else {
  6172. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  6173. //}
  6174. bool convert_incompatible_tensor = false;
  6175. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  6176. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  6177. int nx = tensor->ne[0];
  6178. int ny = tensor->ne[1];
  6179. if (nx % QK_K != 0) {
  6180. 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));
  6181. convert_incompatible_tensor = true;
  6182. } else {
  6183. ++qs.n_k_quantized;
  6184. }
  6185. }
  6186. if (convert_incompatible_tensor) {
  6187. switch (new_type) {
  6188. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  6189. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  6190. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  6191. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  6192. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  6193. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  6194. }
  6195. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  6196. ++qs.n_fallback;
  6197. }
  6198. return new_type;
  6199. }
  6200. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  6201. ggml_type quantized_type;
  6202. llama_ftype ftype = params->ftype;
  6203. switch (params->ftype) {
  6204. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  6205. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  6206. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  6207. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  6208. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  6209. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  6210. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  6211. // K-quants
  6212. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  6213. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  6214. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  6215. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  6216. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  6217. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  6218. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  6219. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  6220. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  6221. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  6222. }
  6223. int nthread = params->nthread;
  6224. if (nthread <= 0) {
  6225. nthread = std::thread::hardware_concurrency();
  6226. }
  6227. // mmap consistently increases speed Linux, and also increases speed on Windows with
  6228. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  6229. #if defined(__linux__) || defined(_WIN32)
  6230. constexpr bool use_mmap = true;
  6231. #else
  6232. constexpr bool use_mmap = false;
  6233. #endif
  6234. llama_model_loader ml(fname_inp, use_mmap);
  6235. if (ml.use_mmap) {
  6236. ml.mapping.reset(new llama_mmap(&ml.file, /* prefetch */ 0, ggml_is_numa()));
  6237. }
  6238. llama_model model;
  6239. llm_load_arch(ml, model);
  6240. llm_load_hparams(ml, model);
  6241. struct quantize_state_internal qs(model, params);
  6242. if (params->only_copy) {
  6243. ftype = model.ftype;
  6244. }
  6245. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  6246. struct gguf_context * ctx_out = gguf_init_empty();
  6247. // copy the KV pairs from the input file
  6248. gguf_set_kv (ctx_out, ml.ctx_gguf);
  6249. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  6250. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  6251. for (int i = 0; i < ml.n_tensors; ++i) {
  6252. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  6253. const std::string name = ggml_get_name(meta);
  6254. // TODO: avoid hardcoded tensor names - use the TN_* constants
  6255. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  6256. ++qs.n_attention_wv;
  6257. }
  6258. else if (name.find("ffn_down.weight") != std::string::npos) {
  6259. ++qs.n_feed_forward_w2;
  6260. }
  6261. }
  6262. if (qs.n_attention_wv != qs.n_feed_forward_w2 || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  6263. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  6264. __func__, qs.n_attention_wv, qs.n_feed_forward_w2, model.hparams.n_layer);
  6265. }
  6266. size_t total_size_org = 0;
  6267. size_t total_size_new = 0;
  6268. std::vector<int64_t> hist_all(1 << 4, 0);
  6269. std::vector<std::thread> workers;
  6270. workers.reserve(nthread);
  6271. std::mutex mutex;
  6272. int idx = 0;
  6273. std::vector<no_init<uint8_t>> read_data;
  6274. std::vector<no_init<uint8_t>> work;
  6275. std::vector<no_init<float>> f32_conv_buf;
  6276. // populate the original tensors so we get an initial meta data
  6277. for (int i = 0; i < ml.n_tensors; ++i) {
  6278. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  6279. gguf_add_tensor(ctx_out, meta);
  6280. }
  6281. std::ofstream fout(fname_out, std::ios::binary);
  6282. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  6283. const size_t meta_size = gguf_get_meta_size(ctx_out);
  6284. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  6285. // placeholder for the meta data
  6286. ::zeros(fout, meta_size);
  6287. for (int i = 0; i < ml.n_tensors; ++i) {
  6288. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  6289. const std::string name = ggml_get_name(tensor);
  6290. if (!ml.use_mmap) {
  6291. if (read_data.size() < ggml_nbytes(tensor)) {
  6292. read_data.resize(ggml_nbytes(tensor));
  6293. }
  6294. tensor->data = read_data.data();
  6295. }
  6296. ml.load_data_for(tensor);
  6297. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  6298. ++idx, ml.n_tensors,
  6299. ggml_get_name(tensor),
  6300. llama_format_tensor_shape(tensor).c_str(),
  6301. ggml_type_name(tensor->type));
  6302. // This used to be a regex, but <regex> has an extreme cost to compile times.
  6303. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  6304. // quantize only 2D tensors
  6305. quantize &= (tensor->n_dims == 2);
  6306. quantize &= params->quantize_output_tensor || name != "output.weight";
  6307. quantize &= !params->only_copy;
  6308. enum ggml_type new_type;
  6309. void * new_data;
  6310. size_t new_size;
  6311. if (quantize) {
  6312. new_type = quantized_type;
  6313. if (!params->pure) {
  6314. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  6315. }
  6316. // If we've decided to quantize to the same type the tensor is already
  6317. // in then there's nothing to do.
  6318. quantize = tensor->type != new_type;
  6319. }
  6320. if (!quantize) {
  6321. new_type = tensor->type;
  6322. new_data = tensor->data;
  6323. new_size = ggml_nbytes(tensor);
  6324. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  6325. } else {
  6326. const size_t nelements = ggml_nelements(tensor);
  6327. float * f32_data;
  6328. if (tensor->type == GGML_TYPE_F32) {
  6329. f32_data = (float *) tensor->data;
  6330. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  6331. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  6332. } else {
  6333. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  6334. f32_data = (float *) f32_conv_buf.data();
  6335. }
  6336. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  6337. fflush(stdout);
  6338. if (work.size() < nelements * 4) {
  6339. work.resize(nelements * 4); // upper bound on size
  6340. }
  6341. new_data = work.data();
  6342. std::array<int64_t, 1 << 4> hist_cur = {};
  6343. static const int chunk_size = 32 * 512;
  6344. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  6345. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  6346. if (nthread_use < 2) {
  6347. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  6348. } else {
  6349. size_t counter = 0;
  6350. new_size = 0;
  6351. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  6352. std::array<int64_t, 1 << 4> local_hist = {};
  6353. size_t local_size = 0;
  6354. while (true) {
  6355. std::unique_lock<std::mutex> lock(mutex);
  6356. size_t first = counter; counter += chunk_size;
  6357. if (first >= nelements) {
  6358. if (local_size > 0) {
  6359. for (int j=0; j<int(local_hist.size()); ++j) {
  6360. hist_cur[j] += local_hist[j];
  6361. }
  6362. new_size += local_size;
  6363. }
  6364. break;
  6365. }
  6366. lock.unlock();
  6367. size_t last = std::min(nelements, first + chunk_size);
  6368. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  6369. }
  6370. };
  6371. for (int it = 0; it < nthread_use - 1; ++it) {
  6372. workers.emplace_back(compute);
  6373. }
  6374. compute();
  6375. for (auto & w : workers) { w.join(); }
  6376. workers.clear();
  6377. }
  6378. LLAMA_LOG_INFO("size = %8.2f MB -> %8.2f MB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  6379. int64_t tot_count = 0;
  6380. for (size_t i = 0; i < hist_cur.size(); i++) {
  6381. hist_all[i] += hist_cur[i];
  6382. tot_count += hist_cur[i];
  6383. }
  6384. if (tot_count > 0) {
  6385. for (size_t i = 0; i < hist_cur.size(); i++) {
  6386. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  6387. }
  6388. }
  6389. LLAMA_LOG_INFO("\n");
  6390. }
  6391. total_size_org += ggml_nbytes(tensor);
  6392. total_size_new += new_size;
  6393. // update the gguf meta data as we go
  6394. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  6395. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  6396. // write tensor data + padding
  6397. fout.write((const char *) new_data, new_size);
  6398. zeros(fout, GGML_PAD(new_size, align) - new_size);
  6399. }
  6400. // go back to beginning of file and write the updated meta data
  6401. {
  6402. fout.seekp(0);
  6403. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  6404. gguf_get_meta_data(ctx_out, data.data());
  6405. fout.write((const char *) data.data(), data.size());
  6406. }
  6407. fout.close();
  6408. gguf_free(ctx_out);
  6409. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  6410. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  6411. // print histogram for all tensors
  6412. {
  6413. int64_t sum_all = 0;
  6414. for (size_t i = 0; i < hist_all.size(); i++) {
  6415. sum_all += hist_all[i];
  6416. }
  6417. if (sum_all > 0) {
  6418. LLAMA_LOG_INFO("%s: hist: ", __func__);
  6419. for (size_t i = 0; i < hist_all.size(); i++) {
  6420. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  6421. }
  6422. LLAMA_LOG_INFO("\n");
  6423. }
  6424. }
  6425. if (qs.n_fallback > 0) {
  6426. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  6427. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  6428. }
  6429. }
  6430. static int llama_apply_lora_from_file_internal(
  6431. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  6432. ) {
  6433. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  6434. const int64_t t_start_lora_us = ggml_time_us();
  6435. auto fin = std::ifstream(path_lora, std::ios::binary);
  6436. if (!fin) {
  6437. LLAMA_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_lora);
  6438. return 1;
  6439. }
  6440. // verify magic and version
  6441. {
  6442. uint32_t magic;
  6443. fin.read((char *) &magic, sizeof(magic));
  6444. uint32_t format_version;
  6445. fin.read((char *) &format_version, sizeof(format_version));
  6446. if (format_version != 1) {
  6447. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  6448. return 1;
  6449. }
  6450. }
  6451. int32_t lora_r;
  6452. int32_t lora_alpha;
  6453. fin.read((char *) &lora_r, sizeof(lora_r));
  6454. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  6455. float scaling = scale * (float)lora_alpha / (float)lora_r;
  6456. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  6457. // create a temporary ggml context to store the lora tensors
  6458. // todo: calculate size from biggest possible tensor
  6459. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  6460. struct ggml_init_params params;
  6461. params.mem_size = lora_buf.size();
  6462. params.mem_buffer = lora_buf.data();
  6463. params.no_alloc = false;
  6464. ggml_context * lora_ctx = ggml_init(params);
  6465. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  6466. // create a name -> tensor map of the model to accelerate lookups
  6467. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  6468. for (const auto & kv : model.tensors_by_name) {
  6469. model_tensors.insert(kv);
  6470. }
  6471. // load base model
  6472. std::unique_ptr<llama_model_loader> ml;
  6473. ggml_context * base_ctx = NULL;
  6474. std::vector<uint8_t> base_buf;
  6475. if (path_base_model) {
  6476. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  6477. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  6478. size_t ctx_size;
  6479. size_t mmapped_size;
  6480. ml->calc_sizes(ctx_size, mmapped_size);
  6481. base_buf.resize(ctx_size);
  6482. ggml_init_params base_params;
  6483. base_params.mem_size = base_buf.size();
  6484. base_params.mem_buffer = base_buf.data();
  6485. base_params.no_alloc = ml->use_mmap;
  6486. base_ctx = ggml_init(base_params);
  6487. // maybe this should in llama_model_loader
  6488. if (ml->use_mmap) {
  6489. ml->mapping.reset(new llama_mmap(&ml->file, /* prefetch */ 0, ggml_is_numa()));
  6490. }
  6491. }
  6492. // read tensors and apply
  6493. bool warned = false;
  6494. int n_tensors = 0;
  6495. std::vector<uint8_t> work_buffer;
  6496. while (true) {
  6497. int32_t n_dims;
  6498. int32_t length;
  6499. int32_t ftype;
  6500. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  6501. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  6502. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  6503. if (fin.eof()) {
  6504. break;
  6505. }
  6506. int32_t ne[2] = { 1, 1 };
  6507. for (int i = 0; i < n_dims; ++i) {
  6508. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  6509. }
  6510. std::string name;
  6511. {
  6512. char buf[1024];
  6513. fin.read(buf, length);
  6514. name = std::string(buf, length);
  6515. }
  6516. // check for lora suffix and get the type of tensor
  6517. const std::string lora_suffix = ".lora";
  6518. size_t pos = name.rfind(lora_suffix);
  6519. if (pos == std::string::npos) {
  6520. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  6521. return 1;
  6522. }
  6523. std::string lora_type = name.substr(pos + lora_suffix.length());
  6524. std::string base_name = name;
  6525. base_name.erase(pos);
  6526. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  6527. if (model_tensors.find(base_name) == model_tensors.end()) {
  6528. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  6529. return 1;
  6530. }
  6531. // create ggml tensor
  6532. ggml_type wtype;
  6533. switch (ftype) {
  6534. case 0: wtype = GGML_TYPE_F32; break;
  6535. case 1: wtype = GGML_TYPE_F16; break;
  6536. default:
  6537. {
  6538. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  6539. __func__, ftype);
  6540. return false;
  6541. }
  6542. }
  6543. ggml_tensor * lora_tensor;
  6544. if (n_dims == 2) {
  6545. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  6546. }
  6547. else {
  6548. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  6549. return 1;
  6550. }
  6551. ggml_set_name(lora_tensor, "lora_tensor");
  6552. // load tensor data
  6553. size_t offset = fin.tellg();
  6554. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  6555. offset = (offset + 31) & -32;
  6556. fin.seekg(offset);
  6557. fin.read((char*)lora_tensor->data, tensor_data_size);
  6558. lora_tensors[name] = lora_tensor;
  6559. // check if we have both A and B tensors and apply
  6560. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  6561. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  6562. ggml_tensor * dest_t = model_tensors[base_name];
  6563. offload_func_t offload_func = ggml_offload_nop;
  6564. offload_func_t offload_func_force_inplace = ggml_offload_nop;
  6565. #ifdef GGML_USE_CUBLAS
  6566. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  6567. if (dest_t->type != GGML_TYPE_F16) {
  6568. throw std::runtime_error(format(
  6569. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  6570. }
  6571. offload_func = ggml_cuda_assign_buffers;
  6572. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  6573. }
  6574. #endif // GGML_USE_CUBLAS
  6575. ggml_tensor * base_t;
  6576. if (ml) {
  6577. struct gguf_context * ctx_gguf = ml->ctx_gguf;
  6578. // load from base model
  6579. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  6580. // TODO: throw
  6581. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  6582. return 1;
  6583. }
  6584. // TODO: not tested!! maybe not working!
  6585. base_t = ml->create_tensor(base_ctx, base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  6586. ml->load_data_for(base_t);
  6587. } else {
  6588. base_t = dest_t;
  6589. }
  6590. if (ggml_is_quantized(base_t->type)) {
  6591. if (!warned) {
  6592. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  6593. "use a f16 or f32 base model with --lora-base\n", __func__);
  6594. warned = true;
  6595. }
  6596. }
  6597. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  6598. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  6599. ggml_set_name(loraA, "loraA");
  6600. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  6601. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  6602. ggml_set_name(loraB, "loraB");
  6603. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  6604. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  6605. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  6606. return 1;
  6607. }
  6608. // w = w + BA*s
  6609. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  6610. offload_func(BA);
  6611. ggml_set_name(BA, "BA");
  6612. if (scaling != 1.0f) {
  6613. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  6614. ggml_set_name(scale_tensor, "scale_tensor");
  6615. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  6616. offload_func(BA);
  6617. ggml_set_name(BA, "BA_scaled");
  6618. }
  6619. ggml_tensor * r;
  6620. if (base_t == dest_t) {
  6621. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  6622. offload_func_force_inplace(r);
  6623. ggml_set_name(r, "r_add_inplace");
  6624. }
  6625. else {
  6626. r = ggml_add(lora_ctx, base_t, BA);
  6627. offload_func(r);
  6628. ggml_set_name(r, "r_add");
  6629. r = ggml_cpy(lora_ctx, r, dest_t);
  6630. offload_func(r);
  6631. ggml_set_name(r, "r_cpy");
  6632. }
  6633. struct ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  6634. ggml_build_forward_expand(gf, r);
  6635. ggml_graph_compute_helper(work_buffer, gf, n_threads);
  6636. // we won't need these tensors again, reset the context to save memory
  6637. ggml_free(lora_ctx);
  6638. lora_ctx = ggml_init(params);
  6639. lora_tensors.clear();
  6640. n_tensors++;
  6641. if (n_tensors % 4 == 0) {
  6642. LLAMA_LOG_INFO(".");
  6643. }
  6644. }
  6645. }
  6646. // TODO: this should be in a destructor, it will leak on failure
  6647. ggml_free(lora_ctx);
  6648. if (base_ctx) {
  6649. ggml_free(base_ctx);
  6650. }
  6651. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  6652. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  6653. return 0;
  6654. }
  6655. //
  6656. // interface implementation
  6657. //
  6658. struct llama_model_params llama_model_default_params() {
  6659. struct llama_model_params result = {
  6660. /*.n_gpu_layers =*/ 0,
  6661. /*.main_gpu =*/ 0,
  6662. /*.tensor_split =*/ nullptr,
  6663. /*.progress_callback =*/ nullptr,
  6664. /*.progress_callback_user_data =*/ nullptr,
  6665. /*.vocab_only =*/ false,
  6666. /*.use_mmap =*/ true,
  6667. /*.use_mlock =*/ false,
  6668. };
  6669. #ifdef GGML_USE_METAL
  6670. result.n_gpu_layers = 1;
  6671. #endif
  6672. return result;
  6673. }
  6674. struct llama_context_params llama_context_default_params() {
  6675. struct llama_context_params result = {
  6676. /*.seed =*/ LLAMA_DEFAULT_SEED,
  6677. /*.n_ctx =*/ 512,
  6678. /*.n_batch =*/ 512,
  6679. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  6680. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  6681. /*.rope_freq_base =*/ 0.0f,
  6682. /*.rope_freq_scale =*/ 0.0f,
  6683. /*.mul_mat_q =*/ true,
  6684. /*.f16_kv =*/ true,
  6685. /*.logits_all =*/ false,
  6686. /*.embedding =*/ false,
  6687. };
  6688. return result;
  6689. }
  6690. struct llama_model_quantize_params llama_model_quantize_default_params() {
  6691. struct llama_model_quantize_params result = {
  6692. /*.nthread =*/ 0,
  6693. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  6694. /*.allow_requantize =*/ false,
  6695. /*.quantize_output_tensor =*/ true,
  6696. /*.only_copy =*/ false,
  6697. /*.pure =*/ false,
  6698. };
  6699. return result;
  6700. }
  6701. int llama_max_devices(void) {
  6702. return LLAMA_MAX_DEVICES;
  6703. }
  6704. bool llama_mmap_supported(void) {
  6705. return llama_mmap::SUPPORTED;
  6706. }
  6707. bool llama_mlock_supported(void) {
  6708. return llama_mlock::SUPPORTED;
  6709. }
  6710. void llama_backend_init(bool numa) {
  6711. ggml_time_init();
  6712. // needed to initialize f16 tables
  6713. {
  6714. struct ggml_init_params params = { 0, NULL, false };
  6715. struct ggml_context * ctx = ggml_init(params);
  6716. ggml_free(ctx);
  6717. }
  6718. if (numa) {
  6719. ggml_numa_init();
  6720. }
  6721. #ifdef GGML_USE_MPI
  6722. ggml_mpi_backend_init();
  6723. #endif
  6724. }
  6725. void llama_backend_free(void) {
  6726. #ifdef GGML_USE_MPI
  6727. ggml_mpi_backend_free();
  6728. #endif
  6729. }
  6730. int64_t llama_time_us(void) {
  6731. return ggml_time_us();
  6732. }
  6733. struct llama_model * llama_load_model_from_file(
  6734. const char * path_model,
  6735. struct llama_model_params params) {
  6736. ggml_time_init();
  6737. llama_model * model = new llama_model;
  6738. unsigned cur_percentage = 0;
  6739. if (params.progress_callback == NULL) {
  6740. params.progress_callback_user_data = &cur_percentage;
  6741. params.progress_callback = [](float progress, void * ctx) {
  6742. unsigned * cur_percentage_p = (unsigned *) ctx;
  6743. unsigned percentage = (unsigned) (100 * progress);
  6744. while (percentage > *cur_percentage_p) {
  6745. *cur_percentage_p = percentage;
  6746. LLAMA_LOG_INFO(".");
  6747. if (percentage >= 100) {
  6748. LLAMA_LOG_INFO("\n");
  6749. }
  6750. }
  6751. };
  6752. }
  6753. if (!llama_model_load(path_model, *model, params.n_gpu_layers,
  6754. params.main_gpu, params.tensor_split,
  6755. params.use_mmap, params.use_mlock, params.vocab_only,
  6756. params.progress_callback, params.progress_callback_user_data)) {
  6757. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  6758. delete model;
  6759. return nullptr;
  6760. }
  6761. return model;
  6762. }
  6763. void llama_free_model(struct llama_model * model) {
  6764. delete model;
  6765. }
  6766. struct llama_context * llama_new_context_with_model(
  6767. struct llama_model * model,
  6768. struct llama_context_params params) {
  6769. if (!model) {
  6770. return nullptr;
  6771. }
  6772. llama_context * ctx = new llama_context(*model);
  6773. const auto & hparams = model->hparams;
  6774. auto & cparams = ctx->cparams;
  6775. cparams.n_batch = params.n_batch;
  6776. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  6777. cparams.rope_freq_base = params.rope_freq_base == 0 ? hparams.rope_freq_base_train : params.rope_freq_base;
  6778. cparams.rope_freq_scale = params.rope_freq_scale == 0 ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  6779. cparams.n_threads = params.n_threads;
  6780. cparams.n_threads_batch = params.n_threads_batch;
  6781. cparams.mul_mat_q = params.mul_mat_q;
  6782. if (params.seed == LLAMA_DEFAULT_SEED) {
  6783. params.seed = time(NULL);
  6784. }
  6785. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  6786. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  6787. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  6788. ctx->rng = std::mt19937(params.seed);
  6789. ctx->logits_all = params.logits_all;
  6790. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  6791. // reserve memory for context buffers
  6792. if (!hparams.vocab_only) {
  6793. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, cparams.n_ctx, model->n_gpu_layers)) {
  6794. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  6795. llama_free(ctx);
  6796. return nullptr;
  6797. }
  6798. {
  6799. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  6800. LLAMA_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  6801. }
  6802. // resized during inference
  6803. if (params.logits_all) {
  6804. ctx->logits.reserve(cparams.n_ctx*hparams.n_vocab);
  6805. } else {
  6806. ctx->logits.reserve(hparams.n_vocab);
  6807. }
  6808. if (params.embedding){
  6809. ctx->embedding.resize(hparams.n_embd);
  6810. }
  6811. {
  6812. static const size_t tensor_alignment = 32;
  6813. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  6814. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  6815. // create measure allocator
  6816. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  6817. // build worst-case graph
  6818. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  6819. int n_past = cparams.n_ctx - n_tokens;
  6820. 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
  6821. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  6822. #ifdef GGML_USE_METAL
  6823. if (model->n_gpu_layers > 0) {
  6824. ggml_metal_log_set_callback(llama_log_callback_default, NULL);
  6825. ctx->ctx_metal = ggml_metal_init(1);
  6826. if (!ctx->ctx_metal) {
  6827. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  6828. llama_free(ctx);
  6829. return NULL;
  6830. }
  6831. //ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  6832. //ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  6833. }
  6834. #endif
  6835. // measure memory requirements for the graph
  6836. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  6837. LLAMA_LOG_INFO("%s: compute buffer total size = %.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  6838. // recreate allocator with exact memory requirements
  6839. ggml_allocr_free(ctx->alloc);
  6840. ctx->buf_alloc.resize(alloc_size);
  6841. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  6842. #ifdef GGML_USE_METAL
  6843. if (ctx->ctx_metal) {
  6844. //ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  6845. }
  6846. #endif
  6847. #ifdef GGML_USE_CUBLAS
  6848. ggml_cuda_set_scratch_size(alloc_size);
  6849. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
  6850. // calculate total VRAM usage
  6851. auto add_tensor = [](const ggml_tensor * t, size_t & size) {
  6852. if (t->backend == GGML_BACKEND_GPU || t->backend == GGML_BACKEND_GPU_SPLIT) {
  6853. size += ggml_nbytes(t);
  6854. }
  6855. };
  6856. size_t model_vram_size = 0;
  6857. for (const auto & kv : model->tensors_by_name) {
  6858. add_tensor(kv.second, model_vram_size);
  6859. }
  6860. size_t kv_vram_size = 0;
  6861. add_tensor(ctx->kv_self.k, kv_vram_size);
  6862. add_tensor(ctx->kv_self.v, kv_vram_size);
  6863. size_t ctx_vram_size = alloc_size + kv_vram_size;
  6864. size_t total_vram_size = model_vram_size + ctx_vram_size;
  6865. LLAMA_LOG_INFO("%s: total VRAM used: %.2f MB (model: %.2f MB, context: %.2f MB)\n", __func__,
  6866. total_vram_size / 1024.0 / 1024.0,
  6867. model_vram_size / 1024.0 / 1024.0,
  6868. ctx_vram_size / 1024.0 / 1024.0);
  6869. #endif
  6870. }
  6871. #ifdef GGML_USE_METAL
  6872. if (model->n_gpu_layers > 0) {
  6873. // this allocates all Metal resources and memory buffers
  6874. void * data_ptr = NULL;
  6875. size_t data_size = 0;
  6876. if (ctx->model.mapping) {
  6877. data_ptr = ctx->model.mapping->addr;
  6878. data_size = ctx->model.mapping->size;
  6879. } else {
  6880. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  6881. data_size = ggml_get_mem_size (ctx->model.ctx);
  6882. }
  6883. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  6884. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  6885. #define LLAMA_METAL_CHECK_BUF(result) \
  6886. if (!(result)) { \
  6887. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  6888. llama_free(ctx); \
  6889. return NULL; \
  6890. }
  6891. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  6892. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  6893. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  6894. #undef LLAMA_METAL_CHECK_BUF
  6895. }
  6896. #endif
  6897. }
  6898. #ifdef GGML_USE_MPI
  6899. ctx->ctx_mpi = ggml_mpi_init();
  6900. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  6901. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  6902. // TODO: needs fix after #3228
  6903. GGML_ASSERT(false && "not implemented");
  6904. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  6905. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  6906. llama_backend_free();
  6907. exit(1);
  6908. }
  6909. #endif
  6910. return ctx;
  6911. }
  6912. void llama_free(struct llama_context * ctx) {
  6913. delete ctx;
  6914. }
  6915. const llama_model * llama_get_model(const struct llama_context * ctx) {
  6916. return &ctx->model;
  6917. }
  6918. int llama_n_ctx(const struct llama_context * ctx) {
  6919. return ctx->cparams.n_ctx;
  6920. }
  6921. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  6922. return model->vocab.type;
  6923. }
  6924. int llama_n_vocab(const struct llama_model * model) {
  6925. return model->vocab.id_to_token.size();
  6926. }
  6927. int llama_n_ctx_train(const struct llama_model * model) {
  6928. return model->hparams.n_ctx_train;
  6929. }
  6930. int llama_n_embd(const struct llama_model * model) {
  6931. return model->hparams.n_embd;
  6932. }
  6933. float llama_rope_freq_scale_train(const struct llama_model * model) {
  6934. return model->hparams.rope_freq_scale_train;
  6935. }
  6936. int llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  6937. return snprintf(buf, buf_size, "%s %s %s",
  6938. llama_model_arch_name(model->arch).c_str(),
  6939. llama_model_type_name(model->type),
  6940. llama_model_ftype_name(model->ftype).c_str());
  6941. }
  6942. uint64_t llama_model_size(const struct llama_model * model) {
  6943. uint64_t size = 0;
  6944. for (const auto & it : model->tensors_by_name) {
  6945. size += ggml_nbytes(it.second);
  6946. }
  6947. return size;
  6948. }
  6949. uint64_t llama_model_n_params(const struct llama_model * model) {
  6950. uint64_t nparams = 0;
  6951. for (const auto & it : model->tensors_by_name) {
  6952. nparams += ggml_nelements(it.second);
  6953. }
  6954. return nparams;
  6955. }
  6956. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  6957. return ggml_get_tensor(model->ctx, name);
  6958. }
  6959. int llama_model_quantize(
  6960. const char * fname_inp,
  6961. const char * fname_out,
  6962. const llama_model_quantize_params * params) {
  6963. try {
  6964. llama_model_quantize_internal(fname_inp, fname_out, params);
  6965. return 0;
  6966. } catch (const std::exception & err) {
  6967. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  6968. return 1;
  6969. }
  6970. }
  6971. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int n_threads) {
  6972. try {
  6973. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  6974. } catch (const std::exception & err) {
  6975. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  6976. return 1;
  6977. }
  6978. }
  6979. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int n_threads) {
  6980. try {
  6981. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  6982. } catch (const std::exception & err) {
  6983. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  6984. return 1;
  6985. }
  6986. }
  6987. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  6988. return ctx->kv_self.head;
  6989. }
  6990. void llama_kv_cache_clear(struct llama_context * ctx) {
  6991. llama_kv_cache_clear(ctx->kv_self);
  6992. }
  6993. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  6994. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  6995. }
  6996. 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) {
  6997. if (seq_id_src == seq_id_dst) {
  6998. return;
  6999. }
  7000. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  7001. }
  7002. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  7003. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  7004. }
  7005. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  7006. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  7007. }
  7008. // Returns the *maximum* size of the state
  7009. size_t llama_get_state_size(const struct llama_context * ctx) {
  7010. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  7011. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  7012. const size_t s_rng_size = sizeof(size_t);
  7013. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  7014. const size_t s_logits_capacity = sizeof(size_t);
  7015. const size_t s_logits_size = sizeof(size_t);
  7016. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  7017. const size_t s_embedding_size = sizeof(size_t);
  7018. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  7019. const size_t s_kv_size = sizeof(size_t);
  7020. const size_t s_kv_ntok = sizeof(int);
  7021. const size_t s_kv = ctx->kv_self.buf.size;
  7022. const size_t s_total = (
  7023. + s_rng_size
  7024. + s_rng
  7025. + s_logits_capacity
  7026. + s_logits_size
  7027. + s_logits
  7028. + s_embedding_size
  7029. + s_embedding
  7030. + s_kv_size
  7031. + s_kv_ntok
  7032. + s_kv
  7033. );
  7034. return s_total;
  7035. }
  7036. // llama_context_data
  7037. struct llama_data_context {
  7038. virtual void write(const void * src, size_t size) = 0;
  7039. virtual size_t get_size_written() = 0;
  7040. virtual ~llama_data_context() = default;
  7041. };
  7042. struct llama_data_buffer_context : llama_data_context {
  7043. uint8_t * ptr;
  7044. size_t size_written = 0;
  7045. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  7046. void write(const void * src, size_t size) override {
  7047. memcpy(ptr, src, size);
  7048. ptr += size;
  7049. size_written += size;
  7050. }
  7051. size_t get_size_written() override {
  7052. return size_written;
  7053. }
  7054. };
  7055. struct llama_data_file_context : llama_data_context {
  7056. llama_file * file;
  7057. size_t size_written = 0;
  7058. llama_data_file_context(llama_file * f) : file(f) {}
  7059. void write(const void * src, size_t size) override {
  7060. file->write_raw(src, size);
  7061. size_written += size;
  7062. }
  7063. size_t get_size_written() override {
  7064. return size_written;
  7065. }
  7066. };
  7067. /** copy state data into either a buffer or file depending on the passed in context
  7068. *
  7069. * file context:
  7070. * llama_file file("/path", "wb");
  7071. * llama_data_file_context data_ctx(&file);
  7072. * llama_copy_state_data(ctx, &data_ctx);
  7073. *
  7074. * buffer context:
  7075. * std::vector<uint8_t> buf(max_size, 0);
  7076. * llama_data_buffer_context data_ctx(&buf.data());
  7077. * llama_copy_state_data(ctx, &data_ctx);
  7078. *
  7079. */
  7080. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  7081. // copy rng
  7082. {
  7083. std::stringstream rng_ss;
  7084. rng_ss << ctx->rng;
  7085. const size_t rng_size = rng_ss.str().size();
  7086. char rng_buf[LLAMA_MAX_RNG_STATE];
  7087. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  7088. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  7089. data_ctx->write(&rng_size, sizeof(rng_size));
  7090. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  7091. }
  7092. // copy logits
  7093. {
  7094. const size_t logits_cap = ctx->logits.capacity();
  7095. const size_t logits_size = ctx->logits.size();
  7096. data_ctx->write(&logits_cap, sizeof(logits_cap));
  7097. data_ctx->write(&logits_size, sizeof(logits_size));
  7098. if (logits_size) {
  7099. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  7100. }
  7101. // If there is a gap between the size and the capacity, write padding
  7102. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  7103. if (padding_size > 0) {
  7104. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  7105. data_ctx->write(padding.data(), padding_size);
  7106. }
  7107. }
  7108. // copy embeddings
  7109. {
  7110. const size_t embedding_size = ctx->embedding.size();
  7111. data_ctx->write(&embedding_size, sizeof(embedding_size));
  7112. if (embedding_size) {
  7113. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  7114. }
  7115. }
  7116. // copy kv cache
  7117. {
  7118. const auto & kv_self = ctx->kv_self;
  7119. const auto & hparams = ctx->model.hparams;
  7120. const auto & cparams = ctx->cparams;
  7121. const auto n_layer = hparams.n_layer;
  7122. const auto n_embd = hparams.n_embd_gqa();
  7123. const auto n_ctx = cparams.n_ctx;
  7124. const size_t kv_buf_size = kv_self.buf.size;
  7125. const uint32_t kv_head = kv_self.head;
  7126. const uint32_t kv_size = kv_self.size;
  7127. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  7128. data_ctx->write(&kv_head, sizeof(kv_head));
  7129. data_ctx->write(&kv_size, sizeof(kv_size));
  7130. if (kv_buf_size) {
  7131. const size_t elt_size = ggml_element_size(kv_self.k);
  7132. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  7133. ggml_cgraph gf{};
  7134. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_head, n_layer);
  7135. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  7136. kout3d->data = kout3d_data.data();
  7137. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_head, n_embd, n_layer);
  7138. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  7139. vout3d->data = vout3d_data.data();
  7140. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  7141. n_embd, kv_head, n_layer,
  7142. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  7143. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  7144. kv_head, n_embd, n_layer,
  7145. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  7146. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  7147. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  7148. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  7149. ggml_free(cpy_ctx);
  7150. // our data is now in the kout3d_data and vout3d_data buffers
  7151. // write them to file
  7152. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  7153. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  7154. }
  7155. for (uint32_t i = 0; i < kv_size; ++i) {
  7156. const auto & cell = kv_self.cells[i];
  7157. const llama_pos pos = cell.pos;
  7158. const size_t seq_id_size = cell.seq_id.size();
  7159. data_ctx->write(&pos, sizeof(pos));
  7160. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  7161. for (auto seq_id : cell.seq_id) {
  7162. data_ctx->write(&seq_id, sizeof(seq_id));
  7163. }
  7164. }
  7165. }
  7166. }
  7167. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  7168. llama_data_buffer_context data_ctx(dst);
  7169. llama_copy_state_data_internal(ctx, &data_ctx);
  7170. return data_ctx.get_size_written();
  7171. }
  7172. // Sets the state reading from the specified source address
  7173. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  7174. uint8_t * inp = src;
  7175. // set rng
  7176. {
  7177. size_t rng_size;
  7178. char rng_buf[LLAMA_MAX_RNG_STATE];
  7179. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  7180. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  7181. std::stringstream rng_ss;
  7182. rng_ss.str(std::string(&rng_buf[0], rng_size));
  7183. rng_ss >> ctx->rng;
  7184. GGML_ASSERT(!rng_ss.fail());
  7185. }
  7186. // set logits
  7187. {
  7188. size_t logits_cap;
  7189. size_t logits_size;
  7190. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  7191. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  7192. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  7193. if (logits_size) {
  7194. ctx->logits.resize(logits_size);
  7195. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  7196. }
  7197. inp += logits_cap * sizeof(float);
  7198. }
  7199. // set embeddings
  7200. {
  7201. size_t embedding_size;
  7202. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  7203. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  7204. if (embedding_size) {
  7205. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  7206. inp += embedding_size * sizeof(float);
  7207. }
  7208. }
  7209. // set kv cache
  7210. {
  7211. const auto & kv_self = ctx->kv_self;
  7212. const auto & hparams = ctx->model.hparams;
  7213. const auto & cparams = ctx->cparams;
  7214. const int n_layer = hparams.n_layer;
  7215. const int n_embd = hparams.n_embd_gqa();
  7216. const int n_ctx = cparams.n_ctx;
  7217. size_t kv_buf_size;
  7218. uint32_t kv_head;
  7219. uint32_t kv_size;
  7220. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  7221. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  7222. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  7223. if (kv_buf_size) {
  7224. GGML_ASSERT(kv_self.buf.size == kv_buf_size);
  7225. const size_t elt_size = ggml_element_size(kv_self.k);
  7226. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  7227. ggml_cgraph gf{};
  7228. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_head, n_layer);
  7229. kin3d->data = (void *) inp;
  7230. inp += ggml_nbytes(kin3d);
  7231. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_head, n_embd, n_layer);
  7232. vin3d->data = (void *) inp;
  7233. inp += ggml_nbytes(vin3d);
  7234. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  7235. n_embd, kv_head, n_layer,
  7236. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  7237. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  7238. kv_head, n_embd, n_layer,
  7239. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  7240. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  7241. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  7242. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  7243. ggml_free(cpy_ctx);
  7244. }
  7245. ctx->kv_self.head = kv_head;
  7246. ctx->kv_self.size = kv_size;
  7247. ctx->kv_self.cells.resize(kv_size);
  7248. for (uint32_t i = 0; i < kv_size; ++i) {
  7249. llama_pos pos;
  7250. size_t seq_id_size;
  7251. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  7252. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  7253. ctx->kv_self.cells[i].pos = pos;
  7254. llama_seq_id seq_id;
  7255. for (size_t j = 0; j < seq_id_size; ++j) {
  7256. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  7257. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  7258. }
  7259. }
  7260. }
  7261. const size_t nread = inp - src;
  7262. const size_t max_size = llama_get_state_size(ctx);
  7263. GGML_ASSERT(nread <= max_size);
  7264. return nread;
  7265. }
  7266. 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) {
  7267. llama_file file(path_session, "rb");
  7268. // sanity checks
  7269. {
  7270. const uint32_t magic = file.read_u32();
  7271. const uint32_t version = file.read_u32();
  7272. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  7273. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  7274. return false;
  7275. }
  7276. llama_hparams session_hparams;
  7277. file.read_raw(&session_hparams, sizeof(llama_hparams));
  7278. if (session_hparams != ctx->model.hparams) {
  7279. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  7280. return false;
  7281. }
  7282. }
  7283. // load the prompt
  7284. {
  7285. const uint32_t n_token_count = file.read_u32();
  7286. if (n_token_count > n_token_capacity) {
  7287. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  7288. return false;
  7289. }
  7290. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  7291. *n_token_count_out = n_token_count;
  7292. }
  7293. // restore the context state
  7294. {
  7295. const size_t n_state_size_cur = file.size - file.tell();
  7296. const size_t n_state_size_max = llama_get_state_size(ctx);
  7297. if (n_state_size_cur > n_state_size_max) {
  7298. 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);
  7299. return false;
  7300. }
  7301. std::vector<uint8_t> state_data(n_state_size_max);
  7302. file.read_raw(state_data.data(), n_state_size_cur);
  7303. llama_set_state_data(ctx, state_data.data());
  7304. }
  7305. return true;
  7306. }
  7307. 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) {
  7308. try {
  7309. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  7310. } catch (const std::exception & err) {
  7311. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  7312. return false;
  7313. }
  7314. }
  7315. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  7316. llama_file file(path_session, "wb");
  7317. file.write_u32(LLAMA_SESSION_MAGIC);
  7318. file.write_u32(LLAMA_SESSION_VERSION);
  7319. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  7320. // save the prompt
  7321. file.write_u32((uint32_t) n_token_count);
  7322. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  7323. // save the context state using stream saving
  7324. llama_data_file_context data_ctx(&file);
  7325. llama_copy_state_data_internal(ctx, &data_ctx);
  7326. return true;
  7327. }
  7328. int llama_eval(
  7329. struct llama_context * ctx,
  7330. llama_token * tokens,
  7331. int32_t n_tokens,
  7332. int n_past) {
  7333. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  7334. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  7335. if (ret < 0) {
  7336. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  7337. }
  7338. return ret;
  7339. }
  7340. int llama_eval_embd(
  7341. struct llama_context * ctx,
  7342. float * embd,
  7343. int32_t n_tokens,
  7344. int n_past) {
  7345. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  7346. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  7347. const int ret = llama_decode_internal(*ctx, batch);
  7348. if (ret < 0) {
  7349. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  7350. }
  7351. return ret;
  7352. }
  7353. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  7354. ctx->cparams.n_threads = n_threads;
  7355. ctx->cparams.n_threads_batch = n_threads_batch;
  7356. }
  7357. struct llama_batch llama_batch_get_one(
  7358. llama_token * tokens,
  7359. int32_t n_tokens,
  7360. llama_pos pos_0,
  7361. llama_seq_id seq_id) {
  7362. return {
  7363. /*n_tokens =*/ n_tokens,
  7364. /*tokens =*/ tokens,
  7365. /*embd =*/ nullptr,
  7366. /*pos =*/ nullptr,
  7367. /*n_seq_id =*/ nullptr,
  7368. /*seq_id =*/ nullptr,
  7369. /*logits =*/ nullptr,
  7370. /*all_pos_0 =*/ pos_0,
  7371. /*all_pos_1 =*/ 1,
  7372. /*all_seq_id =*/ seq_id,
  7373. };
  7374. }
  7375. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  7376. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  7377. if (embd) {
  7378. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  7379. } else {
  7380. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  7381. }
  7382. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  7383. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  7384. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  7385. for (int i = 0; i < n_tokens; ++i) {
  7386. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  7387. }
  7388. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  7389. return batch;
  7390. }
  7391. void llama_batch_free(struct llama_batch batch) {
  7392. if (batch.token) free(batch.token);
  7393. if (batch.embd) free(batch.embd);
  7394. if (batch.pos) free(batch.pos);
  7395. if (batch.n_seq_id) free(batch.n_seq_id);
  7396. if (batch.seq_id) {
  7397. for (int i = 0; i < batch.n_tokens; ++i) {
  7398. free(batch.seq_id[i]);
  7399. }
  7400. free(batch.seq_id);
  7401. }
  7402. if (batch.logits) free(batch.logits);
  7403. }
  7404. int llama_decode(
  7405. struct llama_context * ctx,
  7406. struct llama_batch batch) {
  7407. const int ret = llama_decode_internal(*ctx, batch);
  7408. if (ret < 0) {
  7409. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  7410. }
  7411. return ret;
  7412. }
  7413. float * llama_get_logits(struct llama_context * ctx) {
  7414. return ctx->logits.data();
  7415. }
  7416. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  7417. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  7418. }
  7419. float * llama_get_embeddings(struct llama_context * ctx) {
  7420. return ctx->embedding.data();
  7421. }
  7422. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  7423. return model->vocab.id_to_token[token].text.c_str();
  7424. }
  7425. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  7426. return model->vocab.id_to_token[token].score;
  7427. }
  7428. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  7429. return model->vocab.id_to_token[token].type;
  7430. }
  7431. llama_token llama_token_bos(const struct llama_model * model) {
  7432. return model->vocab.special_bos_id;
  7433. }
  7434. llama_token llama_token_eos(const struct llama_model * model) {
  7435. return model->vocab.special_eos_id;
  7436. }
  7437. llama_token llama_token_nl(const struct llama_model * model) {
  7438. return model->vocab.linefeed_id;
  7439. }
  7440. llama_token llama_token_prefix(const struct llama_model * model) {
  7441. return model->vocab.special_prefix_id;
  7442. }
  7443. llama_token llama_token_middle(const struct llama_model * model) {
  7444. return model->vocab.special_middle_id;
  7445. }
  7446. llama_token llama_token_suffix(const struct llama_model * model) {
  7447. return model->vocab.special_suffix_id;
  7448. }
  7449. llama_token llama_token_eot(const struct llama_model * model) {
  7450. return model->vocab.special_eot_id;
  7451. }
  7452. int llama_tokenize(
  7453. const struct llama_model * model,
  7454. const char * text,
  7455. int text_len,
  7456. llama_token * tokens,
  7457. int n_max_tokens,
  7458. bool add_bos,
  7459. bool special) {
  7460. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  7461. if (n_max_tokens < (int) res.size()) {
  7462. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  7463. return -((int) res.size());
  7464. }
  7465. for (size_t i = 0; i < res.size(); i++) {
  7466. tokens[i] = res[i];
  7467. }
  7468. return res.size();
  7469. }
  7470. static std::string llama_decode_text(const std::string & text) {
  7471. std::string decoded_text;
  7472. auto unicode_sequences = codepoints_from_utf8(text);
  7473. for (auto& unicode_sequence : unicode_sequences) {
  7474. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  7475. }
  7476. return decoded_text;
  7477. }
  7478. // does not write null-terminator to buf
  7479. int llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int length) {
  7480. if (0 <= token && token < llama_n_vocab(model)) {
  7481. switch (llama_vocab_get_type(model->vocab)) {
  7482. case LLAMA_VOCAB_TYPE_SPM: {
  7483. if (llama_is_normal_token(model->vocab, token)) {
  7484. std::string result = model->vocab.id_to_token[token].text;
  7485. llama_unescape_whitespace(result);
  7486. if (length < (int) result.length()) {
  7487. return -result.length();
  7488. }
  7489. memcpy(buf, result.c_str(), result.length());
  7490. return result.length();
  7491. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  7492. if (length < 3) {
  7493. return -3;
  7494. }
  7495. memcpy(buf, "\xe2\x96\x85", 3);
  7496. return 3;
  7497. } else if (llama_is_control_token(model->vocab, token)) {
  7498. ;
  7499. } else if (llama_is_byte_token(model->vocab, token)) {
  7500. if (length < 1) {
  7501. return -1;
  7502. }
  7503. buf[0] = llama_token_to_byte(model->vocab, token);
  7504. return 1;
  7505. } else {
  7506. // TODO: for now we accept all unsupported token types,
  7507. // suppressing them like CONTROL tokens.
  7508. // GGML_ASSERT(false);
  7509. }
  7510. break;
  7511. }
  7512. case LLAMA_VOCAB_TYPE_BPE: {
  7513. if (llama_is_normal_token(model->vocab, token)) {
  7514. std::string result = model->vocab.id_to_token[token].text;
  7515. result = llama_decode_text(result);
  7516. if (length < (int) result.length()) {
  7517. return -result.length();
  7518. }
  7519. memcpy(buf, result.c_str(), result.length());
  7520. return result.length();
  7521. } else if (llama_is_control_token(model->vocab, token)) {
  7522. ;
  7523. } else {
  7524. // TODO: for now we accept all unsupported token types,
  7525. // suppressing them like CONTROL tokens.
  7526. // GGML_ASSERT(false);
  7527. }
  7528. break;
  7529. }
  7530. default:
  7531. GGML_ASSERT(false);
  7532. }
  7533. }
  7534. return 0;
  7535. }
  7536. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  7537. struct llama_timings result = {
  7538. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  7539. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  7540. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  7541. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  7542. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  7543. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  7544. /*.n_sample =*/ std::max(1, ctx->n_sample),
  7545. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  7546. /*.n_eval =*/ std::max(1, ctx->n_eval),
  7547. };
  7548. return result;
  7549. }
  7550. void llama_print_timings(struct llama_context * ctx) {
  7551. const llama_timings timings = llama_get_timings(ctx);
  7552. LLAMA_LOG_INFO("\n");
  7553. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  7554. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  7555. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  7556. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  7557. __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);
  7558. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  7559. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  7560. LLAMA_LOG_INFO("%s: total time = %10.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  7561. }
  7562. void llama_reset_timings(struct llama_context * ctx) {
  7563. ctx->t_start_us = ggml_time_us();
  7564. ctx->t_sample_us = ctx->n_sample = 0;
  7565. ctx->t_eval_us = ctx->n_eval = 0;
  7566. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  7567. }
  7568. const char * llama_print_system_info(void) {
  7569. static std::string s;
  7570. s = "";
  7571. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  7572. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  7573. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  7574. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  7575. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  7576. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  7577. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  7578. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  7579. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  7580. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  7581. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  7582. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  7583. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  7584. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  7585. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  7586. return s.c_str();
  7587. }
  7588. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  7589. fprintf(stream, "\n");
  7590. fprintf(stream, "###########\n");
  7591. fprintf(stream, "# Timings #\n");
  7592. fprintf(stream, "###########\n");
  7593. fprintf(stream, "\n");
  7594. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  7595. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  7596. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  7597. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  7598. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  7599. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  7600. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  7601. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  7602. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  7603. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  7604. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  7605. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  7606. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  7607. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  7608. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  7609. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  7610. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  7611. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  7612. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  7613. }
  7614. // For internal test use
  7615. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  7616. struct llama_context * ctx
  7617. ) {
  7618. return ctx->model.tensors_by_name;
  7619. }
  7620. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  7621. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  7622. g_state.log_callback_user_data = user_data;
  7623. }
  7624. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  7625. va_list args_copy;
  7626. va_copy(args_copy, args);
  7627. char buffer[128];
  7628. int len = vsnprintf(buffer, 128, format, args);
  7629. if (len < 128) {
  7630. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  7631. } else {
  7632. char* buffer2 = new char[len+1];
  7633. vsnprintf(buffer2, len+1, format, args_copy);
  7634. buffer2[len] = 0;
  7635. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  7636. delete[] buffer2;
  7637. }
  7638. va_end(args_copy);
  7639. }
  7640. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  7641. va_list args;
  7642. va_start(args, format);
  7643. llama_log_internal_v(level, format, args);
  7644. va_end(args);
  7645. }
  7646. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  7647. (void) level;
  7648. (void) user_data;
  7649. fputs(text, stderr);
  7650. fflush(stderr);
  7651. }