llama.cpp 377 KB

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