llama.cpp 392 KB

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