llama.cpp 371 KB

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