llama.cpp 373 KB

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