llama.cpp 338 KB

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