llama.cpp 323 KB

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