llama.cpp 300 KB

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